python簡單實現(xiàn)AES加密和解密
更新時間:2019年03月28日 14:42:02 作者:Frankssss
這篇文章主要為大家詳細介紹了python簡單實現(xiàn)AES加密和解密,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python實現(xiàn)AES加密和解密的具體代碼,供大家參考,具體內(nèi)容如下
AES加密算法是一種對稱加密算法, 他有一個密匙, 即用來加密, 也用來解密
import base64
from Crypto.Cipher import AES
# 密鑰(key), 密斯偏移量(iv) CBC模式加密
def AES_Encrypt(key, data):
vi = '0102030405060708'
pad = lambda s: s + (16 - len(s)%16) * chr(16 - len(s)%16)
data = pad(data)
# 字符串補位
cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
encryptedbytes = cipher.encrypt(data.encode('utf8'))
# 加密后得到的是bytes類型的數(shù)據(jù)
encodestrs = base64.b64encode(encryptedbytes)
# 使用Base64進行編碼,返回byte字符串
enctext = encodestrs.decode('utf8')
# 對byte字符串按utf-8進行解碼
return enctext
def AES_Decrypt(key, data):
vi = '0102030405060708'
data = data.encode('utf8')
encodebytes = base64.decodebytes(data)
# 將加密數(shù)據(jù)轉(zhuǎn)換位bytes類型數(shù)據(jù)
cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
text_decrypted = cipher.decrypt(encodebytes)
unpad = lambda s: s[0:-s[-1]]
text_decrypted = unpad(text_decrypted)
# 去補位
text_decrypted = text_decrypted.decode('utf8')
return text_decrypted
key = '0CoJUm6Qyw8W8jud'
data = 'sdadsdsdsfd'
AES_Encrypt(key, data)
enctext = AES_Encrypt(key, data)
print(enctext)
text_decrypted = AES_Decrypt(key, enctext)
print(text_decrypted)
hBXLrMkpkBpDFsf9xSRGQQ== sdadsdsdsfd
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
termux中matplotlib無法顯示中文問題的解決方法
這篇文章主要介紹了termux中matplotlib無法顯示中文問題的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01

