-
Notifications
You must be signed in to change notification settings - Fork 0
/
encryption.py
55 lines (41 loc) · 1.85 KB
/
encryption.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import os
import hashlib
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
def generate_key_from_input(data, key_size=32):
"""Generate a fixed-size key using SHA-256 hash."""
hash_object = hashlib.sha256(data.encode())
return hash_object.digest()[
:key_size
] # Ensure the key size is appropriate
def encrypt_aes_256(plaintext, passphrase):
"""Encrypt plaintext using AES-256 with a key derived from a passphrase."""
key = generate_key_from_input(passphrase)
iv = os.urandom(16) # AES block size is 16 bytes
cipher = Cipher(
algorithms.AES(key), modes.CBC(iv), backend=default_backend()
)
encryptor = cipher.encryptor()
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_plaintext = padder.update(plaintext.encode()) + padder.finalize()
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
return iv + ciphertext
def decrypt_aes_256(ciphertext, passphrase):
"""Decrypt ciphertext using AES-256 with a key derived from a passphrase."""
key = generate_key_from_input(passphrase)
iv = ciphertext[:16]
ciphertext = ciphertext[16:]
cipher = Cipher(
algorithms.AES(key), modes.CBC(iv), backend=default_backend()
)
decryptor = cipher.decryptor()
padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()
return plaintext.decode()