ECDSA example to create and verify a digital signature
The following packages are used to perform hashing, ECC key creation, and signature creation and verification:
from Crypto.Hash import SHA256 from Crypto.PublicKey import ECC from Crypto.Signature import DSS
The key is generated on the secp256k1 elliptical curve using the ECC.generate method, and both public and private keys are exported:
key = ECC.generate(curve='P-256') with open('ecc.pub', 'wt') as f: f.write(key.public_key().export_key(format='PEM')) with open('ecc.pem', 'wt') as f: f.write(key.export_key(format='PEM'))
Messages that need to be signed are hashed using the SHA256 algorithm, and then a signer object is created using the DSS package by providing a private key. The hashed message is then signed by the owner:
message = b'ECDSA message for signature' key = ECC.import_key(open('ecc.pem').read()) h = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(h)
Signature verification in the following code is similar to that of signing. The received message is hashed initially since the hashing was performed at the sender side as well. The distributed public key is imported and used to create a new DSS object for verification. The hashed message and the received signature are used for verification. The verify function throws a ValueError if the message or signature was tampered with:
h = SHA256.new(message) key = ECC.import_key(open('ecc.pub').read()) verifier = DSS.new(key, 'fips-186-3') try: verifier.verify(h, signature) print("The message is authentic.") except ValueError: print("The message is not authentic.")