本文要点在于Python扩展库pycrypto实现了大量密码学算法,可以拿来直接使用。
import string
import random
from Crypto.Cipher import AES
def keyGenerater(length):
'''生成指定长度的秘钥'''
if length not in (16, 24, 32):
return None
x = string.ascii_letters+string.digits
return ''.join([random.choice(x) for i in range(length)])
def encryptor_decryptor(key, mode):
return AES.new(key, mode, b'0000000000000000')
def AESencrypt(key, mode, text):
encryptor = encryptor_decryptor(key, mode)
return encryptor.encrypt(text)
def AESdecrypt(key, mode, text):
decryptor = encryptor_decryptor(key, mode)
return decryptor.decrypt(text)
if __name__ == '__main__':
text = '董付国 《Python程序设计》系列教材,清华大学出版社'
key = keyGenerater(16)
mode = random.choice((AES.MODE_CBC, AES.MODE_CFB, AES.MODE_ECB, AES.MODE_OFB))
if not key:
print('Something is wrong.')
else:
print('key:', key)
print('mode:', mode)
print('Before encryption:', text)
#明文必须以字节串形式,且长度为16的倍数
text_encoded = text.encode()
text_length = len(text_encoded)
padding_length = 16 - text_length%16
text_encoded = text_encoded + b'0'*padding_length
text_encrypted = AESencrypt(key, mode, text_encoded)
print('After encryption:', text_encrypted)
text_decrypted =AESdecrypt(key, mode, text_encrypted)
print('After decryption:', text_decrypted.decode()[:-padding_length])
代码连续运行2次的结果如下:
= RESTART: C:\Python 3.5\tttt.py =
key: pIfvcrQ7P1N4OKmR
mode: 2
Before encryption: 董付国 《Python程序设计》系列教材,清华大学出版社
After encryption: b";\xe8\x01\xd5\xc38e'\x1b\xb0[\x96u\xdd#y\xf4\xa1\x17y\x15\r5-\xc3\x1c\xe4\x9c-8\xef\xac@\xb7v\x92LN\x1f~\xe6\xd0U\t\xd6;C\x92|\xa0\x1e\xcf\xff\xb5\xeb\xf6cbU\xdc\xa0\xc6\x0ceoU4\x8f\x9f\xec\x0b\xc3\xd2\xfegT\xdd\xc5\x12<"
After decryption: 董付国 《Python程序设计》系列教材,清华大学出版社
>>>
= RESTART: C:\Python 3.5\tttt.py =
key: JH9rdP86pwHc5f0g
mode: 2
Before encryption: 董付国 《Python程序设计》系列教材,清华大学出版社
After encryption: b't\x04\xf6\x9d\xfc\x14z\xb2w\x82\xf8\xe8)\t\x84\x0cb\x15\x8c\xfc\xb7\x19\xf5\xd9\xa6\x82\xd1\x19Wn\xc1\xaf\xbe\xbfg)/\xa0\\G\xdc\xe5\x06\xf0\x13/]c\xc6?\xa3\xe0\xa1\xa1\xd0\xc4\xa5\x90\xc5\xa3@s\xef\xff\xfe\x12\x10\xdf\xaa\x8f\x95\xbcW\xd0Ah\x9f.\xa4,'