-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAESexample.py
44 lines (35 loc) · 1.17 KB
/
AESexample.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
from Crypto import Random
from Crypto.Cipher import AES
import base64
import hashlib
class AESCipher(object):
def __init__(self, key):
self.bs = 32
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw):
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_ECB, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_ECB, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
def main():
secretKey = file("secretkey","rb").read(32)
obj = AESCipher(secretKey)
plain = file("sample.bmp","rb").read()
enc = obj.encrypt(plain)
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
temp = file("./results/AESECB.bmp","wb")
temp.write(enc[AES.block_size:])
temp.close()
if __name__ == "__main__":
main()