Using Cryptography for Security in Django App | SecureCoding (2024)

Using Cryptography for Security in Django App | SecureCoding (1)

It is always important to build a secure application.

Django comes with built-in security for passwords, but it doesn’t provide security for other datasets that are supposed to be secured.

If the hurdle of securing data on your Django app has stumped you and you’re looking for an answer, you have come to the right place.

In this tutorial, I will be introducing you to cryptography as a means of securing your application. In the process, we will discuss encryption and hashing and how the two relate to each other. Data, like people’s home addresses, salary, customer information, etc., should be stored securely so that they aren’t exposed in the case of a data breach. When there is a data breach, you wouldn’t want sensitive data to be exposed to other users. This is where cryptography comes in.

Data is typically transmitted from the user to the database. While it is in transit, it should be encrypted. Then, if the network is intercepted, the transmitted data will stay secure. Encryption and hashing of sensitive data is one of the easiest ways to protect critical data.

To follow this article basic understanding of Django framework is required

Contents hide

About Encryption, Decryption, and Cryptography

Build Django Project

Encrypting Data in Database

Conclusion

About Encryption, Decryption, and Cryptography

Encryption is the process of converting the original versions of data into an encoded form known as ciphertext. When this is done, only the receiver is able to decipher the ciphertext back into its original version. Therefore, encryption does not make your application secure it just converts its data into a form that can’t be understood by other people.

Decryption is the act of converting the already encrypted data. It is the exact opposite of encryption. Decryption enables you to decode the encrypted information so that an authorized user can access it with the expected secret key or password.

Cryptography is the process of protecting information by converting it so that it is only readable for the intended recipient. For example, assume a web application user wants to save their address in a database from the frontend. While the data sits in the database, it is at risk of being exposed to a user for whom it isn’t intended. Thus, it is encrypted and then decrypted when necessary. Cryptography encapsulates the concepts of both encryption and decryption.

Build Django Project

First, create a new virtual environment for the project: $ virtualenv env

Activate the virtual environment.

On MacOS and Linux, use $ source env/bin/activate.

On Windows, use $ .\env\Scripts\activate.

To install Django, run (env) $ pip install django. Then, run (env) $ django-admin startproject crypto_project to create a new project.

Now, cd into the root of your application and create an app by running (env) $ python manage.py startapp app.

Add the app you just created to settings.py.

To encrypt your data using django_cryptography, all you need to do is import encrypt from django_cryptography.fields and use it directly on each field where it is required.

In app/models.py put the code given below.

Then, add the code given below to app/admin.py to display your models on your admin page.

Encrypting Data in Database

Normally, when using Django, data is stored in human-readable format. So, the task is to encrypt the data into a format that is not human-readable. Thankfully, we don’t need to write much code since a Django project that provides that service has already been built.

In this article, we will be using django_cryptography.

To install it, just run (env)$ pip install django-cryptography.

Next, we have to create our database. On your terminal, navigate to the root of your project, where manage.py is and run (env)$ python manage.py makemigrations.

Then, run (env)$ python manage.py migrate.

Now, let’s create an admin user so that we can store some data and test out our application.

To do that, run $ python manage.py createsuperuser and fill in the necessary details.

Next, run the server with $ python manage.py runserver. Then, open the admin page on the browser using http://127.0.0.1:8000/admin/ and add some data to the models.

Now, to test whether our security protocol worked, we will use a network other than Django to view our data. In this tutorial, we will use the sqlite3 server to view our database.

To do that, on your terminal, navigate to the folder where the database is and run: $ sqlite3 db.sqlite3

Then, use .tables to see all the tables you have on the database.

Now, run select * from app_mymodel; to view all the data you have saved and you will see that the table you added cryptography to is hidden. It will display the names but not the addresses and health data. This means that our process worked. Now, no one will be able to view the users’ data in the event of a data breach.

You will notice that you are able to see the data without any issues in the Django admin. This is because django_cryptography has been built that way. The data is encrypted once saved, but it is decrypted into plaintext if you access the data with the Django server.

Conclusion

In this article, I briefly discussed encryption, decryption, and cryptography and how you can potentially secure your Django application using them. Encryption and decryption protect applications from sensitive data exposure, which is third in the OWASP Top 10 list. The process given above can protect sensitive data on your Django application if the wrong server, network, or person is trying to access it.

Sensitive data exposure is a very serious issue in current web apps. That is why it is third in the OWASP Top 10 list.

Hopefully, with the process and tools provided in this article, you will be able to start creating Django applications that are free of any sensitive data exposure.

Using Cryptography for Security in Django App | SecureCoding (2024)

