def save(key: RSA.RsaKey, *, name: str, secret: str = None) -> None: if secret is not None: secret = secret.encode() path = to_file_path(name) content = key.exportKey(passphrase=secret) with open(path, mode='wb') as file: file.write(content) cache[name] = key
def decrypt(message: bytes, *, private_key: RSA.RsaKey) -> bytes: indexes_increments = [ 0, private_key.size_in_bytes(), NONCE_LENGTH, MAC_TAG_LENGTH ] indexes = list(accumulate(indexes_increments)) + [None] encrypted_session_key, nonce, tag, encrypted = [ message[previous_index:index] for previous_index, index in zip(indexes, indexes[1:]) ] session_key = decrypt_rsa(encrypted_session_key, private_key=private_key) cipher = AES.new(session_key, mode=AES.MODE_EAX, nonce=nonce) return cipher.decrypt_and_verify(encrypted, received_mac_tag=tag)
def private_key_to_string(private_key: RsaKey) -> str: return private_key.exportKey(pkcs=_PKCS_NUMBER_PRIVATE_KEY).decode()
def public_key_to_string(public_key: RsaKey) -> str: return re.sub(_PATTERN_RSA, _REPLACEMENT_RSA, public_key.exportKey().decode())
def flatten(self, obj: RsaKey, data): data["rsa_key"] = base64.b64encode(obj.export_key()).decode("utf-8") return data
def test_encrypt(public_key: RSA.RsaKey, message: bytes) -> None: result = encrypt(message, public_key=public_key) assert isinstance(result, bytes) assert len(result) == (public_key.size_in_bytes() + NONCE_LENGTH + MAC_TAG_LENGTH + len(message))