1. 程式人生 > >pycrypto:AES加密詳解

pycrypto:AES加密詳解

  最近在寫介面自動化指令碼,需要的payload引數需要加密,而採用的加密標準為AES,因此特地去學了一下,發現專門有加密演算法庫支援這種加密演算法,就是PyCrypto

PyCrypto是一個免費的加密演算法庫,支援常見的DES、AES、以及MD5、SHA等各種HASH運算

 

PyPi地址:https://pypi.org/project/pycrypto/

 

這篇博文只對AES加密進行重點講解

 

#coding:utf-8
from Crypto.Cipher import AES

#加密
cryptor = AES.new('This is a key123
', AES.MODE_CBC, 'This is an iv456') msg='the answer is no' ciphertext = cryptor.encrypt(msg) print(ciphertext) #解密 cryptor2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an iv456') plain_text=cryptor2.decrypt(ciphertext) print(plain_text)

 

1)加密

'This is an iv456'為key,長度有著嚴格的要求,必須是16/24或者32位,否則將丟擲錯誤:ValueError: AES key must be either 16, 24, or 32 bytes long
'This is an iv456'為VI,長度要求更加嚴格,只能為16位,否則將丟擲錯誤:ValueError: IV must be 16 bytes long
通過encrypt()對msg字串進行加密得到ciphertext

2)解密
要想對加密字串進行解密,必須知道加密時使用的key和VI,通過decrypt()方法對加密字串進行解密
如果key和VI錯誤,則將無法得到正確的解密字串,解密失敗後將會得到一個新的加密字串

3)關於安裝PyCrypto模組遇到問題的請參考本人的另外一篇部落格:https://www.cnblogs.com/Elaine1/p/10180260.html