Pythonで文字列を暗号化して出力する方法は何ですか?

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
bannerAds