def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
python类Hash()的实例源码
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def rsa_key_fingerprint(key):
""" Return the SHA256 fingerprint of an RSA public or private key in url safe BASE64 """
fp = hashes.Hash(algorithm=hashes.SHA256(), backend=default_backend())
if isinstance(key, rsa.RSAPrivateKey):
fp.update(key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
elif isinstance(key, rsa.RSAPublicKey):
fp.update(key.public_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PublicFormat.PKCS1
))
return urlsafe_b64encode(fp.finalize()).decode()
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def generate_fingerprint(public_key):
try:
pub_bytes = public_key.encode('utf-8')
# Test that the given public_key string is a proper ssh key. The
# returned object is unused since pyca/cryptography does not have a
# fingerprint method.
serialization.load_ssh_public_key(
pub_bytes, backends.default_backend())
pub_data = base64.b64decode(public_key.split(' ')[1])
digest = hashes.Hash(hashes.MD5(), backends.default_backend())
digest.update(pub_data)
md5hash = digest.finalize()
raw_fp = binascii.hexlify(md5hash)
if six.PY3:
raw_fp = raw_fp.decode('ascii')
return ':'.join(a + b for a, b in zip(raw_fp[::2], raw_fp[1::2]))
except Exception:
raise exception.InvalidKeypair(
reason=_('failed to generate fingerprint'))
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def check(self):
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
off = self.offset
if self.copyMethod == 0 and (1 << 20) > self.size >= 0x800+0xA00 and self.address == 0x08006000:
if self.sectionData[0x50 : 0x53] == b"K9L":
self.guessedType = self.sectionData[0x50 : 0x54].decode("ascii")
elif self.sectionData[0x50 : 0x54] == b"\xFF\xFF\xFF\xFF":
self.guessedType = "K9L0"
elif self.copyMethod == 0 and (1 << 20) > self.size >= 0xA00 and self.address == 0x08006800:
self.guessedType = "Kernel9"
elif self.copyMethod == 1 and self.size >= 0xA00:
if self.sectionData[0x100 : 0x104] == b"NCCH":
self.guessedType = "Kernel11 modules"
H = hashes.Hash(hashes.SHA256(), backend=default_backend())
H.update(self.sectionData)
self.hashIsValid = self.hash == H.finalize()
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def derive(self, key_material):
if self._used:
raise AlreadyFinalized
self._used = True
if not isinstance(key_material, bytes):
raise TypeError("key_material must be bytes.")
output = [b""]
outlen = 0
counter = 1
while self._length > outlen:
h = hashes.Hash(self._algorithm, self._backend)
h.update(key_material)
h.update(_int_to_u32be(counter))
if self._sharedinfo is not None:
h.update(self._sharedinfo)
output.append(h.finalize())
outlen += len(output[-1])
counter += 1
return b"".join(output)[:self._length]
def test_ecc_static_length_signature(algorithm):
private_key = ec.generate_private_key(
curve=algorithm.signing_algorithm_info(),
backend=default_backend()
)
hasher = hashes.Hash(
algorithm.signing_hash_type(),
backend=default_backend()
)
data = b'aifuhaw9fe48haw9e8cnavwp9e8fhaw9438fnhjzsudfvhnsa89w74fhp90se8rhgfi'
hasher.update(data)
digest = hasher.finalize()
signature = _ecc_static_length_signature(
key=private_key,
algorithm=algorithm,
digest=digest
)
assert len(signature) == algorithm.signature_len
private_key.public_key().verify(
signature=signature,
data=data,
signature_algorithm=ec.ECDSA(algorithm.signing_hash_type())
)
def _encrypted_data_keys_hash(hasher, encrypted_data_keys):
"""Generates the expected hash for the provided encrypted data keys.
:param hasher: Existing hasher to use
:type hasher: cryptography.hazmat.primitives.hashes.Hash
:param iterable encrypted_data_keys: Encrypted data keys to hash
:returns: Concatenated, sorted, list of all hashes
:rtype: bytes
"""
hashed_keys = []
for edk in encrypted_data_keys:
serialized_edk = serialize_encrypted_data_key(edk)
_hasher = hasher.copy()
_hasher.update(serialized_edk)
hashed_keys.append(_hasher.finalize())
return b''.join(sorted(hashed_keys))
# 512 bits of 0 for padding between hashes in decryption materials cache ID generation.
def generate_fingerprint(public_key):
try:
pub_bytes = public_key.encode('utf-8')
# Test that the given public_key string is a proper ssh key. The
# returned object is unused since pyca/cryptography does not have a
# fingerprint method.
serialization.load_ssh_public_key(
pub_bytes, backends.default_backend())
pub_data = base64.b64decode(public_key.split(' ')[1])
digest = hashes.Hash(hashes.MD5(), backends.default_backend())
digest.update(pub_data)
md5hash = digest.finalize()
raw_fp = binascii.hexlify(md5hash)
if six.PY3:
raw_fp = raw_fp.decode('ascii')
return ':'.join(a + b for a, b in zip(raw_fp[::2], raw_fp[1::2]))
except Exception:
raise exception.InvalidKeypair(
reason=_('failed to generate fingerprint'))
def stretch(passw, iv1):
# hash the external iv and the password 8192 times
digest = iv1 + (16 * b"\x00")
for i in range(8192):
passHash = hashes.Hash(hashes.SHA256(), backend=default_backend())
passHash.update(digest)
passHash.update(bytes(passw, "utf_16_le"))
digest = passHash.finalize()
return digest
# encrypting function
# arguments:
# infile: plaintext file path
# outfile: ciphertext file path
# passw: encryption password
# bufferSize: encryption buffer size, must be a multiple of
# AES block size (16)
# using a larger buffer speeds up things when dealing
# with big files
def fingerprint(self, algorithm):
h = hashes.Hash(algorithm, self._backend)
h.update(self.public_bytes(serialization.Encoding.DER))
return h.finalize()
def fingerprint(self, algorithm):
h = hashes.Hash(algorithm, self._backend)
bio = self._backend._create_mem_bio_gc()
res = self._backend._lib.i2d_X509_CRL_bio(
bio, self._x509_crl
)
self._backend.openssl_assert(res == 1)
der = self._backend._read_mem_bio(bio)
h.update(der)
return h.finalize()
def __init__(self, backend, private_key, algorithm):
self._backend = backend
self._private_key = private_key
self._digest = hashes.Hash(algorithm, backend)
def __init__(self, backend, public_key, signature, algorithm):
self._backend = backend
self._public_key = public_key
self._signature = signature
self._algorithm = algorithm
self._hash_ctx = hashes.Hash(self._algorithm, self._backend)
def __init__(self, backend, private_key, algorithm):
self._backend = backend
self._private_key = private_key
self._algorithm = algorithm
self._hash_ctx = hashes.Hash(self._algorithm, self._backend)
def _hash(self):
return hashes.Hash(self._algorithm, self._backend)
def fingerprint(self, algorithm):
h = hashes.Hash(algorithm, self._backend)
h.update(self.public_bytes(serialization.Encoding.DER))
return h.finalize()
def __init__(self, backend, private_key, algorithm):
self._backend = backend
self._private_key = private_key
self._digest = hashes.Hash(algorithm, backend)