RSA加密算法python实现
时间: 2024-10-08 14:16:31 浏览: 39
RSA是一种非对称加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman于1977年发明。Python中可以使用内置库`cryptography`或第三方库`pycryptodome`来实现RSA。以下是基本的RSA加密算法在Python中的一种实现:
```python
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
# 生成密钥对
def generate_rsa_keys():
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
private_key = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
public_key = key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return private_key, public_key
# 加密函数
def encrypt_message(message, public_key):
encrypted = public_key.encrypt(
message.encode(),
padding=serialization.OAEP(
mgf=serialization.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return encrypted
# 解密函数
def decrypt_message(encrypted_message, private_key):
decrypted = private_key.decrypt(
encrypted_message,
padding=serialization OAEP(
mgf=serialization.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return decrypted.decode()
# 示例
private_key, public_key = generate_rsa_keys()
message = "Hello, RSA!"
encrypted = encrypt_message(message, public_key)
decrypted = decrypt_message(encrypted, private_key)
print(f"原始消息: {message}")
print(f"加密后: {encrypted.hex()}")
print(f"解密后: {decrypted}")
```
阅读全文