服务器之家

服务器之家 > 正文

Python基于pycrypto实现的AES加密和解密算法示例

时间:2021-01-29 00:41     来源/作者:chengqiuming

本文实例讲述了Python基于pycrypto实现的AES加密解密算法。分享给大家供大家参考,具体如下:

一 代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# -*- 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.')

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/chengqiuming/article/details/78601125

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
返回顶部