· 9 years ago · Dec 26, 2016, 02:56 PM
1import base64
2import json
3
4from Crypto import Random
5from Crypto.Cipher import AES
6
7from star_site import settings
8
9
10class AESCrypt:
11 """
12 AES/ECB/PKCS#7 åŠ å¯†ç®—æ³•
13 """
14 BLOCK_SIZE = 16
15
16 def pkcs7_pad(self, s):
17 length = self.BLOCK_SIZE - (len(s) % self.BLOCK_SIZE)
18 s += bytes([length]) * length
19 return s
20
21 def pkcs7_unpad(self, s):
22 """
23 unpadding according to PKCS #7
24 @param s: string to unpad
25 @type s: byte
26 @rtype: byte
27 """
28 sd = -(s[-1])
29 return s[0:sd]
30
31 def __encrypt__(self, plain_text, secret_key):
32 if (plain_text is None) or (len(plain_text) == 0):
33 raise ValueError('input text cannot be null or empty set')
34
35 if not secret_key or (len(secret_key) == 0):
36 raise ValueError('密钥长度错误')
37
38 plain_bytes = plain_text.encode('utf-8')
39 raw = self.pkcs7_pad(plain_bytes)
40 print(raw)
41 print(len(raw))
42 iv = Random.new().read(AES.block_size)
43 cipher = AES.new(secret_key, AES.MODE_ECB, iv)
44
45 cipher_bytes = cipher.encrypt(raw)
46
47 cipher_text = self.base64_encode(iv + cipher_bytes)
48 return cipher_text
49
50 def __decrypt__(self, cipher_text, secret_key):
51
52 if not secret_key or (len(secret_key) == 0):
53 raise ValueError('密钥长度错误')
54
55 cipher_bytes = self.base64_decode(cipher_text)
56 iv = cipher_bytes[:AES.block_size]
57 cipher_data = cipher_bytes[AES.block_size:]
58
59 cipher = AES.new(secret_key, AES.MODE_ECB, iv)
60 plain_pad = cipher.decrypt(cipher_data)
61 plain_text = self.pkcs7_unpad(plain_pad)
62 return plain_text.decode()
63
64 def base64_encode(self, bytes_data):
65 """
66 åŠ base64
67
68 :type bytes_data: byte
69 :rtype 返回类型: string
70 """
71 return (base64.urlsafe_b64encode(bytes_data)).decode()
72
73 def base64_decode(self, str_data):
74 """
75 è§£base64
76
77 :type str_data: string
78 :rtype 返回类型: byte
79 """
80 return base64.urlsafe_b64decode(str_data)
81
82
83class HowToUse:
84 def test_encrypt(self):
85 # secret_key = 'hotel!!!!!'
86 plain_text = 'test test test test aes'
87 # secret_key md5åŽ
88 secret_key_md5 = '5373a944a96d5c656cd4307012b8e2d0'
89 # secret_key_md5 = hash_md5(secret_key)
90
91 aes_crypt = AESCrypt()
92 cipher_text = aes_crypt.__encrypt__(plain_text, secret_key_md5)
93
94 plain_data = aes_crypt.__decrypt__(cipher_text, secret_key_md5)
95
96 assert plain_data == plain_text