用python帮我写一个RSA加密算法
时间: 2024-12-14 17:16:28 浏览: 12
当然可以,RSA是一种非对称加密算法,Python中有一个名为`cryptography`的库可以方便地实现它。下面是一个简单的RSA加密和解密的例子:
```python
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
from cryptography.exceptions import InvalidSignature
# RSA密钥生成
def generate_rsa_key_pair():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
return private_key, public_key
# 加密函数
def encrypt_data(plaintext, public_key):
ciphertext = public_key.encrypt(
plaintext.encode(),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return ciphertext
# 解密函数
def decrypt_data(ciphertext, private_key):
try:
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext.decode()
except InvalidSignature:
print("Invalid signature, decryption failed.")
# 示例
private_key, public_key = generate_rsa_key_pair()
plaintext = "Hello, world!"
ciphertext = encrypt_data(plaintext, public_key)
decrypted_text = decrypt_data(ciphertext, private_key)
print(f"Plaintext: {plaintext}")
print(f"Ciphertext: {ciphertext.hex()}")
print(f"Decrypted Text: {decrypted_text}")
阅读全文