# SPDX-FileCopyrightText: 2024 Tim Cocks
# SPDX-License-Identifier: MIT
import binascii
import json

import adafruit_rsa
from adafruit_rsa import PrivateKey, PublicKey

"""
CircuitPython microcontrollers cannot load PEM key files generated by OpenSSL
because the pyasn1 module is not supported. This example illustrates a way
of loading keys from JSON files instead.
"""

# load a keypair from JSON files

with open("keys/example512key.json") as f:
    priv_key_obj = json.loads(f.read())


with open("keys/example512key_pub.json") as f:
    pub_key_obj = json.loads(f.read())


# initialize the Key objects from data that was loaded from the JSON files
public_key = PublicKey(*pub_key_obj["public_key_arguments"])
private_key = PrivateKey(*priv_key_obj["private_key_arguments"])

# Message to send
message = "hello blinka"

# Encode the string as bytes (Adafruit_RSA only operates on bytes!)
message = message.encode("utf-8")

# Encrypt the message using the public key
print("Encrypting message...")
encrypted_message = adafruit_rsa.encrypt(message, public_key)

print("encrypted b64: ")
print(binascii.b2a_base64(encrypted_message, False).decode())

# Decrypt the encrypted message using a private key
print("Decrypting message...")
decrypted_message = adafruit_rsa.decrypt(encrypted_message, private_key)

# Print out the decrypted message
print("Decrypted Message: ", decrypted_message.decode("utf-8"))
