forked from svemaraju/PyAESCrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaescrypt.py
More file actions
40 lines (33 loc) · 1.2 KB
/
Copy pathaescrypt.py
File metadata and controls
40 lines (33 loc) · 1.2 KB
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
from Crypto.Cipher import AES
import base64
import hashlib
class PyAesCrypt(object):
def __init__(self,iv=None,encoding=True):
self.iv = iv
self.encoding = encoding
def encrypt(self,key,message):
cipher = AES.new(key=self._hashkey(key=key))
cipher_text = cipher.encrypt(self.pkcs7padding(data=message))
if self.encoding:
return base64.b64encode(s=cipher_text)
return cipher_text
def pkcs7padding(self,data):
bs = 8
padding = bs - len(data) % bs
padding_text = chr(padding) * padding
return data + padding_text
def pkcs7decode(self, text):
if type(text) is bytes:
pad = ord(text.decode("utf-8")[-1])
return text[:-pad]
else:
raise RuntimeError("bytes required found %s" % type(text))
def _hashkey(self,key):
return hashlib.sha256(key.encode()).digest()
def decrypt(self,key,message):
cipher = AES.new(key=self._hashkey(key=key))
if self.encoding:
resp = cipher.decrypt(ciphertext=base64.b64decode(s=message))
else:
resp = cipher.decrypt(ciphertext=message)
return self.pkcs7decode(text=resp)