RSApython代码
时间: 2024-06-24 07:00:35 浏览: 122
RSA.rar_RSA加密的python代码_complex5ix_universee3k
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,广泛用于数据加密和数字签名。在Python中,你可以使用`cryptography`库来实现RSA。以下是一个简单的RSA密码学生成密钥对、加密和解密的示例:
```python
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric.padding import OAEP, PKCS1v15
# 生成RSA密钥对
def generate_rsa_keys():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=serialization.default_backend()
)
public_key = private_key.public_key()
return private_key, public_key
# 保存密钥对
def save_keys(private_key, filename="private.pem", public_key=None, filename_public="public.pem"):
if public_key is None:
public_key = private_key.public_key()
with open(filename, "wb") as f:
private_key_bytes = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
f.write(private_key_bytes)
with open(filename_public, "wb") as f:
public_key_bytes = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
f.write(public_key_bytes)
# 加载密钥对
def load_keys(filename="private.pem", filename_public="public.pem"):
with open(filename, "rb") as f:
private_key = serialization.load_pem_private_key(
data=f.read(),
password=None,
backend=serialization.default_backend()
)
with open(filename_public, "rb") as f:
public_key = serialization.load_pem_public_key(
data=f.read(),
backend=serialization.default_backend()
)
return private_key, public_key
# 加密数据
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
# 解密数据
def decrypt(ciphertext, private_key):
plaintext = private_key.decrypt(
ciphertext,
padding=PKCS1v15()
)
return plaintext.decode()
# 示例
private_key, public_key = generate_rsa_keys()
save_keys(private_key, public_key=public_key)
loaded_private_key, loaded_public_key = load_keys()
encrypted_message = encrypt("Hello, RSA!", loaded_public_key)
decrypted_message = decrypt(encrypted_message, loaded_private_key)
print("Original message:", message)
print("Encrypted message:", encrypted_message.hex())
print("Decrypted message:", decrypted_message)
```
阅读全文