|
| 1 | +import scrypt |
| 2 | + |
| 3 | +from typing import Union |
| 4 | + |
| 5 | + |
| 6 | +class ArgumentError(Exception): |
| 7 | + pass |
| 8 | + |
| 9 | + |
| 10 | +def generate_digest(message: str, |
| 11 | + password: str = None, |
| 12 | + maxtime: Union[float, int] = 0.5, |
| 13 | + salt: str = "", |
| 14 | + length: int = 64) -> bytes: |
| 15 | + """Multi-arity function for generating a digest. |
| 16 | +
|
| 17 | + Use KDF symmetric encryption given a password. |
| 18 | + Use deterministic hash function given a salt (or lack of password). |
| 19 | + """ |
| 20 | + |
| 21 | + if password and salt: |
| 22 | + raise ArgumentError("only provide a password or a salt, not both") |
| 23 | + |
| 24 | + if salt != "" and len(salt) < 16: |
| 25 | + raise ArgumentError("salts need to be minimum of 128bits (~16 characters)") |
| 26 | + |
| 27 | + if password: |
| 28 | + return scrypt.encrypt(message, password, maxtime=maxtime) |
| 29 | + else: |
| 30 | + return scrypt.hash(message, salt, buflen=length) |
| 31 | + |
| 32 | + |
| 33 | +def decrypt_digest(digest: bytes, |
| 34 | + password: str, |
| 35 | + maxtime: Union[float, int] = 0.5) -> bytes: |
| 36 | + """Decrypts digest using given password.""" |
| 37 | + |
| 38 | + return scrypt.decrypt(digest, password, maxtime) |
| 39 | + |
| 40 | + |
| 41 | +def validate_digest(digest: bytes, |
| 42 | + password: str, |
| 43 | + maxtime: Union[float, int] = 0.5) -> bool: |
| 44 | + """Validate digest using given password.""" |
| 45 | + |
| 46 | + try: |
| 47 | + scrypt.decrypt(digest, password, maxtime) |
| 48 | + return True |
| 49 | + except scrypt.error: |
| 50 | + return False |
0 commit comments