Python String Encryption Guide
In Python, you can use different encryption algorithms to encrypt strings. Common encryption algorithms include AES, DES, RSA, etc. Below is an example of encrypting a string using the RSA algorithm.
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)
In the above example, first an RSA key pair is generated, then the string “Hello, world!” is encrypted using the public key. Finally, the encrypted message is encoded in base64. Note that before using the encryption algorithm, the pycryptodome module needs to be installed. You can install it using the following command:
pip install pycryptodome