How to implement RSA encryption and decryption in Python?
In Python, the rsa library can be used to implement RSA encryption and decryption.
Firstly, make sure you have installed the rsa library. You can install it using the following command:
pip install rsa
Next, we will separately introduce the implementation of RSA encryption and decryption.
RSA encryption
import rsa
# 生成RSA公私钥对
(pubkey, privkey) = rsa.newkeys(2048)
# 将公私钥保存到文件
with open('public.pem', 'w+') as f:
f.write(pubkey.save_pkcs1().decode())
with open('private.pem', 'w+') as f:
f.write(privkey.save_pkcs1().decode())
# 加载公私钥
with open('public.pem', 'r') as f:
pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
with open('private.pem', 'r') as f:
privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())
# 加密
message = 'Hello World!'
crypto = rsa.encrypt(message.encode(), pubkey)
# 输出加密后的结果
print(crypto)
In the above code, we first generate a 2048-bit RSA key pair and save it to a file. Then, we load the key pair, use the public key to encrypt the plaintext, and get the encrypted result.
decrypting using RSA
import rsa
# 加载私钥
with open('private.pem', 'r') as f:
privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())
# 解密
message = rsa.decrypt(crypto, privkey).decode()
# 输出解密后的结果
print(message)
In the above code, we loaded the previously generated private key and used it to decrypt the ciphertext, obtaining the decrypted plaintext.
Please ensure to securely store the ciphertext and public-private keys, and ensure that only authorized users can access the private key.