本文整理汇总了Python中cryptography.exceptions.InvalidSignature方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.InvalidSignature方法的具体用法?Python exceptions.InvalidSignature怎么用?Python exceptions.InvalidSignature使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.exceptions
的用法示例。
在下文中一共展示了exceptions.InvalidSignature方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decrypt
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def decrypt(self, k, a, iv, e, t):
""" Decrypt according to the selected encryption and hashing
functions.
:param k: Encryption key (optional)
:param a: Additional Authenticated Data
:param iv: Initialization Vector
:param e: Ciphertext
:param t: Authentication Tag
Returns plaintext or raises an error
"""
hkey = k[:_inbytes(self.keysize)]
dkey = k[_inbytes(self.keysize):]
# verify mac
if not constant_time.bytes_eq(t, self._mac(hkey, a, iv, e)):
raise InvalidSignature('Failed to verify MAC')
# decrypt
cipher = Cipher(algorithms.AES(dkey), modes.CBC(iv),
backend=self.backend)
decryptor = cipher.decryptor()
d = decryptor.update(e) + decryptor.finalize()
unpadder = PKCS7(self.blocksize).unpadder()
return unpadder.update(d) + unpadder.finalize()
示例2: rsa_verify
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def rsa_verify(public_key, message, signature):
""" RSA verify message """
try:
public_key.verify(
base64.b64decode(signature),
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
except exceptions.InvalidSignature:
return False
except Exception as e:
raise e
return True
示例3: verify_digest
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [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
示例4: verify_certificate_signature
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def verify_certificate_signature(certificate, signer, payload):
public_key = certificate.public_key()
signature = signer['signature'].native
if "signed_attrs" in signer and signer["signed_attrs"]:
# Seen with the iPhone simulator for example
signed_string = signer["signed_attrs"].dump()
if signed_string.startswith(b'\xa0'):
# TODO: WTF!!!
# see https://stackoverflow.com/questions/24567623/how-to-see-what-attributes-are-signed-inside-pkcs7#24581628 # NOQA
signed_string = b'\x31' + signed_string[1:]
else:
signed_string = payload
asymmetric_padding = get_cryptography_asymmetric_padding(signer)
hash_algorithm = get_cryptography_hash_algorithm(signer)
try:
public_key.verify(signature, signed_string,
asymmetric_padding(), hash_algorithm())
except InvalidSignature:
return False
else:
return True
示例5: verify
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def verify(self, public_key, message, signature):
"""ECDSA verify signature.
:param public_key: Signing public key
:param message: Origin message
:param signature: Signature of message
:return: verify result boolean, True means valid
"""
if not (self._check_malleability(signature)):
return False
try:
public_key.verify(signature, message,
ec.ECDSA(self.sign_hash_algorithm))
except InvalidSignature:
return False
except Exception as e:
raise e
return True
示例6: verify_ssh_sig
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def verify_ssh_sig(self, data, msg):
if msg.get_text() != self.ecdsa_curve.key_format_identifier:
return False
sig = msg.get_binary()
sigR, sigS = self._sigdecode(sig)
signature = encode_dss_signature(sigR, sigS)
verifier = self.verifying_key.verifier(
signature, ec.ECDSA(self.ecdsa_curve.hash_object())
)
verifier.update(data)
try:
verifier.verify()
except InvalidSignature:
return False
else:
return True
示例7: verify_ssh_sig
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def verify_ssh_sig(self, data, msg):
if msg.get_text() != 'ssh-rsa':
return False
key = self.key
if isinstance(key, rsa.RSAPrivateKey):
key = key.public_key()
verifier = key.verifier(
signature=msg.get_binary(),
padding=padding.PKCS1v15(),
algorithm=hashes.SHA1(),
)
verifier.update(data)
try:
verifier.verify()
except InvalidSignature:
return False
else:
return True
示例8: test_exception_is_thrown_on_invalid_hmac_signature
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def test_exception_is_thrown_on_invalid_hmac_signature(self):
aes_key = AESKey.generate()
plaintext = 'hello world ponies 2'
encrypted = cryptography_symmetric_encrypt(aes_key, plaintext)
# Verify original non manipulated value can be decrypted
decrypted = cryptography_symmetric_decrypt(aes_key, encrypted)
self.assertEqual(decrypted, plaintext)
# Corrupt the HMAC signature (last part is the HMAC signature)
encrypted_malformed = binascii.unhexlify(encrypted)
encrypted_malformed = encrypted_malformed[:-3]
encrypted_malformed += b'abc'
encrypted_malformed = binascii.hexlify(encrypted_malformed)
# Verify corrupted value results in an excpetion
expected_msg = 'Signature did not match digest'
self.assertRaisesRegexp(InvalidSignature, expected_msg, cryptography_symmetric_decrypt,
aes_key, encrypted_malformed)
示例9: verify
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [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
示例10: verify
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def verify(self, msg, key, sig):
verifier = key.verifier(
sig,
padding.PSS(
mgf=padding.MGF1(self.hash_alg()),
salt_length=self.hash_alg.digest_size
),
self.hash_alg()
)
verifier.update(msg)
try:
verifier.verify()
return True
except InvalidSignature:
return False
示例11: verify
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def verify(self, token, verifying_key):
# grab the token parts
token_parts = self._unpack(token)
header, payload, raw_signature, signing_input = token_parts
# load the verifying key
verifying_key = load_verifying_key(verifying_key, self.crypto_backend)
# convert the raw_signature to DER format
der_signature = raw_to_der_signature(
raw_signature, verifying_key.curve)
# initialize the verifier
verifier = self._get_verifier(verifying_key, der_signature)
verifier.update(signing_input)
# check to see whether the signature is valid
try:
verifier.verify()
except InvalidSignature:
# raise DecodeError('Signature verification failed')
return False
return True
示例12: verify
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def verify(self, msg, key, sig):
try:
key.verify(sig, msg, padding.PKCS1v15(), self.hash_alg())
return True
except InvalidSignature:
return False
示例13: verify
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def verify(self, key, payload, signature):
if key.key_type != 'oct' or key.get_op_key() != '':
raise InvalidSignature('The "none" signature cannot be verified')
示例14: unsign
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def unsign(self, signed_value, ttl=None):
"""
Retrieve original value and check it wasn't signed more
than max_age seconds ago.
:type signed_value: bytes
:type ttl: int | datetime.timedelta
"""
h_size, d_size = struct.calcsize('>cQ'), self.digest.digest_size
fmt = '>cQ%ds%ds' % (len(signed_value) - h_size - d_size, d_size)
try:
version, timestamp, value, sig = struct.unpack(fmt, signed_value)
except struct.error:
raise BadSignature('Signature is not valid')
if version != self.version:
raise BadSignature('Signature version not supported')
if ttl is not None:
if isinstance(ttl, datetime.timedelta):
ttl = ttl.total_seconds()
# Check timestamp is not older than ttl
age = abs(time.time() - timestamp)
if age > ttl + _MAX_CLOCK_SKEW:
raise SignatureExpired('Signature age %s > %s seconds' % (age,
ttl))
try:
self.signature(signed_value[:-d_size]).verify(sig)
except InvalidSignature:
raise BadSignature(
'Signature "%s" does not match' % binascii.b2a_base64(sig))
return value
示例15: _verify_signature
# 需要导入模块: from cryptography import exceptions [as 别名]
# 或者: from cryptography.exceptions import InvalidSignature [as 别名]
def _verify_signature(self, data):
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(data[:-32])
try:
h.verify(data[-32:])
except InvalidSignature:
raise InvalidToken