diff --git a/electrum/crypto.py b/electrum/crypto.py index 58f66c2d1..40101200e 100644 --- a/electrum/crypto.py +++ b/electrum/crypto.py @@ -190,6 +190,7 @@ def _hash_password(password: Union[bytes, str], *, version: int) -> bytes: def pw_encode_bytes(data: bytes, password: Union[bytes, str], *, version: int) -> str: + """plaintext bytes -> base64 ciphertext""" if version not in KNOWN_PW_HASH_VERSIONS: raise UnexpectedPasswordHashVersion(version) # derive key from password @@ -199,7 +200,9 @@ def pw_encode_bytes(data: bytes, password: Union[bytes, str], *, version: int) - ciphertext_b64 = base64.b64encode(ciphertext) return ciphertext_b64.decode('utf8') + def pw_decode_bytes(data: str, password: Union[bytes, str], *, version: int) -> bytes: + """base64 ciphertext -> plaintext bytes""" if version not in KNOWN_PW_HASH_VERSIONS: raise UnexpectedPasswordHashVersion(version) data_bytes = bytes(base64.b64decode(data)) @@ -212,15 +215,22 @@ def pw_decode_bytes(data: str, password: Union[bytes, str], *, version: int) -> raise InvalidPassword() from e return d + def pw_encode(data: str, password: Union[bytes, str, None], *, version: int) -> str: + """plaintext str -> base64 ciphertext""" if not password: return data - return pw_encode_bytes(to_bytes(data, "utf8"), password, version=version) + plaintext_bytes = to_bytes(data, "utf8") + return pw_encode_bytes(plaintext_bytes, password, version=version) + def pw_decode(data: str, password: Union[bytes, str, None], *, version: int) -> str: + """base64 ciphertext -> plaintext str""" if password is None: return data - return to_string(pw_decode_bytes(data, password, version=version), "utf8") + plaintext_bytes = pw_decode_bytes(data, password, version=version) + plaintext_str = to_string(plaintext_bytes, "utf8") + return plaintext_str def sha256(x: Union[bytes, str]) -> bytes: