温馨提示×

python字符串加密输出的方法是什么

小亿
100
2024-02-18 17:00:21
栏目: 编程语言

在Python中,可以使用不同的加密算法来加密字符串。常见的加密算法包括AES、DES、RSA等。以下是一个使用RSA算法加密字符串的示例:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64

# 生成RSA密钥对
key = RSA.generate(2048)

# 获取公钥和私钥
public_key = key.publickey()
private_key = key

# 加密字符串
message = "Hello, world!"
cipher = PKCS1_OAEP.new(public_key)
encrypted_message = cipher.encrypt(message.encode())

# 将加密后的消息进行base64编码
encrypted_message_base64 = base64.b64encode(encrypted_message)

print("加密后的消息:", encrypted_message_base64)

在上面的示例中,首先生成了一个RSA密钥对,然后使用公钥加密了字符串"Hello, world!"。最后,将加密后的消息进行base64编码输出。请注意,使用加密算法前,需要安装pycryptodome模块。您可以使用以下命令安装:

pip install pycryptodome

0