1. 程式人生 > >Python 的AES加密與解密

Python 的AES加密與解密

AES加密方式有五種:ECB, CBC, CTR, CFB, OFB

從安全性角度推薦CBC加密方法,本文介紹了CBC,ECB兩種加密方法的python實現

python 在 Windows下使用AES時要安裝的是pycryptodome 模組   pip install pycryptodome 

python 在 Linux下使用AES時要安裝的是pycrypto模組   pip install pycrypto 

CBC加密需要一個十六位的key(金鑰)和一個十六位iv(偏移量)

ECB加密不需要iv

 

AES CBC 加密的python實現

 1 from Crypto.Cipher import AES
 2 from binascii import b2a_hex, a2b_hex
 3 
 4 
 5 # 如果text不足16位的倍數就用空格補足為16位
 6 def add_to_16(text):
 7     if len(text.encode('utf-8')) % 16:
 8         add = 16 - (len(text.encode('utf-8')) % 16)
 9     else:
10         add = 0
11     text = text + ('\0' * add)
12 return text.encode('utf-8') 13 14 15 # 加密函式 16 def encrypt(text): 17 key = '9999999999999999'.encode('utf-8') 18 mode = AES.MODE_CBC 19 iv = b'qqqqqqqqqqqqqqqq' 20 text = add_to_16(text) 21 cryptos = AES.new(key, mode, iv) 22 cipher_text = cryptos.encrypt(text) 23 #
因為AES加密後的字串不一定是ascii字符集的,輸出儲存可能存在問題,所以這裡轉為16進位制字串 24 return b2a_hex(cipher_text) 25 26 27 # 解密後,去掉補足的空格用strip() 去掉 28 def decrypt(text): 29 key = '9999999999999999'.encode('utf-8') 30 iv = b'qqqqqqqqqqqqqqqq' 31 mode = AES.MODE_CBC 32 cryptos = AES.new(key, mode, iv) 33 plain_text = cryptos.decrypt(a2b_hex(text)) 34 return bytes.decode(plain_text).rstrip('\0') 35 36 37 if __name__ == '__main__': 38 e = encrypt("hello world") # 加密 39 d = decrypt(e) # 解密 40 print("加密:", e) 41 print("解密:", d)

 

AES ECB加密的python實現

 1 """
 2 ECB沒有偏移量
 3 """
 4 from Crypto.Cipher import AES
 5 from binascii import b2a_hex, a2b_hex
 6 
 7 
 8 def add_to_16(text):
 9     if len(text.encode('utf-8')) % 16:
10         add = 16 - (len(text.encode('utf-8')) % 16)
11     else:
12         add = 0
13     text = text + ('\0' * add)
14     return text.encode('utf-8')
15 
16 
17 # 加密函式
18 def encrypt(text):
19     key = '9999999999999999'.encode('utf-8')
20     mode = AES.MODE_ECB
21     text = add_to_16(text)
22     cryptos = AES.new(key, mode)
23 
24     cipher_text = cryptos.encrypt(text)
25     return b2a_hex(cipher_text)
26 
27 
28 # 解密後,去掉補足的空格用strip() 去掉
29 def decrypt(text):
30     key = '9999999999999999'.encode('utf-8')
31     mode = AES.MODE_ECB
32     cryptor = AES.new(key, mode)
33     plain_text = cryptor.decrypt(a2b_hex(text))
34     return bytes.decode(plain_text).rstrip('\0')
35 
36 
37 if __name__ == '__main__':
38     e = encrypt("hello world")  # 加密
39     d = decrypt(e)  # 解密
40     print("加密:", e)
41     print("解密:", d)