python rsa加解密
warning:
这篇文章距离上次修改已过284天,其中的内容可能已经有所变动。
在Python中,可以使用cryptography
库来进行RSA加密和解密。以下是一个简单的例子:
首先,安装cryptography
库(如果尚未安装):
pip install cryptography
然后,使用以下代码进行RSA加密和解密:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# 生成RSA密钥对
def generate_keys():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
# 私钥序列化
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
# 公钥序列化
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return private_pem, public_pem
# RSA加密
def encrypt_data(public_key_pem, data):
public_key = serialization.load_pem_public_key(public_key_pem, default_backend())
encrypted = public_key.encrypt(
data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return encrypted
# RSA解密
def decrypt_data(private_key_pem, encrypted_data):
private_key = serialization.load_pem_private_key(private_key_pem, password=None, backend=default_backend())
decrypted = private_key.decrypt(
encrypted_data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return decrypted
# 使用示例
private_pem, public_pem = generate_keys()
data = b"secret data"
encrypted_data = encrypt_data(public_pem, data)
decrypted_data = decrypt_data(private_pem, encrypted_data)
print("Original data:", data)
print("Encrypted data:", encrypted_data)
print("Decrypted data:", decrypted_data)
这段代码展示了如何生成RSA密钥对,如何加密和解密数据。注意,在实际应用中,密钥对应该安全地存储和管理,而且加密时要使用随机的初始化向量(IV),以及正确的填充方案。
评论已关闭