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

21次阅读
没有评论

共计 608 个字符,预计需要花费 2 分钟才能阅读完成。

在 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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-03-19发表,共计608字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)