Exemplo n.º 1
0
    def setUp(self):
        comps = "Cryptodome.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, "dsa_test.json"), "rt") as file_in:
            tv_tree = json.load(file_in)

        self.tv = []

        for group in tv_tree['testGroups']:
            key = DSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "DSAVer"
            
            from collections import namedtuple
            TestVector = namedtuple('TestVector', 'id comment msg sig key hash_module valid warning')

            for test in group['tests']:
                tv = TestVector(
                    test['tcId'],
                    test['comment'],
                    unhexlify(test['msg']),
                    unhexlify(test['sig']),
                    key,
                    hash_module,
                    test['result'] != "invalid",
                    test['result'] == "acceptable"
                )
                self.tv.append(tv)
Exemplo n.º 2
0
    def setUp(self):
        comps = "Cryptodome.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, "dsa_test.json"), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            key = DSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "DSAVer"
            
            for test in group['tests']:
                tv = TestVector()
                
                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
Exemplo n.º 3
0
def generate_dsa(key, nonce_or_iv):
    dsa_key = DSA.import_key(key)
    signer = DSS.new(dsa_key, 'fips-186-3')

    def do_computation(msg: bytes):
        h = SHA256.new(msg)
        signature = signer.sign(h)

    return do_computation
Exemplo n.º 4
0
    def test_import_key(self):
        """Verify importKey is an alias to import_key"""

        key_obj = DSA.import_key(self.der_public)
        self.failIf(key_obj.has_private())
        self.assertEqual(self.y, key_obj.y)
        self.assertEqual(self.p, key_obj.p)
        self.assertEqual(self.q, key_obj.q)
        self.assertEqual(self.g, key_obj.g)
Exemplo n.º 5
0
    def test_import_key(self):
        """Verify importKey is an alias to import_key"""

        key_obj = DSA.import_key(self.der_public)
        self.failIf(key_obj.has_private())
        self.assertEqual(self.y, key_obj.y)
        self.assertEqual(self.p, key_obj.p)
        self.assertEqual(self.q, key_obj.q)
        self.assertEqual(self.g, key_obj.g)
def sign_data(data):
    '''
    param: string to be signed
    return: base64 encoded signature
    '''
    f_key = open(private_key_loc).read()
    key = DSA.import_key(f_key, passphrase=secret)
    hash_obj = SHA256.new(data.encode('utf-8'))
    signer = DSS.new(key, 'fips-186-3')
    signature = signer.sign(hash_obj)
    return b64encode(signature)
Exemplo n.º 7
0
 def test_nonce_reuse_importkey():
     secret_key = """-----BEGIN PRIVATE KEY-----
                 MIIBSwIBADCCASsGByqGSM44BAEwggEeAoGBAIAAAAAAAAAARApDBH1CEeZPeIM9
                 mMb6l3FyY8+AOy+cdiDzCaqlkIRVIRRxvnCH5oJ6gkinosGscZMTgF7IwQJzDHFm
                 oxvVdpACrj5Je+kpF6djefAbe+ByZ4FowkGq1EdMZF8aZzsik3CFkEA/vDsjvAsg
                 XmKRvOnFHkkFuKCRAhUA/+rcmBQ71NBsDzkbusi6NQpTNF8CgYAFVt8xSXTiCGn8
                 +bqWyoX+gjItArrT28o6fGnq+apjwasvWDHq1FETk/gwqTbTwWTiMo2eOTImRKDF
                 MbK1us+DjhloAUuhL6nCRQhsLs4Jq+8A/y7aol/HjCz1fHRKKDD9wqKDf2kWdI97
                 Kb2Hq4AUoJWTCT0ijX+oQJafbywjdwQXAhUAniK/kyRv/SFd1uJjuDMh0EntMws=
                 -----END PRIVATE KEY-----"""
     return TestDsa.test_nonce_reuse(DSA.import_key(secret_key))
