def pubkey(self, compress=True): if compress: return point_compress(self.point()).encode('hex') x_str = util.number_to_string(self.point().x(), SECP256k1.order) y_str = util.number_to_string(self.point().y(), SECP256k1.order) return x_str + y_str
def to_extended_key(self, include_prv=False): if not self.__testnet: version = 0x0488B21E if not include_prv else 0x0488ADE4 else: version = 0x043587CF if not include_prv else 0x04358394 version = util.number_to_string(version, 2**32-1) depth = util.number_to_string(self.__depth, 2**8-1) parentfp = self.parentfp() childnum = util.number_to_string(self.__childnum, 2**32-1) chaincode = self.__chain if include_prv: if self.__prvkey == None: raise Exception('private key unkown') data = '\x00' + util.number_to_string(self.__prvkey, SECP256k1.order) else: # compress point data = point_compress(self.point()) import base58 ekdata = ''.join([version, depth, parentfp, childnum, chaincode, data]) checksum=hashlib.sha256(hashlib.sha256(ekdata).digest()).digest()[:4] return base58.b58encode(ekdata + checksum)
def to_sec(vk, compressed=True): """Convert verifying key to the SEC binary format (as used by OpenSSL).""" # based on code from https://github.com/richardkiss/pycoin order = vk.pubkey.order x_str = number_to_string(vk.pubkey.point.x(), order) if compressed: if vk.pubkey.point.y() & 1: return b("\x03") + x_str else: return b("\x02") + x_str else: y_str = number_to_string(vk.pubkey.point.y(), order) return b("\x04") + x_str + y_str
def add_mod_n(d, c): assert len(d) == 32 # Truncate prefix byte order = generator_secp256k1.order() d = string_to_number(d) c = string_to_number(c) return number_to_string((d + c) % order, order)
def _get_subnode(cls, node, i): # Child key derivation (CKD) algorithm of BIP32 i_as_bytes = struct.pack(">L", i) if cls.is_prime(i): # Prime derivation data = '\0' + node.private_key + i_as_bytes I64 = hmac.HMAC(key=node.chain_code, msg=data, digestmod=hashlib.sha512).digest() else: # Public derivation data = node.public_key + i_as_bytes I64 = hmac.HMAC(key=node.chain_code, msg=data, digestmod=hashlib.sha512).digest() I_left_as_exponent = string_to_number(I64[:32]) secexp = (I_left_as_exponent + string_to_number(node.private_key)) % SECP256k1.order if I_left_as_exponent >= SECP256k1.order: raise Exception("Il cannot be bigger than order") if secexp == 0: raise Exception("secexp cannot be zero") node_out = types.HDNodeType() node_out.depth = node.depth + 1 node_out.child_num = i node_out.chain_code = I64[32:] node_out.private_key = number_to_string(secexp, SECP256k1.order) node_out.public_key = cls._get_pubkey(node_out.private_key) node_out.fingerprint = bip32_fingerprint(node.public_key) return node_out
def test_crypto(): G = generator_secp256k1 _r = G.order() pvk = ecdsa.util.randrange(pow(2, 256)) % _r Pub = pvk * G pubkey_c = point_to_ser(Pub, True) pubkey_u = point_to_ser(Pub, False) addr_c = public_key_to_bc_address(pubkey_c) addr_u = public_key_to_bc_address(pubkey_u) print "Private key ", "%064x" % pvk print "Compressed public key ", pubkey_c.encode("hex") print "Uncompressed public key", pubkey_u.encode("hex") message = "Chancellor on brink of second bailout for banks" enc = EC_KEY.encrypt_message(message, pubkey_c) eck = EC_KEY(number_to_string(pvk, _r)) dec = eck.decrypt_message(enc) print "decrypted", dec signature = eck.sign_message(message, True, addr_c) print signature EC_KEY.verify_message(addr_c, signature, message)
def _do_test_crypto(self, message): G = generator_secp256k1 _r = G.order() pvk = ecdsa.util.randrange( pow(2,256) ) %_r Pub = pvk*G pubkey_c = point_to_ser(Pub,True) #pubkey_u = point_to_ser(Pub,False) addr_c = public_key_to_bc_address(pubkey_c) #addr_u = public_key_to_bc_address(pubkey_u) #print "Private key ", '%064x'%pvk eck = EC_KEY(number_to_string(pvk,_r)) #print "Compressed public key ", pubkey_c.encode('hex') enc = EC_KEY.encrypt_message(message, pubkey_c) dec = eck.decrypt_message(enc) assert dec == message #print "Uncompressed public key", pubkey_u.encode('hex') #enc2 = EC_KEY.encrypt_message(message, pubkey_u) dec2 = eck.decrypt_message(enc) assert dec2 == message signature = eck.sign_message(message, True, addr_c) #print signature EC_KEY.verify_message(addr_c, signature, message)
def get_private_key(self, address, password): """ Privatekey(type,n) = Master_private_key + H(n|S|type) """ order = generator_secp256k1.order() if address in self.imported_keys.keys(): b = self.pw_decode( self.imported_keys[address], password ) if not b: return None b = ASecretToSecret( b ) secexp = int( b.encode('hex'), 16) else: if address in self.addresses: n = self.addresses.index(address) for_change = False elif address in self.change_addresses: n = self.change_addresses.index(address) for_change = True else: raise BaseException("unknown address") try: seed = self.pw_decode( self.seed, password) except: raise BaseException("Invalid password") if not seed: return None secexp = self.stretch_key(seed) secexp = ( secexp + self.get_sequence(n,for_change) ) % order pk = number_to_string(secexp,order) return pk
def test_crypto(): G = generator_secp256k1 _r = G.order() pvk = ecdsa.util.randrange(pow(2, 256)) % _r Pub = pvk * G pubkey_c = point_to_ser(Pub, True) pubkey_u = point_to_ser(Pub, False) addr_c = public_key_to_bc_address(pubkey_c) addr_u = public_key_to_bc_address(pubkey_u) print("Private key ", "{0:064x}".format(pvk)) print("Compressed public key ", binascii.hexlify(pubkey_c)) print("Uncompressed public key", binascii.hexlify(pubkey_u)) message = b"Chancellor on brink of second bailout for banks" # enc = EC_KEY.encrypt_message(message,pubkey_c) eck = EC_KEY(number_to_string(pvk, _r)) # dec = eck.decrypt_message(enc) # print("decrypted", dec) signature = eck.sign_message(message, True, addr_c) print(signature) EC_KEY.verify_message(addr_c, signature, message)
def _CKD_priv(k, c, s, is_prime): order = generator_secp256k1.order() keypair = EC_KEY(k) cK = GetPubKey(keypair.pubkey,True) data = chr(0) + k + s if is_prime else cK + s I = hmac.new(c, data, hashlib.sha512).digest() k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order ) c_n = I[32:] return k_n, c_n
def child(self, i): assert( 0 <= i <= 2**32-1) priv_deriv = (i & 0x80000000) != 0 if (priv_deriv and not self.__prvkey): raise Exception('Unable to do private derivation') # only allow up to a depth of 255 assert(self.__depth < 0xff) str_i = util.number_to_string(i, 2**32-1) if priv_deriv: str_k = util.number_to_string(self.__prvkey, SECP256k1.order) deriv = hmac.new(key=self.__chain, msg='\x00' + str_k + str_i, digestmod=hashlib.sha512).digest() else: str_K = point_compress(self.point()) deriv = hmac.new(key=self.__chain, msg=str_K + str_i, digestmod=hashlib.sha512).digest() childChain = deriv[32:] childModifier = util.string_to_number(deriv[:32]) if childModifier >= SECP256k1.order: raise Exception('This is higly unprovable IL >= n, but it did happen') if self.__prvkey: childPrvkey = (self.__prvkey + childModifier) % SECP256k1.order if childPrvkey == 0: raise Exception('This is higly unprovable ki = 0, but it did happen') childKey = childPrvkey else: childPubkey = self.point() + SECP256k1.generator * childModifier if childPubkey == ellipticcurve.INFINITY: raise Exception('This is higly unprovable Ki = INFINITY, but it did happen') childKey = childPubkey return self.__class__(childKey, childChain, testnet=self.__testnet, depth=self.__depth + 1, parentfp=self.fingerprint(), childnum=i)
def CKD(k, c, n): import hmac from ecdsa.util import string_to_number, number_to_string order = generator_secp256k1.order() keypair = EC_KEY(string_to_number(k)) K = GetPubKey(keypair.pubkey,True) I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest() k_n = number_to_string( (string_to_number(I[0:32]) * string_to_number(k)) % order , order ) c_n = I[32:] return k_n, c_n
def CKD(k, c, n): import hmac from ecdsa.util import string_to_number, number_to_string order = generator_secp256k1.order() keypair = EC_KEY(k) K = GetPubKey(keypair.pubkey,True) if n & BIP32_PRIME: # We want to make a "secret" address that can't be determined from K data = chr(0) + k + rev_hex(int_to_hex(n,4)).decode('hex') I = hmac.new(c, data, hashlib.sha512).digest() else: # We want a "non-secret" address that can be determined from K I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest() k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order ) c_n = I[32:] return k_n, c_n
def CKD(k, c, n): import hmac from ecdsa.util import string_to_number, number_to_string order = generator_secp256k1.order() keypair = EC_KEY(string_to_number(k)) K = GetPubKey(keypair.pubkey, True) if n & BIP32_PRIME: data = chr(0) + k + rev_hex(int_to_hex(n, 4)).decode("hex") I = hmac.new(c, data, hashlib.sha512).digest() else: I = hmac.new(c, K + rev_hex(int_to_hex(n, 4)).decode("hex"), hashlib.sha512).digest() k_n = number_to_string((string_to_number(I[0:32]) + string_to_number(k)) % order, order) c_n = I[32:] return k_n, c_n
def __init__(self, key, chain_code: bytes, index: int, depth: int, parent_fingerprint: bytes = b''): if isinstance(key, int): key = util.number_to_string(key, curves.NIST256p.order) private_key = SigningKey.from_string(string=key, curve=curves.NIST256p) super().__init__(private_key, chain_code, index, depth, parent_fingerprint) self._public_key = HDPublicKey( public_key=self._key.verifying_key, chain_code=self._chain_code, index=self._index, depth=self._depth, parent_fingerprint=self._parent_fingerprint)
def encrypt_message(self, message, pubkey): pk = ser_to_point(pubkey) if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()): raise Exception('invalid pubkey') ephemeral_exponent = number_to_string(ecdsa.util.randrange(pow(2,256)), generator_secp256k1.order()) ephemeral = EC_KEY(ephemeral_exponent) ecdh_key = point_to_ser(pk * ephemeral.privkey.secret_multiplier) key = hashlib.sha512(ecdh_key).digest() iv, key_e, key_m = key[0:16], key[16:32], key[32:] ciphertext = aes_encrypt_with_iv(key_e, iv, message) ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode('hex') encrypted = 'BIE1' + ephemeral_pubkey + ciphertext mac = hmac.new(key_m, encrypted, hashlib.sha256).digest() return base64.b64encode(encrypted + mac)
def compress(public_key: bytes): """ This method is avaliable for any curves. The result is a flag (0x02 y is even otherwise 0x03) connecting x with discarding y. :param public_key: public key bytes in uncompressed representation :return: """ order = NIST256p.generator.order() pk_bytes = public_key[1:] pk_obj = VerifyingKey.from_string(pk_bytes, curve=NIST256p) point = pk_obj.pubkey.point flag = bytes([2 + (point.y() & 1)]) x_bytes = number_to_string(point.x(), order) return flag + x_bytes
def encrypt_message(self, message: bytes, magic: bytes = b'BIE1'): """ ECIES encryption/decryption methods; AES-128-CBC with PKCS7 is used as the cipher; hmac-sha256 is used as the mac """ assert_bytes(message) randint = ecdsa.util.randrange(CURVE_ORDER) ephemeral_exponent = number_to_string(randint, CURVE_ORDER) ephemeral = ECPrivkey(ephemeral_exponent) ecdh_key = (self * ephemeral.secret_scalar).get_public_key_bytes(compressed=True) key = hashlib.sha512(ecdh_key).digest() iv, key_e, key_m = key[0:16], key[16:32], key[32:] ciphertext = aes_encrypt_with_iv(key_e, iv, message) ephemeral_pubkey = ephemeral.get_public_key_bytes(compressed=True) encrypted = magic + ephemeral_pubkey + ciphertext mac = hmac_oneshot(key_m, encrypted, hashlib.sha256) return base64.b64encode(encrypted + mac)
def decrypt_with_cbc_mode(cipher_text: bytes, private_key: bytes, iv: bytes, encode_g_tilde: bytes): if not isinstance(private_key, bytes): raise SDKException(ErrorCode.other_error('the length of private key should be 32 bytes.')) if len(private_key) != 32: raise SDKException(ErrorCode.other_error('the length of private key should be 32 bytes.')) str_g_tilde_x = encode_g_tilde[1:33] str_g_tilde_y = encode_g_tilde[33:65] g_tilde_x = string_to_number(str_g_tilde_x) g_tilde_y = string_to_number(str_g_tilde_y) g_tilde = Point(NIST256p.curve, g_tilde_x, g_tilde_y, NIST256p.order) h_tilde = g_tilde * SigningKey.from_string(string=private_key, curve=NIST256p).privkey.secret_multiplier seed = b''.join([encode_g_tilde, number_to_string(h_tilde.x(), NIST256p.order)]) aes_key = pbkdf2(seed, 32) try: plain_text = AESHandler.aes_cbc_decrypt(cipher_text, iv, aes_key) except ValueError as e: raise SDKException(ErrorCode.other_error(e.args[0])) return plain_text
def CKD(k, c, n): import hmac from ecdsa.util import string_to_number, number_to_string order = generator_secp256k1.order() keypair = EC_KEY(string_to_number(k)) K = GetPubKey(keypair.pubkey, True) if n & BIP32_PRIME: data = chr(0) + k + rev_hex(int_to_hex(n, 4)).decode('hex') I = hmac.new(c, data, hashlib.sha512).digest() else: I = hmac.new(c, K + rev_hex(int_to_hex(n, 4)).decode('hex'), hashlib.sha512).digest() k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order, order) c_n = I[32:] return k_n, c_n
def CKD(k, c, n): import hmac from ecdsa.util import string_to_number, number_to_string order = generator_secp256k1.order() keypair = EC_KEY(k) K = GetPubKey(keypair.pubkey, True) if n & BIP32_PRIME: # We want to make a "secret" address that can't be determined from K data = chr(0) + k + rev_hex(int_to_hex(n, 4)).decode('hex') I = hmac.new(c, data, hashlib.sha512).digest() else: # We want a "non-secret" address that can be determined from K I = hmac.new(c, K + rev_hex(int_to_hex(n, 4)).decode('hex'), hashlib.sha512).digest() k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order, order) c_n = I[32:] return k_n, c_n
def decrypt_with_cbc_mode(cipher_text: bytes, private_key: bytes, iv: bytes, encode_g_tilde: bytes): if not isinstance(private_key, bytes): raise CryptoException(CryptoError.invalid_private_key) if len(private_key) != 32: raise CryptoException(CryptoError.invalid_private_key) str_g_tilde_x = encode_g_tilde[1:33] str_g_tilde_y = encode_g_tilde[33:65] g_tilde_x = string_to_number(str_g_tilde_x) g_tilde_y = string_to_number(str_g_tilde_y) g_tilde = Point(SECP256k1.curve, g_tilde_x, g_tilde_y, SECP256k1.order) h_tilde = g_tilde * SigningKey.from_string( string=private_key, curve=SECP256k1).privkey.secret_multiplier seed = b''.join( [encode_g_tilde, number_to_string(h_tilde.x(), SECP256k1.order)]) aes_key = pbkdf2(seed, 32) plain_text = AESHandler.aes_cbc_decrypt(cipher_text, iv, aes_key) return plain_text
def encrypt_message(self, message, pubkey): pk = ser_to_point(pubkey) if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()): raise Exception("invalid pubkey") ephemeral_exponent = number_to_string(ecdsa.util.randrange(pow(2, 256)), generator_secp256k1.order()) ephemeral = EC_KEY(ephemeral_exponent) ecdh_key = (pk * ephemeral.privkey.secret_multiplier).x() ecdh_key = ("%064x" % ecdh_key).decode("hex") key = hashlib.sha512(ecdh_key).digest() key_e, key_m = key[:32], key[32:] iv_ciphertext = aes.encryptData(key_e, message) ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode("hex") encrypted = "BIE1" + ephemeral_pubkey + iv_ciphertext mac = hmac.new(key_m, encrypted, hashlib.sha256).digest() return base64.b64encode(encrypted + mac)
def encrypt_message(self, message: bytes, magic: bytes = b'BIE1', ephemeral= None, encode=base64.b64encode): """ ECIES encryption/decryption methods; AES-256-CBC with PKCS7 is used as the cipher; hmac-sha256 is used as the mac """ assert_bytes(message) if ephemeral is None: randint = ecdsa.util.randrange(CURVE_ORDER) ephemeral_exponent = number_to_string(randint, CURVE_ORDER) ephemeral = ECPrivkey(ephemeral_exponent) else: assert(type(ephemeral) == ECPrivkey) ecdh_key = self.ecdh(ephemeral.secret_scalar) key = hashlib.sha512(ecdh_key).digest() iv = bytes(os.urandom(16)) key_e, key_m = key[0:32], key[32:] ciphertext = aes_encrypt_with_iv(key_e, iv, message) ephemeral_pubkey = ephemeral.get_public_key_bytes(compressed=True) encrypted = magic + ephemeral_pubkey + iv + ciphertext mac = hmac_oneshot(key_m, encrypted, hashlib.sha256) return encode(encrypted + mac)
def generate_decrypt_aes_key(private_key: bytes, encode_g_tilde: bytes): if not isinstance(private_key, bytes): raise SDKException( ErrorCode.other_error( 'the length of private key should be 32 bytes.')) if len(private_key) != 32: raise SDKException( ErrorCode.other_error( 'the length of private key should be 32 bytes.')) str_g_tilde_x = encode_g_tilde[1:33] str_g_tilde_y = encode_g_tilde[33:65] g_tilde_x = string_to_number(str_g_tilde_x) g_tilde_y = string_to_number(str_g_tilde_y) g_tilde = Point(NIST256p.curve, g_tilde_x, g_tilde_y, NIST256p.order) h_tilde = g_tilde * SigningKey.from_string( string=private_key, curve=NIST256p).privkey.secret_multiplier seed = b''.join( [encode_g_tilde, number_to_string(h_tilde.x(), NIST256p.order)]) aes_key = pbkdf2(seed, 32) return aes_key
def get_public_key_by_bytes_private_key(private_key: bytes): if not isinstance(private_key, bytes): raise SDKException( ErrorCode.other_error( 'The type of private key should be bytes.')) if len(private_key) != 32: raise SDKException( ErrorCode.other_error( 'The length of private key should be 32 bytes.')) private_key = SigningKey.from_string(string=private_key, curve=NIST256p) public_key = private_key.get_verifying_key() order = public_key.pubkey.order x_int = public_key.pubkey.point.x() y_int = public_key.pubkey.point.y() x_str = number_to_string(x_int, order) if y_int % 2 == 0: point_str = b''.join([b'\x02', x_str]) else: point_str = b''.join([b'\x03', x_str]) return point_str
def _get_subkey(cls, xprv, i): # Key derivation algorithm of BIP32 if i < 0: i_as_bytes = struct.pack(">l", i) else: i &= 0x7fffffff i |= 0x80000000 i_as_bytes = struct.pack(">L", i) data = b'\0' + xprv.private_key + i_as_bytes I64 = hmac.HMAC(key=xprv.chain_code, msg=data, digestmod=hashlib.sha512).digest() I_left_as_exponent = string_to_number(I64[:32]) secexp = (I_left_as_exponent + string_to_number(xprv.private_key)) % SECP256k1.generator.order() xprv_out = proto.XprvType() xprv_out.version = xprv.version xprv_out.depth = xprv.depth + 1 xprv_out.child_num = i xprv_out.chain_code = I64[32:] xprv_out.private_key = number_to_string(secexp, SECP256k1.generator.order()) return xprv_out
def _do_test_crypto(self, message): G = generator_secp256k1 _r = G.order() pvk = ecdsa.util.randrange(pow(2, 256)) % _r Pub = pvk * G pubkey_c = point_to_ser(Pub, True) # pubkey_u = point_to_ser(Pub,False) public_key_to_p2pkh(pubkey_c) eck = EC_KEY(number_to_string(pvk, _r)) enc = EC_KEY.encrypt_message(message, pubkey_c) dec = eck.decrypt_message(enc) self.assertEqual(message, dec) # enc2 = EC_KEY.encrypt_message(message, pubkey_u) dec2 = eck.decrypt_message(enc) self.assertEqual(message, dec2) signature = eck.sign_message(message, True) # print signature EC_KEY.verify_message(eck, signature, message)
def ec_get_public_key_by_private_key(private_key: bytes, curve_name) -> bytes: if curve_name == Curve.P256: private_key = SigningKey.from_string(string=private_key, curve=curves.NIST256p) verifying_key = private_key.get_verifying_key() order = verifying_key.pubkey.order x_int = verifying_key.pubkey.point.x() y_int = verifying_key.pubkey.point.y() x_str = util.number_to_string(x_int, order) if y_int % 2 == 0: point_str = util.b('\x02') + x_str else: point_str = util.b('\x03') + x_str elif curve_name == Curve.P224: raise SDKException(ErrorCode.unsupported_key_type) elif curve_name == Curve.P384: raise SDKException(ErrorCode.unsupported_key_type) elif curve_name == Curve.P521: raise SDKException(ErrorCode.unsupported_key_type) else: raise SDKException(ErrorCode.unsupported_key_type) return point_str
def ec_get_pubkey_by_prikey(privateKey: bytes, curve_name): if curve_name == Curve.P256: private_key = SigningKey.from_string(string=(privateKey), curve=NIST256p) # public_key = private_key.get_verifying_key().to_string() verifying_key = private_key.get_verifying_key() order = verifying_key.pubkey.order x_str = util.number_to_string(verifying_key.pubkey.point.x(), order) # TODO: add verify # y_str = util.number_to_string(verifying_key.pubkey.point.y(), order) # point_str = util.b("\x04") + x_str + y_str if verifying_key.pubkey.point.y() % 2 == 0: point_str = util.b("\x02") + x_str else: point_str = util.b("\x03") + x_str elif curve_name == Curve.P224: raise SDKException(ErrorCode.unsupported_key_type) elif curve_name == Curve.P384: raise SDKException(ErrorCode.unsupported_key_type) elif curve_name == Curve.P521: raise SDKException(ErrorCode.unsupported_key_type) else: raise SDKException(ErrorCode.unknown_key_type) return point_str
def verify_pub_key(self, encoded_sig, digest, pub_key): # remove SIG_ prefix encoded_sig = encoded_sig[4:] # remove curve prefix curvePre = encoded_sig[:3].strip('_') if curvePre != 'K1': raise TypeError('Unsupported curve prefix {}'.format(curvePre)) decoded_sig = self._check_decode(encoded_sig[3:], curvePre) # first 2 bytes are recover param recover_param = hex_to_int(decoded_sig[:2]) - 4 - 27 # use sig sig = decoded_sig[2:] # verify sig vk = self._recover_key(unhexlify(digest), unhexlify(sig), recover_param) order = SECP256k1.order p = vk.pubkey.point x_str = number_to_string(p.x(), order) hex_data = bytearray(chr(2 + (p.y() & 1)), 'utf-8') compressed = hexlify(hex_data + x_str).decode() p_key = 'EOS' + self._check_encode(compressed).decode() return p_key == pub_key
def point_compress(point): x = point.x() y = point.y() curve = point.curve() return chr(2 + (y & 1)) + util.number_to_string(x, curve.p())
def get_private_key_from_stretched_exponent(self, for_change, n, secexp): order = generator_secp256k1.order() secexp = (secexp + self.get_sequence(self.mpk, for_change, n)) % order pk = number_to_string(secexp, generator_secp256k1.order()) return pk
def get_private_key_base58(self, address, password): secexp, compressed = self.get_private_key(address, password) if secexp is None: return None pk = number_to_string( secexp, generator_secp256k1.order() ) return SecretToASecret( pk, compressed )
def point_to_pubkey(point): order = SECP256k1.order x_str = number_to_string(point.x(), order) y_str = number_to_string(point.y(), order) vk = x_str + y_str return chr((ord(vk[63]) & 1) + 2) + vk[0:32] # To compressed key
def get_secret_bytes(self) -> bytes: return number_to_string(self.secret_scalar, CURVE_ORDER)
def from_secret_scalar(cls, secret_scalar: int): secret_bytes = number_to_string(secret_scalar, CURVE_ORDER) return ECPrivkey(secret_bytes)
def generate_random_key(cls): randint = ecdsa.util.randrange(CURVE_ORDER) ephemeral_exponent = number_to_string(randint, CURVE_ORDER) return ECPrivkey(ephemeral_exponent)
def prvkey(self): if self.__prvkey: return util.number_to_string(self.__prvkey, SECP256k1.order) return None
def pubkey(self): x_str = util.number_to_string(self.point().x(), SECP256k1.order) y_str = util.number_to_string(self.point().y(), SECP256k1.order) return x_str + y_str
def export_private_key(self): """ Export private key as hex string """ if self.private_key: return bytes.hex(number_to_string(self.private_key, self._r)) else: return None
def generate_key_pair(self): """ generate encryption/decryption pair """ self.private_key = ecdsa.util.randrange( self._r ) self.eck = EC_KEY(number_to_string(self.private_key, self._r)) self.public_key = point_to_ser(self.private_key*self.G, True)
def generate_key_pair(self): self.private_key = ecdsa.util.randrange(pow(2, 256)) % self._r self.eck = EC_KEY(number_to_string(self.private_key, self._r)) self.public_key = point_to_ser(self.private_key * self.G, True)
def point_to_pubkey(point): order = SECP256k1.order x_str = number_to_string(point.x(), order) y_str = number_to_string(point.y(), order) vk = x_str + y_str return struct.pack('B', (byteindex(vk, 63) & 1) + 2) + vk[0:32] # To compressed key
def get_private_key_from_stretched_exponent(self, sequence, secexp): order = generator_secp256k1.order() secexp = ( secexp + self.get_sequence(sequence, self.mpk) ) % order pk = number_to_string( secexp, generator_secp256k1.order() ) compressed = False return SecretToASecret( pk, compressed )
def int_to_bytes(number, length=None): # if length is None, create a number of the same order # if length is specified in bytes, set order to the biggest int of return ( int_to_minimal_bytes(number) if length == None else number_to_string(number, 2 ** (length*BITS_PER_BYTE) -1) )
def normalize_secret_bytes(cls, privkey_bytes: bytes) -> bytes: scalar = string_to_number(privkey_bytes) % CURVE_ORDER if scalar == 0: raise Exception('invalid EC private key scalar: zero') privkey_32bytes = number_to_string(scalar, CURVE_ORDER) return privkey_32bytes
def point_to_pubkey(point): order = SECP256k1.order x_str = number_to_string(point.x(), order) y_str = number_to_string(point.y(), order) vk = x_str + y_str return struct.pack("B", (vk[63] & 1) + 2) + vk[0:32] # To compressed key
def compressed(self): pubkey = self.key.pubkey order = pubkey.order x, y = [pubkey.point.x(), pubkey.point.y()] return bytes([2 + (y & 1)]) + number_to_string(x, order)
def get_private_key_from_stretched_exponent(self, sequence, secexp): order = generator_secp256k1.order() secexp = (secexp + self.get_sequence(sequence, self.mpk)) % order pk = number_to_string(secexp, generator_secp256k1.order()) compressed = False return SecretToASecret(pk, compressed)
def int_to_minimal_bytes(number): return number_to_string(number, number)