#Security#Encryption#Django

Simple Signing and Unsigning in Django

Medium • Tomisin Abiodun
Medium • Tomisin Abiodun
Jan 28

Learn how to sign and unsigned content in few lines of Django code

Photo by Chris Ried on Unsplash

Initially published on my blog.

In today’s digital landscape, data security has become a crucial aspect of any application.

With the increasing need to protect sensitive information, encryption has emerged as a vital tool for ensuring the safety and privacy of data. This data can include a wide range of sensitive information, such as invite codes, email addresses, usernames, and other personal information that should not be shared with users in plain text.

The use of encryption allows us to scramble this data, making it unreadable to anyone without the appropriate encryption key. This added layer of security is essential for maintaining the trust and confidence of our users, as well as for complying with various legal and regulatory requirements for data protection. As a result, encryption has become an integral part of modern application development, and its use is only expected to continue growing in the future.

Luckily, Django provides a range of utility functions to enable us encrypt and decrypt data of several types — str, int, list, dictionary.

How to generate a secret key in Django

Django provides a utility for generating secret keys. It

from django.core.management.utils import get_random_secret_key
print(get_random_secret_key())

How to Encrypt and Decrypt Data in Django

A. Signer Class

A module in Django called signing has a Signer utility class. The class gives us the chance to supply any encryption key we want, and then use it to encrypt supported datatypes.

from django.core import signing


def encrypt(raw_str: str, encryption_key: str) -> str:
# takes in any encryption key (i.e. salt), and uses it to encrypt some object
signer = signing.Signer(salt=encryption_key)
return signer.sign_object(raw_str)


def decrypt(encoded_str: str, encryption_key: str) -> str:
# takes in any encryption key (i.e. salt), and uses it to decrypt a token
signer = signing.Signer(salt=encryption_key)
try:
return signer.unsign_object(encoded_str)
except signing.BadSignature:
raise ValueError(f"Unable to decode hash {encoded_str}")

B. singing.dumps() and signing.loads()

Django further abstracts encryption by providing two methods dumps and loads, which internally pick the SECRET_KEY supplied in the settings.py file, and then perform encryption operations with the specified encryption key.

from django.core import signing


def encrypt(raw_str: str):
# Picks the `SECRET_KEY` provided in settings.py
return signing.dumps(raw_str)


def decrypt(raw_str: str):
# Picks the `SECRET_KEY` provided in settings.py
return signing.loads(raw_str)

There we have it, signing and unsigning in Django simplified.

Till next time, my guy!

Don’t forget to clap, share and subscribe, if you found this article helpful.

Subscribe * Tomisin Abiodun