RSA是一种常用的非对称加密算法,广泛应用于数据加密和数字签名等场景。下面以Python为例,演示如何通过RSA进行简单的数据加密与解密,实现安全的数据传输。
cryptography 库:pip install cryptography
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
# 生成私钥
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
# 从私钥中导出公钥
public_key = private_key.public_key()
# 保存密钥到文件(可选)
pem_private = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
pem_public = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('private_key.pem', 'wb') as f:
f.write(pem_private)
with open('public_key.pem', 'wb') as f:
f.write(pem_public)
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
message = b'Hello, RSA 非对称加密!'
# 使用接收方的公钥加密数据
encrypted = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(f'加密后的数据: {encrypted}')
decrypted = private_key.decrypt(
encrypted,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(f'解密后的数据: {decrypted.decode()}')
希望这个实例对你有所帮助!如需了解更多,欢迎继续提问~ 😊