|
| 1 | +import secp256k1 |
| 2 | +import hashlib |
| 3 | +from binascii import hexlify |
| 4 | + |
| 5 | +def secp256k1_example(): |
| 6 | + """Usage example for secp256k1 usermodule""" |
| 7 | + |
| 8 | + # randomize context from time to time |
| 9 | + # - it helps against sidechannel attacks |
| 10 | + # secp256k1.context_randomize(os.urandom(32)) |
| 11 | + |
| 12 | + # some random secret key |
| 13 | + secret = hashlib.sha256(b"secret key").digest() |
| 14 | + |
| 15 | + print("Secret key:", hexlify(secret).decode()) |
| 16 | + |
| 17 | + # Makes sense to check if secret key is valid. |
| 18 | + # It will be ok in most cases, only if secret > N it will be invalid |
| 19 | + if not secp256k1.ec_seckey_verify(secret): |
| 20 | + raise ValueError("Secret key is invalid") |
| 21 | + |
| 22 | + # computing corresponding pubkey |
| 23 | + pubkey = secp256k1.ec_pubkey_create(secret) |
| 24 | + |
| 25 | + # serialize the pubkey in compressed format |
| 26 | + sec = secp256k1.ec_pubkey_serialize(pubkey, secp256k1.EC_COMPRESSED) |
| 27 | + print("Public key:", hexlify(sec).decode()) |
| 28 | + |
| 29 | + # this is how you parse the pubkey |
| 30 | + pubkey = secp256k1.ec_pubkey_parse(sec) |
| 31 | + |
| 32 | + # Signature generation: |
| 33 | + |
| 34 | + # hash of the string "hello" |
| 35 | + msg = hashlib.sha256(b"hello").digest() |
| 36 | + # signing |
| 37 | + sig = secp256k1.ecdsa_sign(msg, secret) |
| 38 | + |
| 39 | + # serialization |
| 40 | + der = secp256k1.ecdsa_signature_serialize_der(sig) |
| 41 | + |
| 42 | + print("Signature:", hexlify(der).decode()) |
| 43 | + |
| 44 | + # verification |
| 45 | + if secp256k1.ecdsa_verify(sig, msg, pubkey): |
| 46 | + print("Signature is valid") |
| 47 | + else: |
| 48 | + printf("Invalid signature") |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + secp256k1_example() |
0 commit comments