encrypt.py
| 1 | from cryptography.hazmat.primitives import hashes |
| 2 | from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC |
| 3 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
| 4 | from cryptography.hazmat.primitives import padding |
| 5 | from cryptography.hazmat.backends import default_backend |
| 6 | import os |
| 7 | import sys |
| 8 | |
| 9 | def encrypt(content: bytes, password: str) -> bytes: |
| 10 | """ |
| 11 | Encrypts the given content using the provided password. |
| 12 | |
| 13 | Args: |
| 14 | content (bytes): The content to be encrypted. |
| 15 | password (str): The password used for encryption. |
| 16 | |
| 17 | Returns: |
| 18 | bytes: The encrypted content. |
| 19 | """ |
| 20 | |
| 21 | # Generate a random initialization vector (IV) and salt |
| 22 | iv = os.urandom(16) |
| 23 | salt = os.urandom(16) |
| 24 | |
| 25 | # Derive a key from the password using PBKDF2 |
| 26 | kdf = PBKDF2HMAC( |
| 27 | algorithm=hashes.SHA512(), |
| 28 | length=32, |
| 29 | salt=salt, |
| 30 | iterations=100000, |
| 31 | backend=default_backend() |
| 32 | ) |
| 33 | key = kdf.derive(password.encode()) |
| 34 | |
| 35 | # Create a cipher object with AES-256-CBC |
| 36 | cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) |
| 37 | encryptor = cipher.encryptor() |
| 38 | |
| 39 | # Pad the content to a multiple of the block length |
| 40 | padder = padding.PKCS7(128).padder() |
| 41 | padded_content = padder.update(content) + padder.finalize() |
| 42 | |
| 43 | # Encrypt the padded content |
| 44 | encrypted_content = encryptor.update(padded_content) + encryptor.finalize() |
| 45 | |
| 46 | # Return the salt, IV, and encrypted content concatenated |
| 47 | return salt + iv + encrypted_content |
| 48 | if __name__ == "__main__": |
| 49 | if len(sys.argv) != 4: |
| 50 | print("Usage: encrypt.py <file> <password> <outfile>") |
| 51 | sys.exit(1) |
| 52 | data = encrypt(open(sys.argv[1], "rb").read(), sys.argv[2]) |
| 53 | open(sys.argv[3], "wb").write(data) |
| 54 | |
| 55 |