#encoding:utf-8 from Crypto.Cipher import AES import base64 class prpcrypt(): def __init__(self, key): #這裏密鑰key 長度必須爲16(AES-128)、24(AES-192)、或32(AES-256)Bytes 長度. #目前AES-128足夠用 if len(key)<16: key=key+(16-len(key))*"\0" self.key = key[:16] self.mode = AES.MODE_CBC #加密函數,若是text不是16的倍數【加密文本text必須爲16的倍數!】,那就補足爲16的倍數 def encrypt(self, text): cryptor = AES.new(self.key, self.mode, IV=self.key) length = 16 count = len(text) add=count % length if add: text = text + ('\0' * (length-add)) self.ciphertext = cryptor.encrypt(text) #由於AES加密時候獲得的字符串不必定是ascii字符集的,輸出到終端或者保存時候可能存在問題 #因此這裏統一把加密後的字符串用base64轉化 return base64.b64encode(self.ciphertext) #解密後,去掉補足的'\0'用strip() 去掉 def decrypt(self, text): cryptor = AES.new(self.key, self.mode, IV=self.key) plain_text = cryptor.decrypt(base64.b64decode(text)) return plain_text.rstrip('\0') if __name__ == '__main__': key='keys'*10 pc = prpcrypt(key) e = pc.encrypt("8") print e d = pc.decrypt(e) print d