#coding: utf8
import sys
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的倍數【加密文本text必須為16的倍數!】,那就補足為16的倍數
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
#這里密鑰key 長度必須為16(AES-128)、24(AES-192)、或32(AES-256)Bytes 長度.目前AES-128足夠用
length = 16
count = len(text)
if(count % length != 0) :
add = length - (count % length)
else:
add = 0
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)
plain_text = cryptor.decrypt(a2b_hex(text))
return plain_text.rstrip('\0')
if __name__ == '__main__':
pc = prpcrypt('keyskeyskeyskeys') #初始化密鑰
e = pc.encrypt("0123456789ABCDEF")
d = pc.decrypt(e)
print e, d
e = pc.encrypt("00000000000000000000000000")
d = pc.decrypt(e)
print e, d