Exemplo n.º 8
0
def DSA_3072(file_name):
    print()
    print('DSA 3072 for ' + file_name + ':   ')
    #KEY GENERATION
    t1 = datetime.now()
    key = DSA.generate(3072)
    t2 = datetime.now()
    key_speed = t2 - t1
    print('TIME TAKEN FOR KEY GENERATION:(micro seconds)    ' +
          str(key_speed.microseconds))
    f = open("DSA3072_CSE565.pem", "wb")
    f.write(key.publickey().export_key())
    f.close()
    #SIGNING
    with open(file_name + ".txt", "r") as myfile:
        data = myfile.read()
    plaintext = bytes(data, 'utf-8')
    hash_gen = SHA256.new(plaintext)
    signer = DSS.new(key, 'fips-186-3')
    t1 = datetime.now()
    signature = signer.sign(hash_gen)
    t2 = datetime.now()
    sign_time = t2 - t1
    print('TIME TAKEN TO SIGN:(micro seconds)    ' +
          str(sign_time.microseconds))
    #VERIFIER
    f = open("DSA3072_CSE565.pem", "r")
    hash_gen = SHA256.new(plaintext)
    public_key = DSA.import_key(f.read())
    verifier = DSS.new(public_key, 'fips-186-3')
    try:
        t1 = datetime.now()
        verifier.verify(hash_gen, signature)
        t2 = datetime.now()
        verify_time = t2 - t1
        print('TIME TAKEN TO VERIFY:(micro seconds)    ' +
              str(verify_time.microseconds))
        print("THE SIGNATURE MATCHES!   The message is authentic")
    except ValueError:
        print("The message is not authentic.")
    statinfo = os.stat(file_name + ".txt")
    size = statinfo.st_size
    sign_byte = sign_time.microseconds / size
    verify_byte = verify_time.microseconds / size
    print("TIME TO SIGN PER BYTE:   " + str(sign_byte))
    print("TIME TO VERIFY PER BYTE:   " + str(verify_byte))
Exemplo n.º 9
0
    def setUp(self):
        file_in = open(
            pycryptodome_filename(
                "Cryptodome.SelfTest.Signature.test_vectors.wycheproof".split(
                    "."), "dsa_test.json"), "rt")
        tv_tree = json.load(file_in)

        class TestVector(object):
            pass

        self.tv = []

        for group in tv_tree['testGroups']:
            key = DSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "DSAVer"

            for test in group['tests']:
                tv = TestVector()

                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
from Cryptodome.Signature import DSS
from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import DSA
from base64 import b64encode

secret = "Change this to something unguessable!"
# Read secret key
f_key = open('./secret_key.pem').read()
key = DSA.import_key(f_key, passphrase=secret)

# Create message hash
message = b"2017-12-19T10:59:50.797961"
hash_obj = SHA256.new(message)
print('hash: ', b64encode(hash_obj.digest()))

# Sign the message hash
signer = DSS.new(key, 'fips-186-3')
signature = signer.sign(hash_obj)
print('signature: ', b64encode(signature))

# Load the public key
f = open("public_key.pem", "r")
pub_key = DSA.import_key(f.read())

# Create the hash again for verification
check_hash_obj = SHA256.new(message)
print('check_hash: ', b64encode(check_hash_obj.digest()))

# Verify the authenticity of the message
verifier = DSS.new(key, 'fips-186-3')
try:
Exemplo n.º 11
0
 def filter_dsa(group):
     return DSA.import_key(group['keyPem'])
def sign_data(data, key):
    '''
    param: string to be signed
    return: base64 encoded signature
    '''
    hash_obj = SHA256.new(data.encode('utf-8'))
    signer = DSS.new(key, 'fips-186-3')
    signature = signer.sign(hash_obj)
    return b64encode(signature)


app = Flask(__name__)
secret = "Change this to something unguessable!"
secret_key = os.environ.get('secret_key')
key = DSA.import_key(secret_key, passphrase=secret)


@app.route('/')
def index():
    timestamp = datetime.datetime.utcnow().isoformat()
    t_signature = sign_data(timestamp, key).decode('utf-8')
    data = {
        'output': 'Signed timestamp',
        'timestamp': timestamp,
        'signature': t_signature
    }
    resp = Response(json.dumps(data))
    resp.headers['Content-Type'] = 'application/json'
    return resp
Exemplo n.º 13
0
from Cryptodome.Signature import DSS
from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import DSA
from base64 import b64decode
import json

# Load the public key
f = open('public_key.pem', 'r')
pub_key = DSA.import_key(f.read())

# Read JSON input
json_string = '{"output": "Signed timestamp", "timestamp": "2017-12-19T14:07:39.149933", "signature": "qJVvJcBTUxpv63chyx3dCt43YueMe4fF8/G/qsRHbriSflkHIfUIgSM6rCy387Hx811zxHXSs34="}'
parsed_json = json.loads(json_string)
timestamp = parsed_json['timestamp']
print('timestamp: ', timestamp)
signature = parsed_json['signature']
print('signature: ', signature)

# Create the hash for verification
hash_obj = SHA256.new(timestamp.encode('utf-8'))
print('hash: ', hash_obj.digest())

# Verify the authenticity of the message
verifier = DSS.new(pub_key, 'fips-186-3')
try:
    verifier.verify(hash_obj, b64decode(signature))
    print('The message is authentic.')
except ValueError:
    print('Message failed authentication!')