diff options
author | David Reid <dreid@dreid.org> | 2013-12-23 15:01:28 -0800 |
---|---|---|
committer | David Reid <dreid@dreid.org> | 2014-02-03 10:05:26 -0800 |
commit | ab33266b16d9a1cd3cf6abcf0a7b80e86f915d95 (patch) | |
tree | 2803997acb2b8ee2560fedb97c6d9b22d3f43a57 | |
parent | fa9431d29f90b034aea72f4cc8d1f6ce94159603 (diff) | |
download | cryptography-ab33266b16d9a1cd3cf6abcf0a7b80e86f915d95.tar.gz cryptography-ab33266b16d9a1cd3cf6abcf0a7b80e86f915d95.tar.bz2 cryptography-ab33266b16d9a1cd3cf6abcf0a7b80e86f915d95.zip |
hkdf
-rw-r--r-- | cryptography/hkdf.py | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/cryptography/hkdf.py b/cryptography/hkdf.py new file mode 100644 index 00000000..9665ce57 --- /dev/null +++ b/cryptography/hkdf.py @@ -0,0 +1,43 @@ +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hmac +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives import constant_time + +def hkdf_derive(input_key, key_length, salt=None, info=None, hash=None, backend=None): + if hash is None: + hash = hashes.SHA256() + + if backend is None: + backend = default_backend() + + if info is None: + info = b"" + + if salt is None: + salt = b"\x00" * (hash.digest_size // 8) + + h = hmac.HMAC(salt, hash, backend=backend) + h.update(input_key) + PRK = h.finalize() + + output = [b''] + counter = 1 + + while (hash.digest_size // 8) * len(output) < key_length: + h = hmac.HMAC(PRK, hash, backend=backend) + h.update(output[-1]) + h.update(info) + h.update(chr(counter)) + output.append(h.finalize()) + counter += 1 + + return b"".join(output)[:key_length] + + +def hkdf_verify(expected, input_key, key_length, salt=None, info=None, + hash=None, backend=None): + derived = hkdf_derive(input_key, key_length, salt=salt, info=info, + hash=hash, backend=backend) + + return constant_time.bytes_eq(expected, derived) + |