Python cryptography.hazmat.primitives.asymmetric.ec.derive_private_key() Examples
The following are 10
code examples of cryptography.hazmat.primitives.asymmetric.ec.derive_private_key().
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: signature_handler.py From ontology-python-sdk with GNU Lesser General Public License v3.0 | 6 votes |
def generate_signature(self, pri_key: str, msg: bytes) -> str: if self.__scheme == SignatureScheme.SHA224withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP224R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA224()) ) elif self.__scheme == SignatureScheme.SHA256withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP256R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA256()) ) elif self.__scheme == SignatureScheme.SHA384withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP384R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA384()) ) else: raise SDKException(ErrorCode.other_error('Invalid signature scheme.')) sign = SignatureHandler.dsa_der_to_plain(signature) return sign
Example #2
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 6 votes |
def get_pubkey_hex( privatekey_hex ): """ Get the uncompressed hex form of a private key """ if not isinstance(privatekey_hex, (str, unicode)): raise ValueError("private key is not a hex string but {}".format(str(type(privatekey_hex)))) # remove 'compressed' hint if len(privatekey_hex) > 64: if privatekey_hex[-2:] != '01': raise ValueError("private key does not end in 01") privatekey_hex = privatekey_hex[:64] # get hex public key privatekey_int = int(privatekey_hex, 16) privk = ec.derive_private_key(privatekey_int, ec.SECP256K1(), default_backend()) pubk = privk.public_key() x = pubk.public_numbers().x y = pubk.public_numbers().y pubkey_hex = "04{:064x}{:064x}".format(x, y) return pubkey_hex
Example #3
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 #4
Source File: ecies.py From pyquarkchain with MIT License | 5 votes |
def ecdh_agree(privkey: datatypes.PrivateKey, pubkey: datatypes.PublicKey) -> bytes: """Performs a key exchange operation using the ECDH algorithm.""" privkey_as_int = int(cast(int, privkey)) ec_privkey = ec.derive_private_key(privkey_as_int, CURVE, default_backend()) pubkey_bytes = b"\x04" + pubkey.to_bytes() pubkey_nums = ec.EllipticCurvePublicNumbers.from_encoded_point(CURVE, pubkey_bytes) ec_pubkey = pubkey_nums.public_key(default_backend()) return ec_privkey.exchange(ec.ECDH(), ec_pubkey)
Example #5
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 #6
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 #7
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 #8
Source File: keys.py From learn_python3_spider with MIT License | 5 votes |
def _fromECEncodedPoint(cls, encodedPoint, curve, privateValue=None): """ Build a key from an EC encoded point. @param encodedPoint: The public point encoded as in SEC 1 v2.0 section 2.3.3. @type encodedPoint: L{bytes} @param curve: NIST name of elliptic curve. @type curve: L{bytes} @param privateValue: The private value. @type privateValue: L{int} """ if privateValue is None: # We have public components. keyObject = ec.EllipticCurvePublicKey.from_encoded_point( _curveTable[curve], encodedPoint ) else: keyObject = ec.derive_private_key( privateValue, _curveTable[curve], default_backend() ) return cls(keyObject)
Example #9
Source File: Mastodon.py From Mastodon.py with MIT License | 5 votes |
def push_subscription_decrypt_push(self, data, decrypt_params, encryption_header, crypto_key_header): """ Decrypts `data` received in a webpush request. Requires the private key dict from `push_subscription_generate_keys()`_ (`decrypt_params`) as well as the Encryption and server Crypto-Key headers from the received webpush Returns the decoded webpush as a `push notification dict`_. """ if (not IMPL_HAS_ECE) or (not IMPL_HAS_CRYPTO): raise NotImplementedError('To use the crypto tools, please install the webpush feature dependencies.') salt = self.__decode_webpush_b64(encryption_header.split("salt=")[1].strip()) dhparams = self.__decode_webpush_b64(crypto_key_header.split("dh=")[1].split(";")[0].strip()) p256ecdsa = self.__decode_webpush_b64(crypto_key_header.split("p256ecdsa=")[1].strip()) dec_key = ec.derive_private_key(decrypt_params['privkey'], ec.SECP256R1(), default_backend()) decrypted = http_ece.decrypt( data, salt = salt, key = p256ecdsa, private_key = dec_key, dh = dhparams, auth_secret=decrypt_params['auth'], keylabel = "P-256", version = "aesgcm" ) return json.loads(decrypted.decode('utf-8'), object_hook = Mastodon.__json_hooks) ### # Blurhash utilities ###
Example #10
Source File: ecies.py From trinity with MIT License | 5 votes |
def ecdh_agree(privkey: datatypes.PrivateKey, pubkey: datatypes.PublicKey) -> bytes: """Performs a key exchange operation using the ECDH algorithm.""" privkey_as_int = int(cast(int, privkey)) ec_privkey = ec.derive_private_key(privkey_as_int, CURVE, default_backend()) pubkey_bytes = b'\x04' + pubkey.to_bytes() try: # either of these can raise a ValueError: pubkey_nums = ec.EllipticCurvePublicKey.from_encoded_point(CURVE, pubkey_bytes) ec_pubkey = pubkey_nums.public_numbers().public_key(default_backend()) except ValueError as exc: # Not all bytes can be made into valid public keys, see the warning at # https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/ # under EllipticCurvePublicNumbers(x, y) raise _InvalidPublicKey(str(exc)) from exc return ec_privkey.exchange(ec.ECDH(), ec_pubkey)