29 lines
831 B
Python
29 lines
831 B
Python
import base64
|
|
from cryptography.hazmat.backends import default_backend
|
|
from cryptography.hazmat.primitives import serialization, hashes
|
|
from cryptography.hazmat.primitives.asymmetric import padding
|
|
|
|
|
|
def load_keys_public(public_key_file):
|
|
with open(public_key_file, 'rb') as f:
|
|
public_key_data = f.read()
|
|
|
|
public_key = serialization.load_pem_public_key(
|
|
public_key_data,
|
|
backend=default_backend()
|
|
)
|
|
return public_key
|
|
|
|
|
|
def encrypt_message(message, public_key_file):
|
|
public_key = load_keys_public(public_key_file)
|
|
encrypted = public_key.encrypt(
|
|
message.encode(),
|
|
padding.OAEP(
|
|
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
|
algorithm=hashes.SHA256(),
|
|
label=None
|
|
)
|
|
)
|
|
return base64.b64encode(encrypted).decode('utf-8')
|