重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊、服務(wù)器等服務(wù)
本文實(shí)例講述了Python基于pycrypto實(shí)現(xiàn)的AES加密和解密算法。分享給大家供大家參考,具體如下:
一 代碼
# -*- coding: UTF-8 -*- 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') #使用指定密鑰和模式對給定信息進(jìn)行加密 def AESencrypt(key, mode, text): encryptor = encryptor_decryptor(key, mode) return encryptor.encrypt(text) #使用指定密鑰和模式對給定信息進(jìn)行解密 def AESdecrypt(key, mode, text): decryptor = encryptor_decryptor(key, mode) return decryptor.decrypt(text) if __name__ == '__main__': text = 'Python3.5 is excellent.' key = keyGenerater(16) #隨機(jī)選擇AES的模式 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) #明文必須以字節(jié)串形式,且長度為16的倍數(shù) 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])