python实现AES算法
生活随笔
收集整理的這篇文章主要介紹了
python实现AES算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
pycrypto庫下載:http://pan.baidu.com/s/1nvNtCvB (python2.7的版本),直接安裝就可以了
#!/usr/bin/python #-*- coding:utf-8-*- from Crypto.Cipher import AES from binascii import b2a_hex,a2b_hexclass aes():#自己實現了一個aes類,用于aes的加密和解密def __init__(self,key,mode):#key為aes秘鑰,mode為加密模式self.key = keyself.mode = modedef encrypt(self,text,count):#text的為要加密的文本或者二進制流,count為加密數據的長度cryptor = AES.new(self.key,self.mode,b'0000000000000000')length = 16if count < length:add = (length-count)#\0 backspacetext = text + ('\0' * add)elif count > length:add = (length-(count % length))text = text + ('\0' * add)self.cipherText = cryptor.encrypt(text)return b2a_hex(self.cipherText)#將內存中的數據已16進制字符串打印出來def decrypt(self,cipherText):#cipherText類型為16進制字符串如:"fa0345da",一般為32個字節長度cryptor = AES.new(self.key,self.mode,b'0000000000000000')plainText = cryptor.decrypt(a2b_hex(cipherText))#將秘鑰轉換為二進制流return plainText#返回值為二進制流,因為有很多不可打印字符def main():key = '1234567890123456' #秘鑰的長度必須為16cryptor = aes(key,AES.MODE_ECB)#這里選用的是ECB模式msg = 'helloworld' #加密字符串cipher = cryptor.encrypt(msg,len(msg)) #返回值是內存中的16進制字符串print cipherplainText = cryptor.decrypt(cipher)#解密函數,秘鑰在aes初始化的時候設置好了,aes是對稱加密的,加密的秘鑰和解密的秘鑰是一樣的print plainText if __name__=="__main__":main()總結
以上是生活随笔為你收集整理的python实现AES算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个含有crc32算法的CrackMe分
- 下一篇: CTF短秘钥的RSA解密