Encrypt and Decrypting strings (Easily) in CircuitPython

Look, this is nothing new, I haven’t invented anything clever, but I couldn’t find an easy copy and paste solution to take a string (of any length), encrypt it with a password… and then decrypt it later on with Circuit Python.

I should start by saying, I’m not a python expert, I’m barely even a novice; I just dip in and out on projects. After a few attempts with ucryptolib (and not really understanding how to use it in CircuitPython) I started looking into aesio and came across this issue on github. It put me down the right path to build something myself that I could just import, generate a key, and encrypt a string… use it, and decrypt it later on. I called it CircuitPython-EasyCrypt because… well, you get it.

Anyway, it’s just one file, it’s here. Just copy it beside your project and import it. Usage is pretty simple… it looks like this:

import EasyCrypt

keystring = "SixteenByteKey!!"
inpstring = "Some super secret string, that I don't want you to see."

# This is the initialisation vector/nonce. I generated it with the below code. As you 
#  will need it to decrypt later on, you might want to store it and not just generate it each time
#  I just generated it like this and printed this one out to store it.
#  import os
#  from binascii import hexlify, unhexlify
#  ivstring = hexlify(os.urandom(16)).decode()

ivstring = "aba0a3bde34a03487eda3ec96d5736a8"

crypted = EasyCrypt.encrypt_string(keystring, inpstring, ivstring)

decrypted = EasyCrypt.decrypt_string(keystring, crypted, ivstring)

Ta da! It’s dumb, it’s just a wrapper on the real encryption stuff. But it works on my Feather M4, and makes my life easy and saves me bytearrying and hexlifying things all over the place. Hopefully if you stumble across it from googling it this will make your life easier.

If you want to reduce the code used you could update your own copy and put the key and/or the nonce in the file and just call encrypt_string(somestring) and decrypt_string(someencryptedstring) if you really wanted, you do you.

It would be cool if you use it to let me know.. I get lonely.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: