Python cryptography.hazmat.primitives.asymmetric.utils.Prehashed() Examples
The following are 28
code examples of cryptography.hazmat.primitives.asymmetric.utils.Prehashed().
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.utils
, or try the search function
.
Example #1
Source File: ecc.py From synapse with Apache License 2.0 | 6 votes |
def verify(self, byts, sign): ''' Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise. ''' try: chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() self.publ.verify(sign, digest, c_ec.ECDSA(c_utils.Prehashed(chosen_hash)) ) return True except InvalidSignature: logger.exception('Error in publ.verify') return False
Example #2
Source File: ecc.py From synapse with Apache License 2.0 | 6 votes |
def sign(self, byts): ''' Compute the ECC signature for the given bytestream. Args: byts (bytes): The bytes to sign. Returns: bytes: The RSA Signature bytes. ''' chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() return self.priv.sign(digest, c_ec.ECDSA(c_utils.Prehashed(chosen_hash)) )
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: 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 #5
Source File: transaction.py From lbry-sdk with MIT License | 5 votes |
def is_signature_valid(encoded_signature, signature_digest, public_key_bytes): try: public_key = load_der_public_key(public_key_bytes, default_backend()) public_key.verify(encoded_signature, signature_digest, ec.ECDSA(Prehashed(hashes.SHA256()))) return True except (ValueError, InvalidSignature): pass return False
Example #6
Source File: utils.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _check_not_prehashed(signature_algorithm): if isinstance(signature_algorithm, Prehashed): raise TypeError( "Prehashed is only supported in the sign and verify methods. " "It cannot be used with signer or verifier." )
Example #7
Source File: utils.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _calculate_digest_and_algorithm(backend, data, algorithm): if not isinstance(algorithm, Prehashed): hash_ctx = hashes.Hash(algorithm, backend) hash_ctx.update(data) data = hash_ctx.finalize() else: algorithm = algorithm._algorithm if len(data) != algorithm.digest_size: raise ValueError( "The provided data must be the same length as the hash " "algorithm's digest size." ) return (data, algorithm)
Example #8
Source File: signing.py From pyUmbral with GNU General Public License v3.0 | 5 votes |
def __call__(self, message: bytes, is_prehashed: bool = False) -> Signature: """ Signs the message with this instance's private key. :param message: Message to hash and sign :param is_prehashed: True if the message has been prehashed previously :return: signature """ if is_prehashed: signature_algorithm = ECDSA(utils.Prehashed(self.hash_algorithm())) else: signature_algorithm = ECDSA(self.hash_algorithm()) signature_der_bytes = self.__cryptography_private_key.sign(message, signature_algorithm) return Signature.from_bytes(signature_der_bytes, der_encoded=True, curve=self.curve)
Example #9
Source File: signing.py From pyUmbral with GNU General Public License v3.0 | 5 votes |
def verify(self, message: bytes, verifying_key: UmbralPublicKey, is_prehashed: bool = False) -> bool: """ Verifies that a message's signature was valid. :param message: The message to verify :param verifying_key: UmbralPublicKey of the signer :param is_prehashed: True if the message has been prehashed previously :return: True if valid, False if invalid """ cryptography_pub_key = verifying_key.to_cryptography_pubkey() if is_prehashed: signature_algorithm = ECDSA(utils.Prehashed(self.hash_algorithm())) else: signature_algorithm = ECDSA(self.hash_algorithm()) # TODO: Raise error instead of returning boolean try: cryptography_pub_key.verify( signature=self._der_encoded_bytes(), data=message, signature_algorithm=signature_algorithm ) except InvalidSignature: return False return True
Example #10
Source File: utils.py From quickstart-redhat-openshift with Apache License 2.0 | 5 votes |
def _check_not_prehashed(signature_algorithm): if isinstance(signature_algorithm, Prehashed): raise TypeError( "Prehashed is only supported in the sign and verify methods. " "It cannot be used with signer or verifier." )
Example #11
Source File: utils.py From quickstart-redhat-openshift with Apache License 2.0 | 5 votes |
def _calculate_digest_and_algorithm(backend, data, algorithm): if not isinstance(algorithm, Prehashed): hash_ctx = hashes.Hash(algorithm, backend) hash_ctx.update(data) data = hash_ctx.finalize() else: algorithm = algorithm._algorithm if len(data) != algorithm.digest_size: raise ValueError( "The provided data must be the same length as the hash " "algorithm's digest size." ) return (data, algorithm)
Example #12
Source File: sign_cryptography.py From python-adb with Apache License 2.0 | 5 votes |
def Sign(self, data): return self.rsa_key.sign( data, padding.PKCS1v15(), utils.Prehashed(hashes.SHA1()))
Example #13
Source File: utils.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def _check_not_prehashed(signature_algorithm): if isinstance(signature_algorithm, Prehashed): raise TypeError( "Prehashed is only supported in the sign and verify methods. " "It cannot be used with signer or verifier." )
Example #14
Source File: utils.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def _calculate_digest_and_algorithm(backend, data, algorithm): if not isinstance(algorithm, Prehashed): hash_ctx = hashes.Hash(algorithm, backend) hash_ctx.update(data) data = hash_ctx.finalize() else: algorithm = algorithm._algorithm if len(data) != algorithm.digest_size: raise ValueError( "The provided data must be the same length as the hash " "algorithm's digest size." ) return (data, algorithm)
Example #15
Source File: sign_cryptography.py From adb_shell with Apache License 2.0 | 5 votes |
def Sign(self, data): """Signs given data using a private key. Parameters ---------- data : TODO TODO Returns ------- TODO The signed ``data`` """ return self.rsa_key.sign(data, padding.PKCS1v15(), utils.Prehashed(hashes.SHA1()))
Example #16
Source File: image_signer.py From openstacksdk with Apache License 2.0 | 5 votes |
def generate_signature(self, file_obj): file_obj.seek(0) chunked_file = IterableChunkedFile(file_obj) for chunk in chunked_file: self.hasher.update(chunk) file_obj.seek(0) digest = self.hasher.finalize() signature = self.private_key.sign( digest, self.padding, utils.Prehashed(self.hash) ) return signature
Example #17
Source File: utils.py From learn_python3_spider with MIT License | 5 votes |
def _check_not_prehashed(signature_algorithm): if isinstance(signature_algorithm, Prehashed): raise TypeError( "Prehashed is only supported in the sign and verify methods. " "It cannot be used with signer or verifier." )
Example #18
Source File: utils.py From learn_python3_spider with MIT License | 5 votes |
def _calculate_digest_and_algorithm(backend, data, algorithm): if not isinstance(algorithm, Prehashed): hash_ctx = hashes.Hash(algorithm, backend) hash_ctx.update(data) data = hash_ctx.finalize() else: algorithm = algorithm._algorithm if len(data) != algorithm.digest_size: raise ValueError( "The provided data must be the same length as the hash " "algorithm's digest size." ) return (data, algorithm)
Example #19
Source File: espsecure.py From esptool with GNU General Public License v2.0 | 5 votes |
def verify_signature_v2(args): """ Verify a previously signed binary image, using the RSA public key """ SECTOR_SIZE = 4096 SIG_BLOCK_MAX_COUNT = 3 vk = _get_sbv2_rsa_pub_key(args.keyfile) image_content = args.datafile.read() if len(image_content) < SECTOR_SIZE or len(image_content) % SECTOR_SIZE != 0: raise esptool.FatalError("Invalid datafile. Data size should be non-zero & a multiple of 4096.") digest = digest = hashlib.sha256() digest.update(image_content[:-SECTOR_SIZE]) digest = digest.digest() for sig_blk_num in range(SIG_BLOCK_MAX_COUNT): sig_blk = validate_signature_block(image_content, sig_blk_num) if sig_blk is None: raise esptool.FatalError("Signature block %d invalid. Signature could not be verified with the provided key." % sig_blk_num) sig_data = struct.unpack("<BBxx32s384sI384sI384sI16x", sig_blk) if sig_data[2] != digest: raise esptool.FatalError("Signature block image digest does not match the actual image digest %s. Expected %s." % (digest, sig_data[2])) try: vk.verify( sig_data[-2][::-1], digest, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=32 ), utils.Prehashed(hashes.SHA256()) ) print("Signature block %d verification successful with %s." % (sig_blk_num, args.keyfile.name)) return except exceptions.InvalidSignature: print("Signature block %d is not signed by %s. Checking the next block" % (sig_blk_num, args.keyfile.name)) continue raise esptool.FatalError("Checked all blocks. Signature could not be verified with the provided key.")
Example #20
Source File: utils.py From teleport with Apache License 2.0 | 5 votes |
def _calculate_digest_and_algorithm(backend, data, algorithm): if not isinstance(algorithm, Prehashed): hash_ctx = hashes.Hash(algorithm, backend) hash_ctx.update(data) data = hash_ctx.finalize() else: algorithm = algorithm._algorithm if len(data) != algorithm.digest_size: raise ValueError( "The provided data must be the same length as the hash " "algorithm's digest size." ) return (data, algorithm)
Example #21
Source File: utils.py From teleport with Apache License 2.0 | 5 votes |
def _check_not_prehashed(signature_algorithm): if isinstance(signature_algorithm, Prehashed): raise TypeError( "Prehashed is only supported in the sign and verify methods. " "It cannot be used with signer or verifier." )
Example #22
Source File: utils.py From teleport with Apache License 2.0 | 5 votes |
def _calculate_digest_and_algorithm(backend, data, algorithm): if not isinstance(algorithm, Prehashed): hash_ctx = hashes.Hash(algorithm, backend) hash_ctx.update(data) data = hash_ctx.finalize() else: algorithm = algorithm._algorithm if len(data) != algorithm.digest_size: raise ValueError( "The provided data must be the same length as the hash " "algorithm's digest size." ) return (data, algorithm)
Example #23
Source File: utils.py From teleport with Apache License 2.0 | 5 votes |
def _check_not_prehashed(signature_algorithm): if isinstance(signature_algorithm, Prehashed): raise TypeError( "Prehashed is only supported in the sign and verify methods. " "It cannot be used with signer or verifier." )
Example #24
Source File: utils.py From teleport with Apache License 2.0 | 5 votes |
def _calculate_digest_and_algorithm(backend, data, algorithm): if not isinstance(algorithm, Prehashed): hash_ctx = hashes.Hash(algorithm, backend) hash_ctx.update(data) data = hash_ctx.finalize() else: algorithm = algorithm._algorithm if len(data) != algorithm.digest_size: raise ValueError( "The provided data must be the same length as the hash " "algorithm's digest size." ) return (data, algorithm)
Example #25
Source File: utils.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _calculate_digest_and_algorithm(backend, data, algorithm): if not isinstance(algorithm, Prehashed): hash_ctx = hashes.Hash(algorithm, backend) hash_ctx.update(data) data = hash_ctx.finalize() else: algorithm = algorithm._algorithm if len(data) != algorithm.digest_size: raise ValueError( "The provided data must be the same length as the hash " "algorithm's digest size." ) return (data, algorithm)
Example #26
Source File: authentication.py From aws-encryption-sdk-python with Apache License 2.0 | 5 votes |
def verify(self, signature): """Verifies the signature against the current cryptographic verifier state. :param bytes signature: The signature to verify """ prehashed_digest = self._hasher.finalize() self.key.verify( signature=signature, data=prehashed_digest, signature_algorithm=ec.ECDSA(Prehashed(self.algorithm.signing_hash_type())), )
Example #27
Source File: elliptic_curve.py From aws-encryption-sdk-python with Apache License 2.0 | 5 votes |
def _ecc_static_length_signature(key, algorithm, digest): """Calculates an elliptic curve signature with a static length using pre-calculated hash. :param key: Elliptic curve private key :type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey :param algorithm: Master algorithm to use :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param bytes digest: Pre-calculated hash digest :returns: Signature with required length :rtype: bytes """ pre_hashed_algorithm = ec.ECDSA(Prehashed(algorithm.signing_hash_type())) signature = b"" while len(signature) != algorithm.signature_len: _LOGGER.debug( "Signature length %d is not desired length %d. Recalculating.", len(signature), algorithm.signature_len ) signature = key.sign(digest, pre_hashed_algorithm) if len(signature) != algorithm.signature_len: # Most of the time, a signature of the wrong length can be fixed # by negating s in the signature relative to the group order. _LOGGER.debug( "Signature length %d is not desired length %d. Negating s.", len(signature), algorithm.signature_len ) r, s = decode_dss_signature(signature) s = _ECC_CURVE_PARAMETERS[algorithm.signing_algorithm_info.name].order - s signature = encode_dss_signature(r, s) return signature
Example #28
Source File: ocsp_asn1crypto.py From snowflake-connector-python with Apache License 2.0 | 4 votes |
def verify_signature(self, signature_algorithm, signature, cert, data): use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True' if not use_openssl_only: pubkey = asymmetric.load_public_key(cert.public_key).unwrap().dump() rsakey = RSA.importKey(pubkey) signer = PKCS1_v1_5.new(rsakey) if signature_algorithm in SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS: digest = \ SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS[ signature_algorithm].new() else: # the last resort. should not happen. digest = SHA1.new() digest.update(data.dump()) if not signer.verify(digest, signature): raise RevocationCheckError( msg="Failed to verify the signature", errno=ER_INVALID_OCSP_RESPONSE) else: backend = default_backend() public_key = serialization.load_der_public_key(cert.public_key.dump(), backend=default_backend()) if signature_algorithm in SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS: chosen_hash = \ SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS_OPENSSL[ signature_algorithm]() else: # the last resort. should not happen. chosen_hash = hashes.SHA1() hasher = hashes.Hash(chosen_hash, backend) hasher.update(data.dump()) digest = hasher.finalize() try: public_key.verify( signature, digest, padding.PKCS1v15(), utils.Prehashed(chosen_hash) ) except InvalidSignature: raise RevocationCheckError( msg="Failed to verify the signature", errno=ER_INVALID_OCSP_RESPONSE)