def sign(self, data): ecdsa_sig = None try: # Hash and apply ECDSA hashBuf = bytesToC(Digest.SHA256(data)) ecdsa_sig = o.ECDSA_do_sign(hashBuf, 32, self.ec_key) # Encode the signature into 64 bytes rBuf = bytesToC(bytearray(32)) sBuf = bytesToC(bytearray(32)) rLen = o.BN_bn2bin(ecdsa_sig.contents.r, rBuf) sLen = o.BN_bn2bin(ecdsa_sig.contents.s, sBuf) rBytes = bytearray(32-rLen) + cToBytes(rBuf)[:rLen] sBytes = bytearray(32-sLen) + cToBytes(sBuf)[:sLen] sigBytes = rBytes + sBytes assert(len(sigBytes) == 64) finally: if ecdsa_sig: o.ECDSA_SIG_free(ecdsa_sig) # Double-check the signature before returning assert(OpenSSL_ECPublicKey(self.rawPublicKey).verify(data, sigBytes)) return sigBytes
def sign(self, data): ecdsa_sig = None try: # Hash and apply ECDSA hashBuf = bytesToC(Digest.SHA256(data)) ecdsa_sig = o.ECDSA_do_sign(hashBuf, 32, self.ec_key) # Encode the signature into 64 bytes rBuf = bytesToC(bytearray(32)) sBuf = bytesToC(bytearray(32)) rLen = o.BN_bn2bin(ecdsa_sig.contents.r, rBuf) sLen = o.BN_bn2bin(ecdsa_sig.contents.s, sBuf) rBytes = bytearray(32 - rLen) + cToBytes(rBuf)[:rLen] sBytes = bytearray(32 - sLen) + cToBytes(sBuf)[:sLen] sigBytes = rBytes + sBytes assert (len(sigBytes) == 64) finally: if ecdsa_sig: o.ECDSA_SIG_free(ecdsa_sig) # Double-check the signature before returning assert (OpenSSL_ECPublicKey(self.rawPublicKey).verify(data, sigBytes)) return sigBytes
def generateECKeyPair(): ec_key, ec_group = None, None try: # Generate the new key ec_key = o.EC_KEY_new_by_curve_name(o.OBJ_txt2nid(b"prime256v1")) o.EC_KEY_generate_key(ec_key) # Extract the key's public and private values as strings # into pubBuf and privBuf pubBuf = bytesToC(bytearray(1+64)) # [0x04] ... privBuf = bytesToC(bytearray(32)) ec_point = o.EC_KEY_get0_public_key(ec_key) ec_group = o.EC_GROUP_new_by_curve_name(o.OBJ_txt2nid(b"prime256v1")) o.EC_POINT_point2oct(ec_group, ec_point, o.POINT_CONVERSION_UNCOMPRESSED, pubBuf, 65, None) bignum = o.EC_KEY_get0_private_key(ec_key) privLen = o.BN_bn2bin(bignum, privBuf) # Convert the public and private keys into fixed-length 64 and 32 byte arrays # Leading zeros are added to priv key, leading byte (0x04) stripped from pub key rawPublicKey = cToBytes(pubBuf)[1:65] rawPrivateKey = bytearray(32-privLen) + (cToBytes(privBuf)[:privLen]) # Test signing and verification with the new key # sign() does a verify() internally pub = OpenSSL_ECPublicKey(rawPublicKey) priv = OpenSSL_ECPrivateKey(rawPrivateKey, rawPublicKey) priv.sign(b"test") return (pub, priv) finally: if ec_key: o.EC_KEY_free(ec_key) if ec_group: o.EC_GROUP_free(ec_group)