Python使用AES算法进行加解密

本文要点在于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,'

After decryption: 董付国 《Python程序设计》系列教材,清华大学出版社

温馨提示:单击文章顶部作者名字旁边浅蓝色的“Python小屋”进入公众号,关注后可以查看更多内容!

欢迎转发给您的朋友,或许这正是Ta需要的知识!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dongfuguo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值