本文整理汇总了Python中cryptography.hazmat.primitives.hmac.HMAC.finalize方法的典型用法代码示例。如果您正苦于以下问题:Python HMAC.finalize方法的具体用法?Python HMAC.finalize怎么用?Python HMAC.finalize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.hazmat.primitives.hmac.HMAC
的用法示例。
在下文中一共展示了HMAC.finalize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: encrypt
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def encrypt(pubkey, data):
public_key = _pub_to_public(pubkey)
private_key = ec.generate_private_key(ec.SECP256K1(), openssl.backend)
secret = private_key.exchange(ec.ECDH(), public_key)
key = hashlib.sha512(secret).digest()
enckey = key[0:32]
mackey = key[32:64]
iv = os.urandom(16)
padder = padding.PKCS7(128).padder()
paddeddata = padder.update(data) + padder.finalize()
cipher = Cipher(algorithms.AES(enckey), modes.CBC(iv), openssl.backend)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(paddeddata) + encryptor.finalize()
s = serialize.Serializer()
s.bytes(iv)
s.uint(0x02ca, 2)
public_numbers = private_key.public_key().public_numbers()
x = public_numbers.x.to_bytes(32, 'big').lstrip(b'\x00')
s.uint(len(x), 2)
s.bytes(x)
y = public_numbers.y.to_bytes(32, 'big').lstrip(b'\x00')
s.uint(len(y), 2)
s.bytes(y)
s.bytes(ciphertext)
maccer = HMAC(mackey, hashes.SHA256(), openssl.backend)
maccer.update(s.data)
mac = maccer.finalize()
s.bytes(mac)
return s.data
示例2: encrypt_with_hmac
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def encrypt_with_hmac(self, data, data_id, iv):
if not isinstance(data, bytes):
raise TypeError("data must be bytes.")
if not isinstance(data_id, int):
raise TypeError("data_id must be int.")
main_parts = (
struct.pack(config.FORMAT_CHAR, data_id) + data
)
# PKCS7 padding
padded_data = self.add_padding(main_parts, algorithms.AES.block_size)
# AES with CBC mode
encryptor = Cipher(algorithms.AES(self.aes_key), modes.CBC(iv), backend=self.backend).encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
basic_parts = (
b"\x80" + iv + ciphertext
)
h = HMAC(self.mac_key, hashes.SHA256(), backend=self.backend)
h.update(basic_parts)
hmac = h.finalize()
return basic_parts + hmac
示例3: checkHMAC
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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.
示例4: _get_hmac
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def _get_hmac(key, ciphertext, digest_method):
hmac = HMAC(
key,
get_digest(digest_method),
backend=default_backend()
)
hmac.update(ciphertext)
return hmac.finalize()
示例5: Decryptor
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
class Decryptor(object):
def __init__(self, rsa_private_key_pem):
if not isinstance(rsa_private_key_pem, bytes):
rsa_private_key_pem = rsa_private_key_pem.encode("ascii")
self.rsa_private_key = serialization.load_pem_private_key(
data=rsa_private_key_pem,
password=None,
backend=default_backend())
self.cipher = None
self.authenticator = None
self.buf = b""
def update(self, data):
self.buf += data
if self.cipher is None:
if len(self.buf) < 8:
return b""
if self.buf[0:6] != FILEMAGIC:
raise EncryptorError("Invalid magic bytes")
cipherkeylen = struct.unpack(">H", self.buf[6:8])[0]
if len(self.buf) < 8 + cipherkeylen:
return b""
pad = padding.OAEP(mgf=padding.MGF1(algorithm=SHA1()),
algorithm=SHA1(),
label=None)
try:
plainkey = self.rsa_private_key.decrypt(self.buf[8:8 + cipherkeylen], pad)
except AssertionError:
raise EncryptorError("Decrypting key data failed")
if len(plainkey) != 64:
raise EncryptorError("Integrity check failed")
key = plainkey[0:16]
nonce = plainkey[16:32]
auth_key = plainkey[32:64]
self.cipher = Cipher(algorithms.AES(key), modes.CTR(nonce), backend=default_backend()).decryptor()
self.authenticator = HMAC(auth_key, SHA256(), backend=default_backend())
self.buf = self.buf[8 + cipherkeylen:]
if len(self.buf) < 32:
return b""
self.authenticator.update(self.buf[:-32])
result = self.cipher.update(self.buf[:-32])
self.buf = self.buf[-32:]
return result
def finalize(self):
if self.cipher is None:
return b"" # empty encrypted input yields empty plaintext output
elif self.buf != self.authenticator.finalize():
raise EncryptorError("Integrity check failed")
result = self.cipher.finalize()
self.buf = b""
self.cipher = None
self.authenticator = None
return result
示例6: calculate_hmac
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def calculate_hmac(key, data):
"""Shortcut for calculating HMAC of a string."""
h = HMAC(
key=key,
algorithm=hashes.SHA256(),
backend=backend
)
h.update(data)
return h.finalize()
示例7: __init__
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def __init__(self, key, backend=None):
if backend is None:
backend = default_backend()
key = base64.urlsafe_b64decode(key)
if len(key) != 32:
raise ValueError(
"Fernet key must be 32 url-safe base64-encoded bytes."
)
h = HMAC(key, hashes.SHA256(), backend=backend)
h.update(b"\x00")
self._signing_key = h.finalize()[:16]
h = HMAC(key, hashes.SHA256(), backend=backend)
h.update(b"\x01")
self._encryption_key = h.finalize()[:16]
self._backend = backend
示例8: compute_verify_data
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def compute_verify_data(self, basekey, handshake_context):
hash_len = self.hash.digest_size
finished_key = self.expand_label(basekey, b"finished", b"", hash_len)
h = Hash(self.hash, backend=default_backend())
h.update(handshake_context)
hash_value = h.finalize()
hm = HMAC(finished_key, self.hash, default_backend())
hm.update(hash_value)
return hm.finalize()
示例9: generate_mac
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def generate_mac(key, data, algorithm="SHA256", backend=BACKEND):
""" Returns a message authentication code for verifying the integrity and
authenticity of data by entities that possess the key.
Note this is a lower level function then apply_mac and
only returns the mac itself.
The mac is generated via HMAC with the specified algorithm and key. """
hasher = HMAC(key, getattr(hashes, algorithm.upper())(), backend=backend)
hasher.update(algorithm + '::' + data)
return hasher.finalize()
示例10: _a
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def _a(secret, hash_algorithm, n, seed):
"""
a() is defined as:
a(0) = seed
a(i) = HMAC_hash(secret, A(i-1))
"""
if n == 0:
return seed
else:
h = HMAC(secret, hash_algorithm, default_backend())
h.update(_a(secret, hash_algorithm, n - 1, seed))
return h.finalize()
示例11: _encrypt_cryptography
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def _encrypt_cryptography(b_plaintext, b_key1, b_key2, b_iv):
cipher = C_Cipher(algorithms.AES(b_key1), modes.CTR(b_iv), CRYPTOGRAPHY_BACKEND)
encryptor = cipher.encryptor()
padder = padding.PKCS7(algorithms.AES.block_size).padder()
b_ciphertext = encryptor.update(padder.update(b_plaintext) + padder.finalize())
b_ciphertext += encryptor.finalize()
# COMBINE SALT, DIGEST AND DATA
hmac = HMAC(b_key2, hashes.SHA256(), CRYPTOGRAPHY_BACKEND)
hmac.update(b_ciphertext)
b_hmac = hmac.finalize()
return to_bytes(hexlify(b_hmac), errors='surrogate_or_strict'), hexlify(b_ciphertext)
示例12: _p_hash
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def _p_hash(hash_algorithm, secret, seed, output_length):
"""
A seed expansion function that uses a single hash function to expand a
secret and seed into the number of bytes specified by output_length.
"""
result = bytearray()
i = 1
while len(result) < output_length:
h = HMAC(secret, hash_algorithm, default_backend())
h.update(_a(secret, hash_algorithm, i, seed))
h.update(seed)
result.extend(h.finalize())
i += 1
return bytes(result[:output_length])
示例13: __init__
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def __init__(self, key, backend=None):
if backend is None:
backend = default_backend()
# initialize a fernet object
self._f = Fernet(key, backend=backend)
key = base64.urlsafe_b64decode(key)
if len(key) != 32:
raise ValueError(
"Fernet2 key must be 32 url-safe base64-encoded bytes."
)
h0 = HMAC(key, hashes.SHA256(), backend=backend)
h1 = HMAC(key, hashes.SHA256(), backend=backend)
#
h0 .update(b"0")
h1 .update(b"1")
k0 = h0.finalize()[:16]
k1 = h1.finalize()[:16]
self._signing_key = k0
self._encryption_key = k1
self._backend = backend
示例14: _encrypt_from_parts
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def _encrypt_from_parts(self, data, current_time, iv):
if isinstance(data, six.text_type):
raise TypeError("Unicode-objects must be encoded before encryption")
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
encryptor = Cipher(algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend).encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
basic_parts = b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(basic_parts)
hmac = h.finalize()
return base64.urlsafe_b64encode(basic_parts + hmac)
示例15: _encrypt_from_parts
# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def _encrypt_from_parts(self, data, current_time, iv):
utils._check_bytes("data", data)
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
encryptor = Cipher(
algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
).encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
basic_parts = (
b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
)
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(basic_parts)
hmac = h.finalize()
return base64.urlsafe_b64encode(basic_parts + hmac)