|
| 1 | +import base64 |
| 2 | +import secrets |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from cryptography.exceptions import InvalidTag as InvalidTagException |
| 6 | +from cryptography.hazmat.primitives import hashes, serialization |
| 7 | +from cryptography.hazmat.primitives.asymmetric import padding, rsa |
| 8 | +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
| 9 | + |
| 10 | +from .consts import ENCRYPTED_INPUT_VALUE_REGEXP |
| 11 | + |
| 12 | +ENCRYPTION_KEY_LENGTH = 32 |
| 13 | +ENCRYPTION_IV_LENGTH = 16 |
| 14 | +ENCRYPTION_AUTH_TAG_LENGTH = 16 |
| 15 | + |
| 16 | + |
| 17 | +def public_encrypt(value: str, *, public_key: rsa.RSAPublicKey) -> dict: |
| 18 | + """Encrypts the given value using AES cipher and the password for encryption using the public key. |
| 19 | +
|
| 20 | + The encryption password is a string of encryption key and initial vector used for cipher. |
| 21 | + It returns the encrypted password and encrypted value in BASE64 format. |
| 22 | +
|
| 23 | + Args: |
| 24 | + value (str): Password used to encrypt the private key encoded as base64 string. |
| 25 | + public_key (RSAPublicKey): Private key to use for decryption. |
| 26 | +
|
| 27 | + Returns: |
| 28 | + disc: Encrypted password and value. |
| 29 | + """ |
| 30 | + key_bytes = _crypto_random_object_id(ENCRYPTION_KEY_LENGTH).encode('utf-8') |
| 31 | + initialized_vector_bytes = _crypto_random_object_id(ENCRYPTION_IV_LENGTH).encode('utf-8') |
| 32 | + value_bytes = value.encode('utf-8') |
| 33 | + |
| 34 | + password_bytes = key_bytes + initialized_vector_bytes |
| 35 | + |
| 36 | + # NOTE: Auth Tag is appended to the end of the encrypted data, it has length of 16 bytes and ensures integrity of the data. |
| 37 | + cipher = Cipher(algorithms.AES(key_bytes), modes.GCM(initialized_vector_bytes, min_tag_length=ENCRYPTION_AUTH_TAG_LENGTH)) |
| 38 | + encryptor = cipher.encryptor() |
| 39 | + encrypted_value_bytes = encryptor.update(value_bytes) + encryptor.finalize() |
| 40 | + encrypted_password_bytes = public_key.encrypt( |
| 41 | + password_bytes, |
| 42 | + padding.OAEP( |
| 43 | + mgf=padding.MGF1(algorithm=hashes.SHA1()), |
| 44 | + algorithm=hashes.SHA1(), |
| 45 | + label=None, |
| 46 | + ), |
| 47 | + ) |
| 48 | + return { |
| 49 | + 'encrypted_value': base64.b64encode(encrypted_value_bytes + encryptor.tag).decode('utf-8'), |
| 50 | + 'encrypted_password': base64.b64encode(encrypted_password_bytes).decode('utf-8'), |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | +def private_decrypt( |
| 55 | + encrypted_password: str, |
| 56 | + encrypted_value: str, |
| 57 | + *, |
| 58 | + private_key: rsa.RSAPrivateKey, |
| 59 | +) -> str: |
| 60 | + """Decrypts the given encrypted value using the private key and password. |
| 61 | +
|
| 62 | + Args: |
| 63 | + encrypted_password (str): Password used to encrypt the private key encoded as base64 string. |
| 64 | + encrypted_value (str): Encrypted value to decrypt as base64 string. |
| 65 | + private_key (RSAPrivateKey): Private key to use for decryption. |
| 66 | +
|
| 67 | + Returns: |
| 68 | + str: Decrypted value. |
| 69 | + """ |
| 70 | + encrypted_password_bytes = base64.b64decode(encrypted_password.encode('utf-8')) |
| 71 | + encrypted_value_bytes = base64.b64decode(encrypted_value.encode('utf-8')) |
| 72 | + |
| 73 | + # Decrypt the password |
| 74 | + password_bytes = private_key.decrypt( |
| 75 | + encrypted_password_bytes, |
| 76 | + padding.OAEP( |
| 77 | + mgf=padding.MGF1(algorithm=hashes.SHA1()), |
| 78 | + algorithm=hashes.SHA1(), |
| 79 | + label=None, |
| 80 | + ), |
| 81 | + ) |
| 82 | + |
| 83 | + if len(password_bytes) != ENCRYPTION_KEY_LENGTH + ENCRYPTION_IV_LENGTH: |
| 84 | + raise ValueError('Decryption failed, invalid password length!') |
| 85 | + |
| 86 | + # Slice the encrypted into cypher and authentication tag |
| 87 | + authentication_tag_bytes = encrypted_value_bytes[-ENCRYPTION_AUTH_TAG_LENGTH:] |
| 88 | + encrypted_data_bytes = encrypted_value_bytes[:len(encrypted_value_bytes) - ENCRYPTION_AUTH_TAG_LENGTH] |
| 89 | + encryption_key_bytes = password_bytes[:ENCRYPTION_KEY_LENGTH] |
| 90 | + initialization_vector_bytes = password_bytes[ENCRYPTION_KEY_LENGTH:] |
| 91 | + |
| 92 | + try: |
| 93 | + cipher = Cipher(algorithms.AES(encryption_key_bytes), modes.GCM(initialization_vector_bytes, authentication_tag_bytes)) |
| 94 | + decryptor = cipher.decryptor() |
| 95 | + decipher_bytes = decryptor.update(encrypted_data_bytes) + decryptor.finalize() |
| 96 | + except InvalidTagException: |
| 97 | + raise ValueError('Decryption failed, malformed encrypted value or password.') |
| 98 | + except Exception as err: |
| 99 | + raise err |
| 100 | + |
| 101 | + return decipher_bytes.decode('utf-8') |
| 102 | + |
| 103 | + |
| 104 | +def _load_private_key(private_key_file_base64: str, private_key_password: str) -> rsa.RSAPrivateKey: |
| 105 | + private_key = serialization.load_pem_private_key(base64.b64decode( |
| 106 | + private_key_file_base64.encode('utf-8')), password=private_key_password.encode('utf-8')) |
| 107 | + if not isinstance(private_key, rsa.RSAPrivateKey): |
| 108 | + raise ValueError('Invalid private key.') |
| 109 | + |
| 110 | + return private_key |
| 111 | + |
| 112 | + |
| 113 | +def _load_public_key(public_key_file_base64: str) -> rsa.RSAPublicKey: |
| 114 | + public_key = serialization.load_pem_public_key(base64.b64decode(public_key_file_base64.encode('utf-8'))) |
| 115 | + if not isinstance(public_key, rsa.RSAPublicKey): |
| 116 | + raise ValueError('Invalid public key.') |
| 117 | + |
| 118 | + return public_key |
| 119 | + |
| 120 | + |
| 121 | +def _crypto_random_object_id(length: int = 17) -> str: |
| 122 | + """Python reimplementation of cryptoRandomObjectId from `@apify/utilities`.""" |
| 123 | + chars = 'abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ0123456789' |
| 124 | + return ''.join(secrets.choice(chars) for _ in range(length)) |
| 125 | + |
| 126 | + |
| 127 | +def _decrypt_input_secrets(private_key: rsa.RSAPrivateKey, input: Any) -> Any: |
| 128 | + """Decrypt input secrets.""" |
| 129 | + if not isinstance(input, dict): |
| 130 | + return input |
| 131 | + |
| 132 | + for key, value in input.items(): |
| 133 | + if isinstance(value, str): |
| 134 | + match = ENCRYPTED_INPUT_VALUE_REGEXP.fullmatch(value) |
| 135 | + if match: |
| 136 | + encrypted_password = match.group(1) |
| 137 | + encrypted_value = match.group(2) |
| 138 | + input[key] = private_decrypt( |
| 139 | + encrypted_password, |
| 140 | + encrypted_value, |
| 141 | + private_key=private_key, |
| 142 | + ) |
| 143 | + |
| 144 | + return input |
0 commit comments