本文整理汇总了Python中cryptography.hazmat.primitives.asymmetric.utils.Prehashed方法的典型用法代码示例。如果您正苦于以下问题:Python utils.Prehashed方法的具体用法?Python utils.Prehashed怎么用?Python utils.Prehashed使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.hazmat.primitives.asymmetric.utils
的用法示例。
在下文中一共展示了utils.Prehashed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sign_digest
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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
示例2: verify_digest
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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
示例3: sign
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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))
)
示例4: verify
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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
示例5: _ecc_static_length_signature
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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
示例6: verify
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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())),
)
示例7: _calculate_digest_and_algorithm
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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)
示例8: _check_not_prehashed
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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."
)
示例9: verify_signature_v2
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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.")
示例10: is_signature_valid
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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
示例11: generate_signature
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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
示例12: Sign
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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()))
示例13: Sign
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
def Sign(self, data):
return self.rsa_key.sign(
data, padding.PKCS1v15(), utils.Prehashed(hashes.SHA1()))
示例14: verify
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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
示例15: __call__
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import utils [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 别名]
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)