代碼:
import sys from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex AES_SECRET_KEY = '此處16|24|32個字符' class AES_ENCRYPT(object): def __init__(self): self.key = AES_SECRET_KEY self.mode = AES.MODE_CBC #加密函數,如果text不是16的倍數【加密文本text必須為16的倍數!】,那就補足為16的倍數 def encrypt(self, text): #cryptor = AES.new(self.key, self.mode, self.key) cryptor = AES.new(self.key, self.mode) #這里密鑰key 長度必須為16(AES-128)、24(AES-192)、或32(AES-256)Bytes 長度.目前AES-128足夠用 length = 16 count = len(text) 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, self.key) cryptor = AES.new(self.key, self.mode) plain_text = cryptor.decrypt(a2b_hex(text)) return plain_text.rstrip('\0') if __name__ == '__main__': aes_encrypt = AES_ENCRYPT() #初始化密鑰 customer_id = "3f500ac5-020d-3ce3-a2a2-51a59ddd606e" e = aes_encrypt.encrypt(customer_id) d = aes_encrypt.decrypt(e) print customer_id print e print d
參考資料:
http://www.cnblogs.com/lovebread/archive/2010/11/09/1872747.html
https://my.oschina.net/kjpioo/blog/149293
http://blog.csdn.net/b_h_l/article/details/9454465
http://www.cnblogs.com/kaituorensheng/p/4501128.html
https://my.oschina.net/kuaikuai/blog/208075
http://www.jb51.net/article/56750.htm
http://www.cnblogs.com/happyhippy/archive/2006/12/23/601353.html
http://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256
