from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
import os
def generate_keys():
# 生成RSA私钥
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
# 提取公钥
public_key = private_key.public_key()
# 将私钥保存到文件
with open("private_key.pem", "wb") as f:
f.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption() # 如果需要可以添加密码保护
))
# 将公钥保存到文件
with open("public_key.pem", "wb") as f:
f.write(public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
))
def load_private_key():
# 从文件加载私钥
with open("private_key.pem", "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None, # 如果之前设置了密码,则需要在这里提供
backend=default_backend()
)
return private_key
def load_public_key():
# 从文件加载公钥
with open("public_key.pem", "rb") as key_file:
public_key = serialization.load_pem_public_key(
key_file.read(),
backend=default_backend()
)
return public_key
# 检查是否存在密钥文件,如果不存在则生成新的密钥对
if not (os.path.exists("private_key.pem") and os.path.exists("public_key.pem")):
generate_keys()
# 加载密钥
private_key = load_private_key()
public_key = load_public_key()
def encrypt(message):
# 加密消息
message_bytes = message.encode('utf-8')
encrypted_message = public_key.encrypt(
message_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return encrypted_message
def decrypt(encrypted_message):
# 解密消息
decrypted_message_bytes = private_key.decrypt(
encrypted_message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
decrypted_message = decrypted_message_bytes.decode('utf-8')
return decrypted_message
def get_rsa_public_key():
return public_key