| 1 |
from typing_extensions import assert_never |
| 2 |
|
| 3 |
from cryptography.hazmat.backends import default_backend |
| 4 |
from cryptography.hazmat.primitives import hashes |
| 5 |
from cryptography.hazmat.primitives.kdf.hkdf import HKDF |
| 6 |
|
| 7 |
from .crypto_provider import CryptoProvider, HashFunction |
| 8 |
|
| 9 |
|
| 10 |
__all__ = [ |
| 11 |
"CryptoProviderImpl" |
| 12 |
] |
| 13 |
|
| 14 |
|
| 15 |
def get_hash_algorithm(hash_function: HashFunction) -> hashes.HashAlgorithm: |
| 16 |
""" |
| 17 |
Args: |
| 18 |
hash_function: Identifier of a hash function. |
| 19 |
|
| 20 |
Returns: |
| 21 |
The implementation of the hash function as a cryptography |
| 22 |
:class:`~cryptography.hazmat.primitives.hashes.HashAlgorithm` object. |
| 23 |
""" |
| 24 |
|
| 25 |
if hash_function is HashFunction.SHA_256: |
| 26 |
return hashes.SHA256() |
| 27 |
if hash_function is HashFunction.SHA_512: |
| 28 |
return hashes.SHA512() |
| 29 |
|
| 30 |
return assert_never(hash_function) |
| 31 |
|
| 32 |
|
| 33 |
class CryptoProviderImpl(CryptoProvider): |
| 34 |
""" |
| 35 |
Cryptography provider based on the Python package `cryptography <https://github.com/pyca/cryptography>`_. |
| 36 |
""" |
| 37 |
|
| 38 |
@staticmethod |
| 39 |
async def hkdf_derive( |
| 40 |
hash_function: HashFunction, |
| 41 |
length: int, |
| 42 |
salt: bytes, |
| 43 |
info: bytes, |
| 44 |
key_material: bytes |
| 45 |
) -> bytes: |
| 46 |
return HKDF( |
| 47 |
algorithm=get_hash_algorithm(hash_function), |
| 48 |
length=length, |
| 49 |
salt=salt, |
| 50 |
info=info, |
| 51 |
backend=default_backend() |
| 52 |
).derive(key_material) |