python AES 雙向對稱加密解密

高級加密標準(Advanced Encryption Standard,AES),在密碼學中又稱Rijndael加密法,是美國聯邦政府採用的一種區塊加密標準。這個標準用來替代原先的DES,已經被多方分析且廣爲全世界所使用。通過五年的甄選流程,高級加密標準由美國國家標準與技術研究院(NIST)於2001年11月26日發佈於FIPS PUB 197,並在2002年5月26日成爲有效的標準。2006年,高級加密標準已然成爲對稱密鑰加密中最流行的算法之一。
AES只是個基本算法,實現AES有若干模式。其中的CBC模式由於其安全性而被TLS(就
是https的加密標準)和IPSec(win採用的)做爲技術標準。簡單地說,CBC使用密碼和salt
(起擾亂做用)按固定算法(md5)產生key和iv。而後用key和iv(初始向量,加密第一塊
明文)加密(明文)和解密(密文)。
下面介紹python實現的AES加密解密實例,這裏採用CBC模式,用到了pycrypto‎模塊html

安裝:python

pip install Crypto
pip install binascii

實現:算法

#!/usr/bin/env python
# -*- coding:utf-8 -*- 
#@author: rui.xu
#這裏使用pycrypto‎庫
#按照方法:easy_install pycrypto‎
 
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
 
class prpcrypt():
    def __init__(self,key):
        self.key = key
        self.mode = AES.MODE_CBC
     
    #加密函數,若是text不足16位就用空格補足爲16位,
    #若是大於16當時不是16的倍數,那就補足爲16的倍數。
    def encrypt(self,text):
        cryptor = AES.new(self.key,self.mode,b'0000000000000000')
        #這裏密鑰key 長度必須爲16(AES-128),
        #24(AES-192),或者32 (AES-256)Bytes 長度
        #目前AES-128 足夠目前使用
        length = 16
        count = len(text)
        if count < length:
            add = (length-count)
            #\0 backspace
            text = text + ('\0' * add)
        elif count > length:
            add = (length-(count % length))
            text = text + ('\0' * add)
        self.ciphertext = cryptor.encrypt(text)
        #由於AES加密時候獲得的字符串不必定是ascii字符集的,輸出到終端或者保存時候可能存在問題
        #因此這裏統一把加密後的字符串轉化爲16進制字符串
        return b2a_hex(self.ciphertext)
     
    #解密後,去掉補足的空格用strip() 去掉
    def decrypt(self,text):
        cryptor = AES.new(self.key,self.mode,b'0000000000000000')
        plain_text  = cryptor.decrypt(a2b_hex(text))
        return plain_text.rstrip('\0')
 
if __name__ == '__main__':
    pc = prpcrypt('keyskeyskeyskeys') #初始化密鑰
    import sys
    e = pc.encrypt(sys.argv[1]) #加密
    d = pc.decrypt(e) #解密
    print "加密:",e
    print "解密:",d

 ValueError: IV must be 16 bytes long            windows下默認會報這個錯,windows

cryptor = AES.new(self.key,self.mode,b'0000000000000000') 實例化後面加上後面那個就Ok了

轉載:http://blog.daxuxu.info/2013/11/aes%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%E4%BE%8B%E5%AD%90python%E5%AE%9E%E7%8E%B0%EF%BC%8C%E4%BD%BF%E7%94%A8pycrypt%E7%B1%BB%E5%BA%93.html安全

相關文章
相關標籤/搜索