本文整理汇总了Python中cryptography.hazmat.primitives.hmac.HMAC类的典型用法代码示例。如果您正苦于以下问题:Python HMAC类的具体用法?Python HMAC怎么用?Python HMAC使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HMAC类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: salted_hmac
def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-HASH of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
:type key_salt: any
:type value: any
:type secret: any
:rtype: HMAC
"""
if secret is None:
secret = settings.SECRET_KEY
key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
digest = hashes.Hash(settings.CRYPTOGRAPHY_DIGEST,
backend=settings.CRYPTOGRAPHY_BACKEND)
digest.update(key_salt + secret)
key = digest.finalize()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
h = HMAC(key, settings.CRYPTOGRAPHY_DIGEST,
backend=settings.CRYPTOGRAPHY_BACKEND)
h.update(force_bytes(value))
return h
示例2: _verify_signature
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
示例3: _decrypt_data
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
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: encrypt_with_hmac
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
示例6: decrypt
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()
示例7: encrypt
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
示例8: _get_hmac
def _get_hmac(key, ciphertext, digest_method):
hmac = HMAC(
key,
get_digest(digest_method),
backend=default_backend()
)
hmac.update(ciphertext)
return hmac.finalize()
示例9: signature
def signature(self, value):
"""
:type value: any
:rtype: HMAC
"""
h = HMAC(self.key, self.digest, backend=settings.CRYPTOGRAPHY_BACKEND)
h.update(force_bytes(value))
return h
示例10: Decryptor
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
示例11: calculate_hmac
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()
示例12: verify_hmac
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)
示例13: compute_verify_data
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()
示例14: generate_mac
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()
示例15: _a
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()