Django+MySQL data desensitization and encryption access

1. Overview

In the Django project, desensitizing the user name and password registered by the front-end client (after encrypting it) and storing it in the target database MySQL can be achieved through the following steps:

  1. Install the necessary libraries: Make sure that password hashing libraries such as bcrypt or passlib are installed in the current Django project. These libraries provide password encryption and verification functions. (can be viewed in pycharm)

  2. Create a user model: Create a user model in Django’s model to store the encrypted username and password. You can use Django’s built-in User model, or customize a new model.

from django.db import models

class longUser(models.Model):
    username = models_.CharField(max_length=150, unique=True)
    password = models.CharField(max_length=128)
  1. Password encryption: During the user registration process, the plaintext password passed by the front end is encrypted, and the encrypted password is stored in the database. Password encryption operations can be performed in view functions or forms. Here’s an example of encryption in a view:
from django.contrib.auth.hashers import make_password #Introduce encryption module
from .models import longUser #Introduce the model defined in models.py

def register(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        hashed_password = make_password(password) # Use the make_password function to encrypt the password
        CustomUser.objects.create(username=username, password=hashed_password)
        # Other registration logic...

    #Other processing logic...
  1. Password verification: During the user login process, the password entered by the user is verified against the encrypted password in the database. You can use Django’s built-in check_password function for password verification.
from django.contrib.auth.hashers import check_password
from .models import CustomUser

def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = CustomUser.objects.get(username=username)
        if check_password(password, user.password): # Use the check_password function for password verification
            # Verification successful, perform login operation
        else:
            # Password verification fails, error processing logic

    #Other processing logic...

Through the above steps, the user name and password registered by the front-end client are encrypted in the Django project and stored in MySQL, and the password is verified when logging in. Pay attention to key security and password hashing algorithm selection to ensure password security.

Second, specific applications

We are now security hardening the project content that has been implemented in the previous blog post: Django + MySQL project security hardening based on self-signed certificates, adding a registration function control to the existing login interface (for registration for users without accounts), and Encrypt the account password submitted by the user and store it in the target database.
Since we have already created and migrated the user information data table (userdate)
my1_userdate in mysql (that is, userdate in models.py, when migrating to mysql, it will automatically be prefixed with the application name, such as my1)

(1) Processed in view function

If we still use the existing large project table, we directly introduce the encryption module for data storage, and only add 1 encryption when storing data in views.

def user_register(request):
    u_pwd = request.POST.get('p')
    user_name1 = request.POST.get('u')
    hash_u_pwd=make_password(u_pwd)
    register_mesage=long_userdate(userid=hash_u_pwd,username=user_name1) # Encryption processing
    register_mesage.save()
    return render(request, 'talk_sub.html')

After data encryption processing, running fonts may cause the following problems


The length of the password hash value generated by the make_password function is fixed, depending on the password hashing algorithm used. In Django, the PBKDF2 algorithm is used by default, and the length of the hash value is 128 characters.

It should be noted that this length refers to the length of the string representation of the generated password hash value, not the actual encrypted binary data length. The password hash value is encoded and stored in the database as a string (as shown below)

Therefore, we need to modify the original table structure, or redefine a table that meets the requirements. This article uses redefining a table long_userdate, as shown below

Regarding data desensitization and storage, the data model can be created in a new way, or it can be implemented using the default model in the association framework. For details, see the content in (2) below.

(2) Model – Table Settings

Two methods are given below:
method one:

1 Redefine a model in models.py

Based on the analysis in the previous section, we can redefine a model in models.py and then use the database migration command to migrate to the target database.

class long_userdate(models.Model):
    userid=models.CharField(max_length=150)
    username=models.CharField(max_length=150)

Method 2 (introducing the user model that comes with the framework):

2 Introduce the user model that comes with Django into the existing table

Django’s built-in User model provides a convenient way to manage user authentication and administration. You can use the User model by following these steps:

(1). Open the models.py file in the Django project.

(2). Import the User model:

from django.contrib.auth.models import User

3). In your model class, associate the User model as a field to your model. Suppose we now have a userdate model, associated with it:

class userdate(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # Other fields...

(4). After the above association is successful, you can use the User model to perform user authentication, user creation, user query and other operations after (3) data migration is successful. For example, here are some common usage examples:

  • Create user:

    user = User.objects.create_user(username='john', password='password123')
    
  • User authentication:

    from django.contrib.auth import authenticate
    
    user = authenticate(username='john', password='password123')
    
    if user is not None:
        # User passed verification
    else:
        # User failed verification
    
  • Query users:

    user = User.objects.get(username='john')
    

(3). Run the database migration command to add the data model to the database:

python manage.py makemigrations
python manage.py migrate
(4) Front-end page and routing settings
1 Insert a form (used to collect user name and password input information) into the interface html file where user registration space needs to be added

For example: (required marks required items, register_message is defined in urls.py below)

<form method="post" action="{% url 'register_message' %}"> #url
        {% csrf_token %}
        <label>Username:</label>
        <input type="text" id="txtPassword" name="p" required><br><br>
        <label>Password:</label>
        <input type="text" id="txtPassword" name="u" required><br><br>
        <input type="submit" value="Register"> # Note that type="submit" here is not a button
</form>
2 Set the url in the project’s urls file

path(register_m/’,views.user_register,name=register_message’)

Through the above steps, the user registration data can be encrypted and stored in the database.

After using the above steps to implement user registration, the previous login module can also be associated with the desensitized user information table (but please note that the previous connection html jump and the