Use the Python PyCrypto library for RSA encryption and decryption
Use the Python PyCrypto library for RSA encryption and decryption
RSA is an asymmetric encryption algorithm that is often used to protect the transmission and storage of sensitive data.In Python, we can use the PyCrypto library to achieve RSA encryption and decryption.This article will introduce how to install the PyCrypto library and provide a complete code example and related configuration.
Install the PyCrypto library
First, we need to ensure that Python has been installed.We can then use the PIP command to install the PyCrypto library.Enter the following commands in the command line:
pip install pycrypto
After the installation is completed, we can start using the PyCrypto library for RSA encryption and decryption.
RSA encryption
First of all, we need to generate a pair of RSA keys, including a public key and a private key.You can use the following code to generate a key pair:
python
from Crypto.PublicKey import RSA
# Generate key pair
key = RSA.generate(2048)
# Save the key to the file
private_key = key.export_key()
file_out = open("private.pem", "wb")
file_out.write(private_key)
file_out.close()
public_key = key.publickey().export_key()
file_out = open("public.pem", "wb")
file_out.write(public_key)
file_out.close()
The above code will generate a 2048 -bit RSA key pair, and save the private key into the private.pem file, and the public key is saved into the Public.pem file.
Next, we can encrypt the data with the public key.For example, if you want to encrypt a string, you can use the following code:
python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# Load the public key
public_key = RSA.import_key(open("public.pem").read())
# 创 创
cipher = PKCS1_OAEP.new(public_key)
# 加 加 加
encrypted_data = cipher.encrypt(b"Hello, World!")
print(encrypted_data)
The above code uses the public key to encrypt the string "Hello, World!" And print the encrypted data.
RSA decryption
To decrypt the data, we need to use the private key.The following code demonstrates how to use the private key to decrypt the just encrypted data:
python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# Load the private key
private_key = RSA.import_key(open("private.pem").read())
# 创 创
cipher = PKCS1_OAEP.new(private_key)
# 解 解 解
decrypted_data = cipher.decrypt(encrypted_data)
print(decrypted_data)
The above code uses a private key to decrypt the encrypted data and print the decryption result.
Summarize
This article introduces how to use the Python PyCrypto library for RSA encryption and decryption.We first installed the PyCrypto library, then generated the RSA key pair, and encrypted the data with the public key. The private key decrypted the data.Using the PyCrypto library can easily encrypt and decrypt sensitive data to improve data security.