|
| 1 | +# SPDX-FileCopyrightText: 2024 Tim Cocks |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | +import binascii |
| 4 | +import json |
| 5 | +import adafruit_rsa |
| 6 | +from adafruit_rsa import PublicKey, PrivateKey |
| 7 | + |
| 8 | +""" |
| 9 | +CircuitPython microcontrollers cannot load PEM key files generated by OpenSSL |
| 10 | +because the pyasn1 module is not supported. This example illustrates a way |
| 11 | +of loading keys from JSON files instead. |
| 12 | +""" |
| 13 | + |
| 14 | +# load a keypair from JSON files |
| 15 | + |
| 16 | +with open("keys/example512key.json", "r") as f: |
| 17 | + priv_key_obj = json.loads(f.read()) |
| 18 | + |
| 19 | + |
| 20 | +with open("keys/example512key_pub.json", "r") as f: |
| 21 | + pub_key_obj = json.loads(f.read()) |
| 22 | + |
| 23 | + |
| 24 | +# initialize the Key objects from data that was loaded from the JSON files |
| 25 | +public_key = PublicKey(*pub_key_obj["public_key_arguments"]) |
| 26 | +private_key = PrivateKey(*priv_key_obj["private_key_arguments"]) |
| 27 | + |
| 28 | +# Message to send |
| 29 | +message = "hello blinka" |
| 30 | + |
| 31 | +# Encode the string as bytes (Adafruit_RSA only operates on bytes!) |
| 32 | +message = message.encode("utf-8") |
| 33 | + |
| 34 | +# Encrypt the message using the public key |
| 35 | +print("Encrypting message...") |
| 36 | +encrypted_message = adafruit_rsa.encrypt(message, public_key) |
| 37 | + |
| 38 | +print("encrypted b64: ") |
| 39 | +print(binascii.b2a_base64(encrypted_message, False).decode()) |
| 40 | + |
| 41 | +# Decrypt the encrypted message using a private key |
| 42 | +print("Decrypting message...") |
| 43 | +decrypted_message = adafruit_rsa.decrypt(encrypted_message, private_key) |
| 44 | + |
| 45 | +# Print out the decrypted message |
| 46 | +print("Decrypted Message: ", decrypted_message.decode("utf-8")) |
0 commit comments