python寫的AES128/ECB/pkcs7加密解密函式
阿新 • • 發佈:2018-11-10
因為需要,要實現一個python版的AES128加解密方法,加密模式ECB,填充模式pkcs7.(貌似pkcs5和pkcs7是一模一樣的,我沒有看具體原因(好像是aes沒有64位的,64位對應5?))
下面直接貼原始碼啦(我找了好幾個東拼西湊出來的,反正能工作,也支援中文)
# -*- coding: utf-8 -*- from Crypto.Cipher import AES import os BS = AES.block_size pad =lambda s: s +(BS - len(s)% BS)* chr(BS - len(s)% BS) unpad =lambda s : s[0:-ord(s[-1])] key = os.urandom(16)# the length can be (16, 24, 32) #key='xxxxx'#32位或者0-f的數值,對應16位元組 text ='content==頂你哦,記得回訪哦xxxxx' cipher = AES.new(key, AES.MODE_ECB)#ECB模式 encrypted = cipher.encrypt(pad(text)).encode('hex') print encrypted # will be something like 'f456a6b0e54e35f2711a9fa078a76d16' decrypted = unpad(cipher.decrypt(encrypted.decode('hex'))) print decrypted # will be 'to be encrypted'