FAQs

How do I make my Django app more secure? ›

Django Security Best Practices: Fortifying Your Web Application
  1. Keep Django Up-to-Date. ...
  2. Enable Debug Mode Carefully. ...
  3. Secure Your Django Admin Panel. ...
  4. Implement Strong Authentication. ...
  5. Protect Against Cross-Site Request Forgery (CSRF) ...
  6. Prevent SQL Injection. ...
  7. Validate and Sanitise User Input. ...
  8. Use Django's Security Middleware.
Sep 13, 2023

How does Django provide security? ›

Django's template system protects you against the majority of XSS attacks by escaping specific characters that are "dangerous" in HTML.

What is cryptography in Django? ›

A set of primitives for easily encrypting data in Django, wrapping the Python Cryptography library. Also provided is a drop in replacement for Django's own cryptographic primitives, using Cryptography as the backend provider. Do not forget to read the documentation.

Which is the best authentication for Django? ›

For more robust authentication, Django REST Framework provides integration with OAuth 2.0. OAuth is an authorization standard that allows users to grant third-party access to their data. Typically, this allows users to log in via an external OAuth provider like Google or Facebook.

How to encrypt the password in Django? ›

For storing passwords, Django will use the first hasher in PASSWORD_HASHERS . To store new passwords with a different algorithm, put your preferred algorithm first in PASSWORD_HASHERS . For verifying passwords, Django will find the hasher in the list that matches the algorithm name in the stored password.

How to encrypt data using cryptography? ›

Encryption uses complex mathematical algorithms and digital keys to encrypt data. An encryption algorithm (cipher) and an encryption key encode data into ciphertext. Once the ciphertext is transmitted to the recipient, the same or different key (cipher) is used to decode the ciphertext back into the original value.

What is the default encryption in Django? ›

By default, Django uses the PBKDF2 algorithm with a SHA256 hash, a password stretching mechanism recommended by NIST. This should be sufficient for most users: it's quite secure, requiring massive amounts of computing time to break.

Does Django encrypt passwords? ›

Django provides a secure password hashing mechanism by default, using the PBKDF2 algorithm with a SHA-256 hash. Django uses a robust and secure password hashing mechanism to protect user passwords.

How does Django handle authentication? ›

Overview¶ The Django authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do. Here the term authentication is used to refer to both tasks.

Is Django encrypted? ›

The Django ORM integration encrypts and decrypts values in a transparent way, similar to using a library.

What type of authentication does Django use? ›

Use password hashing: Store user passwords securely by using password hashing. Password hashing is the process of converting a user's password into a hash, which cannot be reversed to obtain the original password. Django's built-in authentication system uses the PBKDF2 algorithm for password hashing.

Is Django good for cyber security? ›

While Django provides good security protection out of the box, it is still important to properly deploy your application and take advantage of the security protection of the web server, operating system and other components. Make sure that your Python code is outside of the web server's root.

How to encrypt data at rest in Django? ›

Using Django Encrypted Model Fields

First install the django-encrypted-model-fields package using pip. Next we need to configure settings.py for usage of the package. Add encrypted_model_fields to the INSTALLED_APPS list. We also need to provide an encryption key for the package to use.

Is cryptography Python safe? ›

However, cryptography does not clear memory by default, as there is no way to clear immutable structures such as bytes . As a result, cryptography , like almost all software in Python is potentially vulnerable to this attack.

How can I make my app more secure? ›

Improve your app's security
  1. Enforce secure communication. Safeguard communication between apps. ...
  2. Provide the right permissions. Use intents to defer permissions. ...
  3. Store data safely. Store private data within internal storage. ...
  4. Keep services and dependencies up to date. ...
  5. More information.

How to protect Django source code? ›

You can encrypt your Django project just the same as you can any other Python code. Don't forget to include "import sourcedefender" to your wsgi/asgi(. py) file so that it gets loaded first and can intercept any import requests to find your encrypted code. You should not encrypt the wsgi/asgi files.

How to make authentication with Django? ›

The main index page should have a “Users” link in the “Auth” section. Unlike other admin pages, “Add user” requires choosing a username and password before you can edit other fields. You must give “add user” and “change user” permissions to any user account that will be creating users via Django Admin.

How to protect sensitive data in Django? ›

Encrypting Database Fields. Django also allows you to encrypt specific fields in your database models using the EncryptedCharField and EncryptedTextField from the django-encrypted-fields package. This ensures that even if your database is compromised, the sensitive data within these fields remains secure.

Top Articles
Latest Posts
Article information

Author: Annamae Dooley

Last Updated:

Views: 6207

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.