39 lines
1.8 KiB
Python
39 lines
1.8 KiB
Python
from cryptography.hazmat.primitives import serialization, hashes
|
|
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
|
|
|
|
|
class RSAEncryptor:
|
|
def __init__(self, friend_public_key_path: str, my_private_key_path: str, my_public_key_path: str):
|
|
# 加载朋友的公钥
|
|
with open(friend_public_key_path, "rb") as f:
|
|
self.friend_public_key = serialization.load_pem_public_key(f.read())
|
|
|
|
# 加载自己的私钥
|
|
with open(my_private_key_path, "rb") as f:
|
|
self.my_private_key = serialization.load_pem_private_key(f.read(), password=None)
|
|
|
|
# 加载自己的公钥(这个部分是可选的,具体依赖于你的需求)
|
|
with open(my_public_key_path, "rb") as f:
|
|
self.my_public_key = serialization.load_pem_public_key(f.read())
|
|
|
|
def encrypt(self, message: str) -> bytes:
|
|
message_bytes = message.encode("utf-8")
|
|
max_length = self.friend_public_key.key_size // 8 - 2 * hashes.SHA256().digest_size - 2
|
|
if len(message_bytes) > max_length:
|
|
raise ValueError(f"消息过长,最大长度 {max_length} 字节")
|
|
|
|
# 使用朋友的公钥加密消息
|
|
ciphertext = self.friend_public_key.encrypt(
|
|
message_bytes,
|
|
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
|
|
)
|
|
return ciphertext
|
|
|
|
def decrypt(self, ciphertext: bytes) -> str:
|
|
# 使用自己的私钥解密消息
|
|
plaintext = self.my_private_key.decrypt(
|
|
ciphertext,
|
|
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
|
|
)
|
|
return plaintext.decode("utf-8")
|