-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaes_cryptography.py
39 lines (35 loc) · 1.4 KB
/
aes_cryptography.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
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, padding
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import os
# to get high entropy paswword from a low entropy password
def generate_high_entropy_key(password, salt):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
iterations=100000,
salt=salt,
length=32
)
key = kdf.derive(password.encode('utf-8'))
return key
# the aes encryption
def aes_encrypt(key, plaintext):
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return iv + ciphertext
# the aes decryption
def aes_decrypt(key, ciphertext):
iv = ciphertext[:16]
ciphertext = ciphertext[16:]
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
return plaintext
# print(generate_high_entropy_key("khritish", b"123wer"))
# print(generate_high_entropy_key("hellojoe", b"123wer"))
# key = generate_high_entropy_key("khritish", b"123wer")
# cipher = aes_encrypt(key, b"Hi this is Khritish")
# print(aes_decrypt(key, cipher))