· 7 years ago · Apr 26, 2018, 07:16 PM
1#!/usr/bin/python
2
3import sys
4from Crypto.Cipher import AES
5
6
7def main():
8 if len(sys.argv) != 3:
9 print("Text or secret key is not specified!")
10 sys.exit(-1)
11
12 plain_text = sys.argv[1]
13 secret_key = sys.argv[2]
14
15 text_as_bytes = list(bytearray(plain_text))
16 len_as_bytes = [hex(len(text_as_bytes) >> i & 0xff) for i in (24, 16, 8, 0)]
17 print("Len: ", len_as_bytes)
18
19 value = len_as_bytes + text_as_bytes
20 print("Len: ", value)
21
22 key = secret_key[:32]
23 cipher = AESCipher(key)
24 encrypted = cipher.encrypt(value)
25
26 print(encrypted)
27
28
29BS = 256
30pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
31
32
33class AESCipher:
34 def __init__(self, key):
35 """
36 Requires hex encoded param as a key
37 """
38 self.key = key.decode("hex")
39
40 def encrypt(self, raw):
41 """
42 Returns hex encoded encrypted value!
43 """
44 raw = pad(raw)
45 cipher = AES.new(self.key, AES.MODE_ECB)
46 return cipher.encrypt(raw).encode("hex")
47
48
49if __name__ == "__main__":
50 main()