Using the field encryption key to decrypt secrets in Crypt Server

Why do this? Well, you shouldn’t really ever need to do this. The beauty of Crypt Server is that you run the docker container with the field encryption key, and Django automatically does all the encrypting and decrypting for you. You shouldn’t need to look manually at the keys stored in the database.

But, in case you have an edge case for doing so, or in case you’re thinking “How closely should I guard the field encryption key?” here’s a script you can use the field encryption key to decrypt the secrets stored in Crypt (to be run inside the Docker container, but if you can find other ways to connect to your database living outside Docker, feel free to modify accordingly).

#!/usr/local/bin/python3

from cryptography.fernet import Fernet
import sqlite3

FIELD_ENCRYPTION_KEY = 'FILLINYOURACTUALENCRYPTIONKEYHERE'

connection = sqlite3.connect("/home/docker/crypt/crypt.db")
cursor = connection.cursor()

cursor.execute("SELECT secret FROM server_secret;")
rows = cursor.fetchall()

for row in rows:
    print(Fernet(FIELD_ENCRYPTION_KEY).decrypt(token=row[0]))

That’s using sqlite3 as a simple example. If you need to use Postgres, you can look into sqlalchemy.

If you want to be even simpler and not script things, you can just go with some commands using Django shell (thanks to Graham Gilbert for this tip):

docker exec -it NAMEOFDOCKERCONTAINER /bin/sh
python manage.py shell
from cryptography.fernet import Fernet
print(Fernet('FIELD_ENCRYPTION_KEY').decrypt(token='SECRET_TO_BE_DECRYPTED'))


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *