pycrypto实现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')
#使用指定密钥和模式对给定信息进行加密
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 = 'Python3.5 is excellent.'
    key = keyGenerater(16)
    #随机选择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)
        #明文必须以字节串形式,且长度为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])

 

二 运行结果
E:\python\python可以这样学\第18章 密码学编程\code>python AES_test.py
('key:', 'D5pcO6iu0HIbj3I2')
('mode:', 1)
('Before encryption:', 'Python3.5 is excellent.')
('After encryption:', '\xf4\x15\x9f\xaf\xea\xd0\n\x03\xfdf\xf6}9\xaa\xa34\xb4\x1eL2\x0e \x16\xa5 \xff?\x8bA\x8e\xdd\xa8')
('After decryption:', u'Python3.5 is excellent.')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值