本文整理汇总了Python中cryptography.hazmat.primitives.constant_time.bytes_eq方法的典型用法代码示例。如果您正苦于以下问题:Python constant_time.bytes_eq方法的具体用法?Python constant_time.bytes_eq怎么用?Python constant_time.bytes_eq使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.hazmat.primitives.constant_time
的用法示例。
在下文中一共展示了constant_time.bytes_eq方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decrypt
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [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: decrypt_header
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def decrypt_header(self, data: bytes) -> bytes:
if len(data) != HEADER_LEN + MAC_LEN:
raise ValueError(
"Unexpected header length: {}, expected {} + {}".format(
len(data), HEADER_LEN, MAC_LEN
)
)
header_ciphertext = data[:HEADER_LEN]
header_mac = data[HEADER_LEN:]
mac_secret = self.ingress_mac.digest()[:HEADER_LEN]
aes = self.mac_enc(mac_secret)[:HEADER_LEN]
self.ingress_mac.update(sxor(aes, header_ciphertext))
expected_header_mac = self.ingress_mac.digest()[:HEADER_LEN]
if not bytes_eq(expected_header_mac, header_mac):
raise DecryptionError(
"Invalid header mac: expected {}, got {}".format(
expected_header_mac, header_mac
)
)
return self.aes_dec.update(header_ciphertext)
示例3: decrypt_body
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def decrypt_body(self, data: bytes, body_size: int) -> bytes:
read_size = roundup_16(body_size)
if len(data) < read_size + MAC_LEN:
raise ValueError(
"Insufficient body length; Got {}, wanted {} + {}".format(
len(data), read_size, MAC_LEN
)
)
frame_ciphertext = data[:read_size]
frame_mac = data[read_size : read_size + MAC_LEN]
self.ingress_mac.update(frame_ciphertext)
fmac_seed = self.ingress_mac.digest()[:MAC_LEN]
self.ingress_mac.update(sxor(self.mac_enc(fmac_seed), fmac_seed))
expected_frame_mac = self.ingress_mac.digest()[:MAC_LEN]
if not bytes_eq(expected_frame_mac, frame_mac):
raise DecryptionError(
"Invalid frame mac: expected {}, got {}".format(
expected_frame_mac, frame_mac
)
)
return self.aes_dec.update(frame_ciphertext)[:body_size]
示例4: decrypt_raw_bytes
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def decrypt_raw_bytes(self, data: bytes, size: int) -> bytes:
"""
same as decrypt_body() but no roundup
"""
if len(data) < size + MAC_LEN:
raise ValueError(
"Insufficient body length; Got {}, wanted {} + {}".format(
len(data), size, MAC_LEN
)
)
frame_ciphertext = data[:size]
frame_mac = data[size : size + MAC_LEN]
self.ingress_mac.update(frame_ciphertext)
fmac_seed = self.ingress_mac.digest()[:MAC_LEN]
self.ingress_mac.update(sxor(self.mac_enc(fmac_seed), fmac_seed))
expected_frame_mac = self.ingress_mac.digest()[:MAC_LEN]
if not bytes_eq(expected_frame_mac, frame_mac):
raise DecryptionError(
"Invalid frame mac: expected {}, got {}".format(
expected_frame_mac, frame_mac
)
)
return self.aes_dec.update(frame_ciphertext)[:size]
示例5: finalize
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def finalize(self):
# CommonCrypto has a yet another bug where you must make at least one
# call to update. If you pass just AAD and call finalize without a call
# to update you'll get null bytes for tag. The following update call
# prevents this issue, which is present in at least 10.8 and 10.9.
# Filed as rdar://18314580
self.update(b"")
tag_size = self._cipher.block_size // 8
tag_buf = self._backend._ffi.new("unsigned char[]", tag_size)
tag_len = self._backend._ffi.new("size_t *", tag_size)
res = self._backend._lib.CCCryptorGCMFinal(
self._ctx[0], tag_buf, tag_len
)
self._backend._check_cipher_response(res)
self._backend._release_cipher_ctx(self._ctx)
self._tag = self._backend._ffi.buffer(tag_buf)[:]
if (self._operation == self._backend._lib.kCCDecrypt and
not constant_time.bytes_eq(
self._tag[:len(self._mode.tag)], self._mode.tag
)):
raise InvalidTag
return b""
示例6: aes_key_unwrap
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def aes_key_unwrap(wrapping_key, wrapped_key, backend):
if len(wrapped_key) < 24:
raise InvalidUnwrap("Must be at least 24 bytes")
if len(wrapped_key) % 8 != 0:
raise InvalidUnwrap("The wrapped key must be a multiple of 8 bytes")
if len(wrapping_key) not in [16, 24, 32]:
raise ValueError("The wrapping key must be a valid AES key length")
aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6"
r = [wrapped_key[i:i + 8] for i in range(0, len(wrapped_key), 8)]
a = r.pop(0)
a, r = _unwrap_core(wrapping_key, a, r, backend)
if not bytes_eq(a, aiv):
raise InvalidUnwrap()
return b"".join(r)
示例7: handle
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def handle(self, request):
name = request['headers'].get(self.id_header, None)
key = request['headers'].get(self.key_header, None)
if name is None and key is None:
self.logger.debug('Ignoring request no relevant headers provided')
return None
validated = False
try:
val = self.store.get(self._db_key(name))
if val is None:
raise ValueError("No such ID")
if constant_time.bytes_eq(val.encode('utf-8'),
key.encode('utf-8')):
validated = True
except Exception: # pylint: disable=broad-except
self.audit_svc_access(log.AUDIT_SVC_AUTH_FAIL,
request['client_id'], name)
return False
if validated:
self.audit_svc_access(log.AUDIT_SVC_AUTH_PASS,
request['client_id'], name)
request['remote_user'] = name
return True
self.audit_svc_access(log.AUDIT_SVC_AUTH_FAIL,
request['client_id'], name)
return False
示例8: check_password
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def check_password(entered_password, user_password, seed=None):
""" Version checking and returning the password
:arg entered_password: password entered by the user.
:type entered_password: str (Python 3) or unicode (Python 2)
:arg user_password: the hashed string fetched from the database.
:type user_password: bytes
:return: a Boolean depending upon the entered_password, True if the
password matches
"""
if not isinstance(entered_password, six.text_type):
raise ValueError("Entered password is not unicode text")
if isinstance(user_password, six.text_type):
user_password = user_password.encode("utf-8")
if not user_password.count(b"$") >= 2:
raise pagure.exceptions.PagureException(
"Password of unknown version found in the database"
)
_, version, user_password = user_password.split(b"$", 2)
if version == b"2":
password = bcrypt.hashpw(
entered_password.encode("utf-8"), user_password
)
elif version == b"1":
password = "%s%s" % (entered_password, seed)
password = (
hashlib.sha512(password.encode("utf-8"))
.hexdigest()
.encode("utf-8")
)
else:
raise pagure.exceptions.PagureException(
"Password of unknown version found in the database"
)
return constant_time.bytes_eq(password, user_password)
示例9: decrypt
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def decrypt(
data: bytes, privkey: datatypes.PrivateKey, shared_mac_data: bytes = b""
) -> bytes:
"""Decrypt data with ECIES method using the given private key
1) generate shared-secret = kdf( ecdhAgree(myPrivKey, msg[1:65]) )
2) verify tag
3) decrypt
ecdhAgree(r, recipientPublic) == ecdhAgree(recipientPrivate, R)
[where R = r*G, and recipientPublic = recipientPrivate*G]
"""
if data[:1] != b"\x04":
raise DecryptionError("wrong ecies header")
# 1) generate shared-secret = kdf( ecdhAgree(myPrivKey, msg[1:65]) )
shared = data[1 : 1 + PUBKEY_LEN]
key_material = ecdh_agree(privkey, keys.PublicKey(shared))
key = kdf(key_material)
key_enc, key_mac = key[: KEY_LEN // 2], key[KEY_LEN // 2 :]
key_mac = sha256(key_mac).digest()
tag = data[-KEY_LEN:]
# 2) Verify tag
expected_tag = hmac_sha256(
key_mac, data[1 + PUBKEY_LEN : -KEY_LEN] + shared_mac_data
)
if not bytes_eq(expected_tag, tag):
raise DecryptionError("Failed to verify tag")
# 3) Decrypt
algo = CIPHER(key_enc)
blocksize = algo.block_size // 8
iv = data[1 + PUBKEY_LEN : 1 + PUBKEY_LEN + blocksize]
ciphertext = data[1 + PUBKEY_LEN + blocksize : -KEY_LEN]
ctx = Cipher(algo, MODE(iv), default_backend()).decryptor()
return ctx.update(ciphertext) + ctx.finalize()
示例10: _open_aes_ctr
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def _open_aes_ctr(key, nonce, ciphertext, expected_hmac, digest_method):
data_key, hmac_key = _halve_key(key)
hmac = _get_hmac(hmac_key, ciphertext, digest_method)
# Check the HMAC before we decrypt to verify ciphertext integrity
if not constant_time.bytes_eq(hmac, expected_hmac):
raise IntegrityError("Computed HMAC on %s does not match stored HMAC")
decryptor = Cipher(
algorithms.AES(data_key),
modes.CTR(nonce),
backend=default_backend()
).decryptor()
return decryptor.update(ciphertext) + decryptor.finalize()
示例11: constant_time_compare
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def constant_time_compare(val1, val2):
"""
:type val1: any
:type val2: any
:rtype: bool
"""
return constant_time.bytes_eq(force_bytes(val1), force_bytes(val2))
示例12: _verify_challenge
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def _verify_challenge(received_challenge, sent_challenge):
return received_challenge \
and sent_challenge \
and isinstance(received_challenge, six.string_types) \
and isinstance(sent_challenge, six.string_types) \
and constant_time.bytes_eq(
to_bytes(sent_challenge),
to_bytes(received_challenge)
)
示例13: _verify_rp_id_hash
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def _verify_rp_id_hash(auth_data_rp_id_hash, rp_id):
rp_id_hash = hashlib.sha256(to_bytes(rp_id)).digest()
return constant_time.bytes_eq(auth_data_rp_id_hash, rp_id_hash)
示例14: __eq__
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def __eq__(self, other):
if not isinstance(other, SubjectKeyIdentifier):
return NotImplemented
return constant_time.bytes_eq(self.digest, other.digest)
示例15: verify
# 需要导入模块: from cryptography.hazmat.primitives import constant_time [as 别名]
# 或者: from cryptography.hazmat.primitives.constant_time import bytes_eq [as 别名]
def verify(self, signature):
digest = self.finalize()
if not constant_time.bytes_eq(digest, signature):
raise InvalidSignature("Signature did not match digest.")