-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaes_cipher.py
More file actions
64 lines (54 loc) · 1.8 KB
/
aes_cipher.py
File metadata and controls
64 lines (54 loc) · 1.8 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import base64
import sys
from Crypto.Cipher import AES
class AESCipher:
block_size = AES.block_size
zero_padding = 1
PKCS5Padding = 2
PKCS7Padding = 3
def __init__(self, key, mode = AES.MODE_ECB):
if type(key) != bytes:
key = bytes(key, 'utf-8')
self.key = key
self.aes = AES.new(self.key, mode)
@classmethod
def padding(cls, data, padding_type):
PKCS7Padding = lambda s: s + (cls.block_size - len(s) % cls.block_size) * \
chr(cls.block_size - len(s) % cls.block_size)
if padding_type == cls.PKCS5Padding or \
padding_type == cls.PKCS7Padding:
return PKCS7Padding(data)
if padding_type == cls.zero_padding:
return data
@classmethod
def unpadding(cls, data, padding_type):
#PKCS7Unpadding = lambda s : s[0:-ord(s[-1])]
PKCS7Unpadding = lambda s : s[0:-s[-1]]
if padding_type == cls.PKCS5Padding or \
padding_type == cls.PKCS7Padding:
return PKCS7Unpadding(data)
if padding_type == cls.zero_padding:
return data
def hex2bytes(self, raw):
if type(raw) == str:
raw = bytes.fromhex(raw)
return raw
def encrypt(self, raw):
raw = AESCipher.padding(raw, self.PKCS5Padding).encode("utf-8")
return self.aes.encrypt(raw).hex().upper()
def decrypt(self, enc):
enc = self.hex2bytes(enc)
raw = self.unpadding(self.aes.decrypt(enc), self.PKCS5Padding).decode('utf8')
raw = raw.strip()
return raw
key = '1234567890123456'
key = key.encode('utf-8')
aes = AESCipher(key)
for line in sys.stdin:
line = line.strip()
if not line:
continue
enc = aes.encrypt(line)
print(enc)
raw = aes.decrypt(enc)
print(raw)