Python Crypto Libraries

Python Crypto Libraries

...

Cryptography in Python

    Hashes, ECC and ECDSA, eth_keys Library

ECDSA in Python: Generate / Load Keys

1
import eth_keys, eth_utils, binascii, os
2
3
# privKey = eth_keys.keys.PrivateKey(os.urandom(32))
4
privKey = eth_keys.keys.PrivateKey(binascii.unhexlify(
5
'97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a'))
6
pubKey = privKey.public_key
7
pubKeyCompressed = '0' + str(2 + int(pubKey) % 2) + str(pubKey)[2:66]
8
address = pubKey.to_checksum_address()
9
print('Private key (64 hex digits):', privKey)
10
print('Public key (plain, 128 hex digits):', pubKey)
11
print('Public key (compressed):', pubKeyCompressed)
12
print('Signer address:', address)
Copied!

ECDSA in Python: Sign Message

1
msg = b'Message for signing'
2
msgHash = eth_utils.keccak(msg)
3
signature = privKey.sign_msg(msg)
4
5
print('Msg:', msg)
6
print('Msg hash:', binascii.hexlify(msgHash))
7
print('Signature: [v = {0}, r = {1}, s = {2}]'.format(
8
hex(signature.v), hex(signature.r), hex(signature.s)))
9
print('Signature (130 hex digits):', signature)
Copied!

ECDSA in Python: Verify Signature

1
msg = b'Message for signing'
2
msgSigner = '0xa44f70834a711F0DF388ab016465f2eEb255dEd0'
3
signature = eth_keys.keys.Signature(binascii.unhexlify(
4
'6f0156091cbe912f2d5d1215cc3cd81c0963c8839b93af60e0921b61a19c54300c71006dd93f3508c432daca21db0095f4b16542782b7986f48a5d0ae3c583d401'))
5
signerPubKey = signature.recover_public_key_from_msg(msg)
6
print('Signer public key (recovered):', signerPubKey)
7
signerAddress = signerPubKey.to_checksum_address()
8
print('Signer address:', signerAddress)
9
print('Signature valid?:', signerAddress == msgSigner)
Copied!
Last modified 11d ago