本文整理汇总了Python中cryptography.hazmat.primitives.hmac.HMAC.verify方法的典型用法代码示例。如果您正苦于以下问题:Python HMAC.verify方法的具体用法?Python HMAC.verify怎么用?Python HMAC.verify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.hazmat.primitives.hmac.HMAC
的用法示例。
在下文中一共展示了HMAC.verify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decrypt
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def decrypt(privkey, data):
s = serialize.Deserializer(data)
iv = s.bytes(16)
curve = s.uint(2)
assert curve == 0x02ca
x_len = s.uint(2)
assert x_len <= 32 # TODO Should we assert this? And should we assert no leading zero bytes?
x = s.bytes(x_len)
y_len = s.uint(2)
assert y_len <= 32 # TODO Should we assert this? And should we assert no leading zero bytes?
y = s.bytes(y_len)
encrypted = s.bytes(-32)
assert encrypted != b''
mac = s.bytes(32)
pubkey = x.rjust(32, b'\x00') + y.rjust(32, b'\x00')
public_key = _pub_to_public(pubkey)
private_key = _priv_to_private(privkey)
secret = private_key.exchange(ec.ECDH(), public_key)
key = hashlib.sha512(secret).digest()
enckey = key[0:32]
mackey = key[32:64]
maccer = HMAC(mackey, hashes.SHA256(), openssl.backend)
maccer.update(data[0:-32])
maccer.verify(mac)
cipher = Cipher(algorithms.AES(enckey), modes.CBC(iv), openssl.backend)
decryptor = cipher.decryptor()
padded = decryptor.update(encrypted) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
return unpadder.update(padded) + unpadder.finalize()
示例2: checkHMAC
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def checkHMAC(self, fp, segments_start, segments_end, fileHMAC):
'''Check the file's integrity'''
filehash = HMAC(self.hmackey, primitives.hashes.SHA256(), backend)
filehash.update(self.FileMACPrefix)
for segmentIndex, startpos, datalen in self.segment_ranges(segments_start, segments_end):
print(" Segment %d" % (segmentIndex))
fp.seek(startpos)
segmentIV = fp.read(self.SegIVLen)
segmentMAC = fp.read(self.SegMACLen)
# Verify the segment's own MAC against the segment data
segmenthash = HMAC(self.hmackey, primitives.hashes.SHA256(), backend)
segmenthash.update(segmentIV)
segmenthash.update(struct.pack('>I', segmentIndex))
segmenthash.update(fp.read(datalen))
# The cryptography module doesn't handle truncated HMACs directly
computed = segmenthash.finalize()
assert primitives.constant_time.bytes_eq(computed[:self.SegMACLen], segmentMAC)
# Add the segment's MAC to the file-MAC context
filehash.update(segmentMAC)
# Finally, verify the file MAC
print(" File hash")
filehash.verify(fileHMAC) # Raises on mismatch.
示例3: _decrypt_data
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def _decrypt_data(self, data, timestamp, ttl):
current_time = int(time.time())
if ttl is not None:
if timestamp + ttl < current_time:
raise InvalidToken
if current_time + _MAX_CLOCK_SKEW < timestamp:
raise InvalidToken
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(data[:-32])
try:
h.verify(data[-32:])
except InvalidSignature:
raise InvalidToken
iv = data[9:25]
ciphertext = data[25:-32]
decryptor = Cipher(
algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
).decryptor()
plaintext_padded = decryptor.update(ciphertext)
try:
plaintext_padded += decryptor.finalize()
except ValueError:
raise InvalidToken
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
unpadded = unpadder.update(plaintext_padded)
try:
unpadded += unpadder.finalize()
except ValueError:
raise InvalidToken
return unpadded
示例4: verifyThenDecrypt
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def verifyThenDecrypt(cipher, emailTime, key):
encryptKey = key[16:]
signKey = key[:16]
payload = base64.urlsafe_b64decode(cipher)
#verify timestamp to prevent replay
try:
timestamp, = struct.unpack(">Q", payload[1:9])
except struct.error:
raise ValueError('Invalid message')
if timestamp + TTL < emailTime:
raise Exception('Invalid timestamp: replay attack detected')
#verify HMAC
hasher = HMAC(signKey, hashes.SHA256(), backend=default_backend())
hasher.update(payload[:-32])
try:
hasher.verify(payload[-32:])
except InvalidSignature:
raise Exception('Invalid HMAC: data modification detected')
#decrypt cipher text
iv = payload[9:25]
ciphertext = payload[25:-32]
decryptor = Cipher(algorithms.AES(encryptKey), modes.CBC(iv), default_backend()).decryptor()
paddedPlaintext = decryptor.update(ciphertext)
paddedPlaintext += decryptor.finalize()
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
plaintext = unpadder.update(paddedPlaintext)
plaintext += unpadder.finalize()
return plaintext
示例5: _verify_signature
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [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
示例6: decrypt
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def decrypt(self, token, ttl=None):
if not isinstance(token, bytes):
raise TypeError("token must be bytes.")
current_time = int(time.time())
try:
data = base64.urlsafe_b64decode(token)
except (TypeError, binascii.Error):
raise InvalidToken
if not data or six.indexbytes(data, 0) != 0x80:
raise InvalidToken
try:
timestamp, = struct.unpack(">Q", data[1:9])
except struct.error:
raise InvalidToken
if ttl is not None:
if timestamp + ttl < current_time:
raise InvalidToken
if current_time + _MAX_CLOCK_SKEW < timestamp:
print (">>>", current_time)
print (">>>", timestamp)
raise InvalidToken
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(data[:-32])
try:
# verify everything in data except for tag is the same as original
h.verify(data[-32:])
except InvalidSignature:
raise InvalidToken
iv = data[9:25]
ciphertext = data[25:-32]
decryptor = Cipher(
algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
).decryptor()
plaintext_padded = decryptor.update(ciphertext)
try:
plaintext_padded += decryptor.finalize()
except ValueError:
raise InvalidToken
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
unpadded = unpadder.update(plaintext_padded)
try:
unpadded += unpadder.finalize()
except ValueError:
raise InvalidToken
return unpadded
示例7: verify_mac
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def verify_mac(key, packed_data, algorithm="SHA256", backend=BACKEND):
""" Verifies a message authentication code as obtained by apply_mac.
Successful comparison indicates integrity and authenticity of the data.
Returns data is comparison succeeds; Otherwise returns pride.functions.security.INVALID_TAG. """
mac, data = load_data(packed_data)
hasher = HMAC(key, getattr(hashes, algorithm.upper())(), backend=backend)
hasher.update(algorithm + '::' + data)
try:
hasher.verify(mac)
except InvalidSignature:
return INVALID_TAG
else:
return data
示例8: opdata1_verify_overall_hmac
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def opdata1_verify_overall_hmac(hmac_key, item):
verifier = HMAC(hmac_key, SHA256(), backend=_backend)
for key, value in sorted(item.items()):
if key == 'hmac':
continue
if isinstance(value, bool):
value = str(int(value)).encode('utf-8')
else:
value = str(value).encode('utf-8')
verifier.update(key.encode('utf-8'))
verifier.update(value)
expected = base64.b64decode(item['hmac'])
try:
verifier.verify(expected)
except InvalidSignature:
raise ValueError("HMAC did not match for data dictionary")
示例9: opdata1_decrypt_key
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def opdata1_decrypt_key(data, key, hmac_key, aes_size=C_AES_SIZE, ignore_hmac=False):
"""Decrypt encrypted item keys"""
hmac_key = make_utf8(hmac_key)
key_size = KEY_SIZE[aes_size]
iv, cryptext, expected_hmac = struct.unpack("=16s64s32s", data)
if not ignore_hmac:
verifier = HMAC(hmac_key, SHA256(), backend=_backend)
verifier.update(iv + cryptext)
try:
verifier.verify(expected_hmac)
except InvalidSignature:
raise ValueError("HMAC did not match for opdata1 key")
aes = Cipher(algorithms.AES(key), modes.CBC(iv), backend=_backend)
decryptor = aes.decryptor()
decrypted = decryptor.update(cryptext) + decryptor.finalize()
crypto_key, mac_key = decrypted[:key_size], decrypted[key_size:]
return crypto_key, mac_key
示例10: decrypt
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def decrypt(self, data, ttl=None):
if not isinstance(data, bytes):
raise TypeError("data must be bytes.")
current_time = int(time.time())
if not data or six.indexbytes(data, 0) != 0x80:
raise InvalidToken
try:
timestamp, = struct.unpack(">Q", data[1:9])
except struct.error:
raise InvalidToken
if ttl is not None:
if timestamp + ttl < current_time:
raise InvalidToken
if current_time + _MAX_CLOCK_SKEW < timestamp:
raise InvalidToken
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(data[:-32])
try:
h.verify(data[-32:])
except InvalidSignature:
raise InvalidToken
iv = data[9:25]
ciphertext = data[25:-32]
decryptor = Cipher(
algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
).decryptor()
plaintext_padded = decryptor.update(ciphertext)
try:
plaintext_padded += decryptor.finalize()
except ValueError:
raise InvalidToken
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
unpadded = unpadder.update(plaintext_padded)
try:
unpadded += unpadder.finalize()
except ValueError:
raise InvalidToken
return unpadded
示例11: verify_hmac
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def verify_hmac(key, data, signature):
"""Shortcut for verifying HMAC of a string."""
h = HMAC(
key=key,
algorithm=hashes.SHA256(),
backend=backend
)
h.update(data)
return h.verify(signature)
示例12: _decrypt_cryptography
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def _decrypt_cryptography(cls, b_ciphertext, b_crypted_hmac, b_key1, b_key2, b_iv):
# b_key1, b_key2, b_iv = self._gen_key_initctr(b_password, b_salt)
# EXIT EARLY IF DIGEST DOESN'T MATCH
hmac = HMAC(b_key2, hashes.SHA256(), CRYPTOGRAPHY_BACKEND)
hmac.update(b_ciphertext)
try:
hmac.verify(unhexlify(b_crypted_hmac))
except InvalidSignature as e:
raise AnsibleVaultError('HMAC verification failed: %s' % e)
cipher = C_Cipher(algorithms.AES(b_key1), modes.CTR(b_iv), CRYPTOGRAPHY_BACKEND)
decryptor = cipher.decryptor()
unpadder = padding.PKCS7(128).unpadder()
b_plaintext = unpadder.update(
decryptor.update(b_ciphertext) + decryptor.finalize()
) + unpadder.finalize()
return b_plaintext
示例13: decrypt
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def decrypt(self, token, associated_data=b"", ttl=None):
if not isinstance(token, bytes):
raise TypeError("token must be bytes.")
current_time = int(time.time())
try:
data = base64.urlsafe_b64decode(token)
except (TypeError, binascii.Error):
raise InvalidToken
if not data or (six.indexbytes(data, 0) != 0x81):
raise InvalidToken
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(data[:-32] + associated_data)
try:
h.verify(data[-32:])
except InvalidSignature:
raise InvalidToken
iv = data[1:17]
ciphertext = data[17:-32]
decryptor = Cipher(
algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
).decryptor()
plaintext_padded = decryptor.update(ciphertext)
try:
plaintext_padded += decryptor.finalize()
except ValueError:
raise InvalidToken
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
unpadded = unpadder.update(plaintext_padded)
try:
unpadded += unpadder.finalize()
except ValueError:
raise InvalidToken
return unpadded
示例14: opdata1_decrypt_item
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def opdata1_decrypt_item(data, key, hmac_key, aes_size=C_AES_SIZE, ignore_hmac=False):
key_size = KEY_SIZE[aes_size]
assert len(key) == key_size
assert len(data) >= OPDATA1_MINIMUM_SIZE
plaintext_length, iv, cryptext, expected_hmac, hmac_d_data = opdata1_unpack(data)
if not ignore_hmac:
verifier = HMAC(hmac_key, SHA256(), backend=_backend)
verifier.update(hmac_d_data)
if len(verifier.copy().finalize()) != len(expected_hmac):
raise ValueError("Got unexpected HMAC length (expected %d bytes, got %d bytes)" % (
len(expected_hmac),
len(got_hmac)
))
try:
verifier.verify(expected_hmac)
except InvalidSignature:
raise ValueError("HMAC did not match for opdata1 record")
aes = Cipher(algorithms.AES(key), modes.CBC(iv), backend=_backend)
decryptor = aes.decryptor()
decrypted = decryptor.update(cryptext) + decryptor.finalize()
unpadded = padding.ab_unpad(decrypted, plaintext_length)
return unpadded
示例15: decrypt
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import verify [as 别名]
def decrypt(self, token):
if not isinstance(token, bytes):
raise TypeError("token must be bytes")
if not token or six.indexbytes(token, 0) != 0x80:
raise InvalidToken
hmac = token[-32:]
h = HMAC(self.mac_key, hashes.SHA256(), backend=self.backend)
h.update(token[:-32])
try:
h.verify(hmac)
except InvalidSignature:
raise InvalidToken
iv = token[1:17]
ciphertext = token[17:-32]
decryptor = Cipher(algorithms.AES(self.aes_key), modes.CBC(iv), self.backend).decryptor()
plaintext_padded = decryptor.update(ciphertext)
try:
plaintext_padded += decryptor.finalize()
except ValueError:
raise InvalidToken
plaintext = self.remove_padding(plaintext_padded, algorithms.AES.block_size)
try:
data_id, = struct.unpack(config.FORMAT_CHAR, plaintext[:8])
except struct.error:
raise InvalidToken
if data_id == config.DUMMY_ID:
raise DummyFileFound
data = plaintext[8:]
return data_id, data