-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencryption.py
59 lines (40 loc) · 1.36 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
56
57
58
59
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random
import binascii
import base64
def encrypt(key, text):
""" Returns encrypted cipher using AES-256 encryption ctr mode """
#check key size
check_key(key)
#create a random 16-byte IV
iv_bytes = Random.new().read(AES.block_size)
#convert the IV to integer
iv = int(binascii.hexlify(iv_bytes), 16)
#create a new Counter object
ctr = Counter.new(AES.block_size * 8, initial_value=iv)
#create AES-CTR cipher
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
#Encrypt and return IV and encoded cipher
cipher = aes.encrypt(text.encode('utf-8'))
print(type(cipher))
return base64.b64encode(iv_bytes+ cipher)
def decrypt(key, cipher):
""" Return decrypt cipher from AES-256 ctr encryption"""
#check key size
check_key(key)
#Decode cipher
cipher = base64.b64decode(cipher)
#extract iv from cipher
iv_bytes= cipher[:16]
iv = int(binascii.hexlify(iv_bytes), 16)
#create a new Counter object
ctr = Counter.new(AES.block_size * 8, initial_value=iv)
#create AES-CTR cipher
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
# Decrypt and return the plaintext.
text = aes.decrypt(cipher[16:])
return text
#check for 32-byte key
def check_key(key):
assert len(key) == 32