rsa加密解密算法python代码
时间: 2024-10-09 21:07:15 浏览: 65
RSA (Rivest-Shamir-Adleman) 算法是一种非对称加密技术,广泛用于数据传输的安全保护。在Python中,你可以使用`cryptography`库来实现RSA加密和解密。下面是一个简单的示例:
```python
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
# 生成RSA密钥对
def generate_rsa_keys():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
return private_key, private_key.public_key()
# RSA加密封装
def encrypt(message, public_key):
ciphertext = public_key.encrypt(
message.encode(),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return ciphertext
# RSA解密封装
def decrypt(ciphertext, private_key):
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext.decode()
# 示例
private_key, public_key = generate_rsa_keys()
message = "Hello, RSA!"
encrypted_message = encrypt(message, public_key)
decrypted_message = decrypt(encrypted_message, private_key)
print(f"原始消息:{message}")
print(f"加密后的消息:{encrypted_message.hex()}")
print(f"解密后的消息:{decrypted_message}")
阅读全文