staking-deposit-cli/eth2deposit/utils/crypto.py

42 lines
1.3 KiB
Python
Raw Normal View History

from typing import Any
2020-02-18 16:03:52 +00:00
from Crypto.Hash import (
SHA256 as _sha256,
SHA512 as _sha512,
)
from Crypto.Protocol.KDF import (
scrypt as _scrypt,
HKDF as _HKDF,
PBKDF2 as _PBKDF2,
)
from Crypto.Cipher import (
AES as _AES
)
2020-02-18 16:44:32 +00:00
def SHA256(x: bytes) -> bytes:
2020-02-18 16:03:52 +00:00
return _sha256.new(x).digest()
def scrypt(*, password: str, salt: str, n: int, r: int, p: int, dklen: int) -> bytes:
assert(n < 2**(128 * r / 8))
res = _scrypt(password=password, salt=salt, key_len=dklen, N=n, r=r, p=p)
return res if isinstance(res, bytes) else res[0] # PyCryptodome can return Tuple[bytes]
2020-06-26 14:10:19 +00:00
def PBKDF2(*, password: bytes, salt: bytes, dklen: int, c: int, prf: str) -> bytes:
2020-02-18 16:03:52 +00:00
assert('sha' in prf)
_hash = _sha256 if 'sha256' in prf else _sha512
2020-06-26 14:10:19 +00:00
res = _PBKDF2(password=password, salt=salt, dkLen=dklen, count=c, hmac_hash_module=_hash) # type: ignore
2020-02-18 16:03:52 +00:00
return res if isinstance(res, bytes) else res[0] # PyCryptodome can return Tuple[bytes]
def HKDF(*, salt: bytes, IKM: bytes, L: int, info: bytes=b'') -> bytes:
res = _HKDF(master=IKM, key_len=L, salt=salt, hashmod=_sha256, context=info)
2020-02-18 16:03:52 +00:00
return res if isinstance(res, bytes) else res[0] # PyCryptodome can return Tuple[bytes]
def AES_128_CTR(*, key: bytes, iv: bytes) -> Any:
2020-05-26 09:32:20 +00:00
assert len(key) == 16
2020-02-18 16:03:52 +00:00
return _AES.new(key=key, mode=_AES.MODE_CTR, initial_value=iv, nonce=b'')