Python cryptography.hazmat.primitives.asymmetric.ec.SECP256K1 Examples
The following are 20
code examples of cryptography.hazmat.primitives.asymmetric.ec.SECP256K1().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cryptography.hazmat.primitives.asymmetric.ec
, or try the search function
.
Example #1
Source File: enc_basic.py From XFLTReaT with MIT License | 6 votes |
def __init__(self): super(Encryption_module, self).__init__() self.cmh_struct_encryption = { # num : [string to look for, function, server(1) or client(0), return on success, return on failure] # return value meanings: True - module continues # False - module thread terminates # in case of Stateless modules, the whole module terminates if the return value is False 0 : ["XFLT>ECDHd1", self.encryption_step_1, 1, True, False, True], 1 : ["XFLT>ECDHd2", self.encryption_step_2, 0, True, False, False], 2 : ["XFLT>ECDHd3", self.encryption_step_3, 1, True, False, True], 3 : ["XFLT>ECDHd4", self.encryption_step_4, 0, True, False, False], 4 : ["XFLT>ECDHd5", self.encryption_step_5, 1, True, False, True], } self.client_step_count = 2 self.server_step_count = 3 self.server_public_key_file = "misc/public_key.pem" self.server_private_key_file = "misc/private_key.pem" self.curve = ec.SECP256K1() return
Example #2
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 6 votes |
def hex_to_priv_key(priv_key_hex, public_key_hex): priv_key_value = long(priv_key_hex, 16) public_key = hex_to_key(public_key_hex) public_numbers = public_key.public_numbers() private_numbers = ec.EllipticCurvePrivateNumbers(priv_key_value, public_numbers) priv_key = private_numbers.private_key(backend) return priv_key # Hybrid Encryption Scheme: # - We perform a Elliptic Curves Diffie-Hellman Key Exchange using: # - SECP256K1 as curve for key generation # - ANSI X9.63 KDF as Key Derivation Function to derive the shared secret # - The symmetric cipher is an AES256.MODE_GCM with authentication tag 16-byte # of length. Since the key is used only once, we can pick the known nonce/iv # '000000000000' (96 bits of length). We return concatenation of the encoded # point, the tag and the ciphertext
Example #3
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 6 votes |
def encrypt(message, receiver_public_key): sender_private_key = ec.generate_private_key(ec.SECP256K1(), backend) shared_key = sender_private_key.exchange(ec.ECDH(), receiver_public_key) sender_public_key = sender_private_key.public_key() point = sender_public_key.public_numbers().encode_point() iv = '000000000000' xkdf = x963kdf.X963KDF( algorithm = hashes.SHA256(), length = 32, sharedinfo = '', backend = backend ) key = xkdf.derive(shared_key) encryptor = Cipher( algorithms.AES(key), modes.GCM(iv), backend = backend ).encryptor() ciphertext = encryptor.update(message) + encryptor.finalize() return point + encryptor.tag + ciphertext
Example #4
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 6 votes |
def decrypt(message, receiver_private_key): point = message[0:65] tag = message[65:81] ciphertext = message[81:] sender_public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), point) sender_public_key = sender_public_numbers.public_key(backend) shared_key = receiver_private_key.exchange(ec.ECDH(), sender_public_key) iv = '000000000000' xkdf = x963kdf.X963KDF( algorithm = hashes.SHA256(), length = 32, sharedinfo = '', backend = backend ) key = xkdf.derive(shared_key) decryptor = Cipher( algorithms.AES(key), modes.GCM(iv,tag), backend = backend ).decryptor() message = decryptor.update(ciphertext) + decryptor.finalize() return message
Example #5
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 6 votes |
def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256): """ Given a digest, public key (as hex), and a base64 signature, verify that the public key signed the digest. Return True if so Return False if not """ if not isinstance(hash_hex, (str, unicode)): raise ValueError("hash hex is not a string") hash_hex = str(hash_hex) pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex) sig_r, sig_s = decode_signature(sigb64) pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubk_uncompressed_hex.decode('hex')).public_key(default_backend()) signature = encode_dss_signature(sig_r, sig_s) try: pubk.verify(signature, hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256()))) return True except InvalidSignature: return False
Example #6
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 6 votes |
def sign_digest(hash_hex, privkey_hex, hashfunc=hashlib.sha256): """ Given a digest and a private key, sign it. Return the base64-encoded signature """ if not isinstance(hash_hex, (str, unicode)): raise ValueError("hash hex is not a string") hash_hex = str(hash_hex) pk_i = decode_privkey_hex(privkey_hex) privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend()) sig = privk.sign(hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256()))) sig_r, sig_s = decode_dss_signature(sig) sigb64 = encode_signature(sig_r, sig_s) return sigb64
Example #7
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 5 votes |
def hex_to_key(pub_key_hex): pub_key_hex = pub_key_hex.strip() pub_key_point = pub_key_hex.decode('hex') public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pub_key_point) public_key = public_numbers.public_key(backend) return public_key
Example #8
Source File: ecies.py From trinity with MIT License | 5 votes |
def generate_privkey() -> datatypes.PrivateKey: """Generate a new SECP256K1 private key and return it""" privkey = ec.generate_private_key(CURVE, default_backend()) return keys.PrivateKey(pad32(int_to_big_endian(privkey.private_numbers().private_value)))
Example #9
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 5 votes |
def __init__(self, public_key_string, version_byte=None, verify=True): """ Takes in a public key in hex format. """ # set the version byte if version_byte: self._version_byte = version_byte self._charencoding, self._type = keylib.public_key_encoding.get_public_key_format(public_key_string) # extract the binary key (compressed/uncompressed w magic byte) self._bin_public_key = keylib.public_key_encoding.extract_bin_ecdsa_pubkey(public_key_string) if verify: pubkey_hex_decompressed = keylib.key_formatting.decompress(self._bin_public_key.encode('hex')) pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubkey_hex_decompressed.decode('hex')).public_key(default_backend())
Example #10
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 5 votes |
def public_key(self): # lazily calculate and set the public key if not hasattr(self, '_public_key'): privk = ec.derive_private_key(int(self._ecdsa_private_key_string.encode('hex'), 16), ec.SECP256K1(), default_backend()) pubk = privk.public_key() ecdsa_public_key_str = pubk.public_numbers().encode_point().encode('hex') if self._compressed: ecdsa_public_key_str = keylib.key_formatting.compress(ecdsa_public_key_str) self._public_key = _ECPublicKey(ecdsa_public_key_str, version_byte=self._pubkeyhash_version_byte) # return the public key object return self._public_key
Example #11
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 5 votes |
def __init__(self, private_key=None, compressed=True): """ Takes in a private key/secret exponent. """ pk_i = None if private_key is None: pk_i = ec.generate_private_key(ec.SECP256K1(), default_backend()).private_numbers().private_value else: pk_i = keylib.key_formatting.encode_privkey(private_key, 'decimal') privkey_str = '{:064x}'.format(pk_i) assert len(privkey_str) == 64 self._ecdsa_private_key_string = privkey_str.decode('hex') self._compressed = compressed
Example #12
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 5 votes |
def __init__(self, pubkey_hex, sigb64): """ Instantiate the verifier with a hex-encoded public key and a base64-encoded signature """ sig_r, sig_s = decode_signature(sigb64) pubkey_hex_decompressed = keylib.key_formatting.decompress(pubkey_hex) pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubkey_hex_decompressed.decode('hex')).public_key(default_backend()) signature = encode_dss_signature(sig_r, sig_s) self.verifier = pubk.verifier(signature, ec.ECDSA(hashes.SHA256()))
Example #13
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 5 votes |
def __init__(self, privkey_hex): """ Instantiate a signer with a hex-encoded ECDSA private key """ pk_i = decode_privkey_hex(privkey_hex) privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend()) self.signer = privk.signer(ec.ECDSA(hashes.SHA256()))
Example #14
Source File: serializer.py From loopchain with Apache License 2.0 | 5 votes |
def serialize_public_key(cls, public_key: bytes) -> bytes: public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1, public_key) pub_key = public_numbers.public_key(default_backend()) return pub_key.public_bytes(encoding=cls.encoding, format=serialization.PublicFormat.SubjectPublicKeyInfo)
Example #15
Source File: serializer.py From loopchain with Apache License 2.0 | 5 votes |
def serialize_private_key(cls, private_key: bytes, password=Optional[bytes]) -> bytes: pri_key = ec.derive_private_key(int.from_bytes(private_key, byteorder="big"), ec.SECP256K1, default_backend()) algorithm = \ serialization.BestAvailableEncryption(password) if password is not None else serialization.NoEncryption() return pri_key.private_bytes(encoding=cls.encoding, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=algorithm)
Example #16
Source File: ecies.py From pyquarkchain with MIT License | 5 votes |
def generate_privkey() -> datatypes.PrivateKey: """Generate a new SECP256K1 private key and return it""" privkey = ec.generate_private_key(CURVE, default_backend()) return keys.PrivateKey( pad32(int_to_big_endian(privkey.private_numbers().private_value)) )
Example #17
Source File: jwk.py From jwcrypto with GNU Lesser General Public License v3.0 | 5 votes |
def _get_curve_by_name(self, name): if name == 'P-256': return ec.SECP256R1() elif name == 'P-384': return ec.SECP384R1() elif name == 'P-521': return ec.SECP521R1() elif name == 'secp256k1': return ec.SECP256K1() elif name in _OKP_CURVES_TABLE: return name else: raise InvalidJWKValue('Unknown Elliptic Curve Type')
Example #18
Source File: utils.py From lemur with Apache License 2.0 | 4 votes |
def generate_private_key(key_type): """ Generates a new private key based on key_type. Valid key types: RSA2048, RSA4096', 'ECCPRIME192V1', 'ECCPRIME256V1', 'ECCSECP192R1', 'ECCSECP224R1', 'ECCSECP256R1', 'ECCSECP384R1', 'ECCSECP521R1', 'ECCSECP256K1', 'ECCSECT163K1', 'ECCSECT233K1', 'ECCSECT283K1', 'ECCSECT409K1', 'ECCSECT571K1', 'ECCSECT163R2', 'ECCSECT233R1', 'ECCSECT283R1', 'ECCSECT409R1', 'ECCSECT571R2' :param key_type: :return: """ _CURVE_TYPES = { "ECCPRIME192V1": ec.SECP192R1(), "ECCPRIME256V1": ec.SECP256R1(), "ECCSECP192R1": ec.SECP192R1(), "ECCSECP224R1": ec.SECP224R1(), "ECCSECP256R1": ec.SECP256R1(), "ECCSECP384R1": ec.SECP384R1(), "ECCSECP521R1": ec.SECP521R1(), "ECCSECP256K1": ec.SECP256K1(), "ECCSECT163K1": ec.SECT163K1(), "ECCSECT233K1": ec.SECT233K1(), "ECCSECT283K1": ec.SECT283K1(), "ECCSECT409K1": ec.SECT409K1(), "ECCSECT571K1": ec.SECT571K1(), "ECCSECT163R2": ec.SECT163R2(), "ECCSECT233R1": ec.SECT233R1(), "ECCSECT283R1": ec.SECT283R1(), "ECCSECT409R1": ec.SECT409R1(), "ECCSECT571R2": ec.SECT571R1(), } if key_type not in CERTIFICATE_KEY_TYPES: raise Exception( "Invalid key type: {key_type}. Supported key types: {choices}".format( key_type=key_type, choices=",".join(CERTIFICATE_KEY_TYPES) ) ) if "RSA" in key_type: key_size = int(key_type[3:]) return rsa.generate_private_key( public_exponent=65537, key_size=key_size, backend=default_backend() ) elif "ECC" in key_type: return ec.generate_private_key( curve=_CURVE_TYPES[key_type], backend=default_backend() )
Example #19
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 4 votes |
def main(): parser = argparse.ArgumentParser(description='Encrypt messages to Oraclize using Elliptic Curve Integrated Encryption Scheme.') parser.add_argument('-e', '--encrypt', dest='mode', action='store_const', const='encrypt', help='Encrypt a string. Requires -p') parser.add_argument('-p', '--with-public-key', dest='public_key', action='store', help='Use the provided hex-encoded public key to encrypt') parser.add_argument('-d', '--decrypt', dest='mode', action='store_const', const='decrypt', help='Decrypt a string. Provide private key in Wallet Import Format in standard input, or first line of standard input if encrypted text is also provided on standard input. DO NOT PUT YOUR PRIVATE KEY ON THE COMMAND LINE.') parser.add_argument('-g', '--generate', dest='mode', action='store_const', const='generate', help='Generates a public and a private key') parser.add_argument('text', nargs='?', action='store', help='String to encrypt, decrypt. If not specified, standard input will be used.') args = parser.parse_args() if args.mode != 'encrypt' and args.mode != 'decrypt' and args.mode != 'generate': parser.print_help() return if args.mode == 'encrypt' and not args.public_key: print "Please, provide a valid public key" return if args.mode == 'encrypt': if args.public_key: pub_key = hex_to_key(args.public_key) if args.text: print base64.b64encode(encrypt(args.text, pub_key)) return else: print base64.b64encode(encrypt(sys.stdin.read(), pub_key)) return elif args.mode == 'decrypt': if args.text: print "Insert your public key" public_key = sys.stdin.read() print "Insert your private key:" private_key = sys.stdin.read() private_key = hex_to_priv_key(private_key, public_key) text = base64.b64decode(args.text) else: print "Insert your public key" public_key = sys.stdin.read() print "\nInsert your private key:" private_key = sys.stdin.read() private_key = hex_to_priv_key(private_key, public_key) print "\nInsert encrypted text" text = base64.b64decode(sys.stdin.read()) print decrypt(text, private_key) if args.mode == 'generate': receiver_private_key = ec.generate_private_key(ec.SECP256K1(), backend) receiver_public_key = receiver_private_key.public_key() number = receiver_private_key.private_numbers() print "Public Key:", receiver_public_key.public_numbers().encode_point().encode('hex') print "Private Key:", hex(number.private_value)
Example #20
Source File: ecdsa.py From python-graphenelib with MIT License | 4 votes |
def recover_public_key(digest, signature, i, message=None): """ Recover the public key from the the signature """ # See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily curve = ecdsa.SECP256k1.curve G = ecdsa.SECP256k1.generator order = ecdsa.SECP256k1.order yp = i % 2 r, s = ecdsa.util.sigdecode_string(signature, order) # 1.1 x = r + (i // 2) * order # 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified. # This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve. alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p() beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p()) y = beta if (beta - yp) % 2 == 0 else curve.p() - beta # 1.4 Constructor of Point is supposed to check if nR is at infinity. R = ecdsa.ellipticcurve.Point(curve, x, y, order) # 1.5 Compute e e = ecdsa.util.string_to_number(digest) # 1.6 Compute Q = r^-1(sR - eG) Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G) if SECP256K1_MODULE == "cryptography" and message is not None: if not isinstance(message, bytes): message = bytes(message, "utf-8") # pragma: no cover sigder = encode_dss_signature(r, s) public_key = ec.EllipticCurvePublicNumbers( Q._Point__x, Q._Point__y, ec.SECP256K1() ).public_key(default_backend()) public_key.verify(sigder, message, ec.ECDSA(hashes.SHA256())) return public_key else: # Not strictly necessary, but let's verify the message for paranoia's sake. if not ecdsa.VerifyingKey.from_public_point( Q, curve=ecdsa.SECP256k1 ).verify_digest( signature, digest, sigdecode=ecdsa.util.sigdecode_string ): # pragma: no cover return None # pragma: no cover return ecdsa.VerifyingKey.from_public_point( Q, curve=ecdsa.SECP256k1 ) # pragma: no cover