python使用Crypto实现字符加密及解密

发布时间:2022-5-31 10:48

python如何使用Crypto对字符进行加密及解密?下面通过一个简单的小实例,给大家介绍一下python使用Crypto实现字符加密及解密的方法。

安装Crypto

在windows上使用如下命令

pip install pycryptodome

在linux使用如下命令

pip install pycrypto

使用

下面是一个简单的小例子,对一个字符串进行加密之后再进行解密

在解密之后的字符串中有时候会出现很多的奇怪符号,我猜测是为了补齐到16个字符长度,原因也不太了解,有时候有些字符串也无法解密。。。不过大多数情况都还挺好用的

import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad


def encrypt(pwd, key):
pwd = pwd.encode('utf-8')
key = key.encode('utf-8')
cryptos = AES.new(key, AES.MODE_ECB)
msg = cryptos.encrypt(pad(pwd, 16))
msg = base64.b64encode(msg)

return msg


def decrypt(word, key):
word = base64.b64decode(word)
key = key.encode("utf-8")
cipher = AES.new(key, AES.MODE_ECB)

a = cipher.decrypt(word)

a = a.decode('utf-8', 'ignore')
a = a.rstrip('\n')
a = a.rstrip('\t')
a = a.rstrip('\r')
a = a.replace('\x06', '')
return a


data = "mmda12231"
print("原数据:" + data)

secret_key = "abcdefghijk12ujk"# 16字节的秘钥
encrypt_data = encrypt(data, secret_key)
print('加密后数据:', encrypt_data)

msg = decrypt(encrypt_data, secret_key)
print('\n', 'data:', msg)

运行结果:

image-20220527170721667

python实现将list拼接为一个字符串 生活杂谈

python实现将list拼接为一个字符串

在 python 中如果想将 list 拼接为一个字符串,可使用 join() 方法。 join() 方法描述 将序列(列表或元组)中的元素以指定的字符连接成一个新的字符串。 语法 s...
Python如何截取字符函数 生活杂谈

Python如何截取字符函数

在工作中我们经常会遇到某种情况需要截取字符串中某个特定标签之间的内容(爬虫可能用到的较多),适用于很多情况例如字符串形式的xml报文、json格式的字符串以及其它类型的字符串。 因为我总...
Python实现自动填写脚本流程详解 生活杂谈

Python实现自动填写脚本流程详解

这篇文章主要介绍了Python实现自动填写脚本,100%准确率,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下! 前言 环境使用 Python 3.8 Pycharm 模...