共計 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 網 – 提供最優質的資源集合!
正文完