Home Database Mysql Tutorial How to encrypt data fields in MySQL database using Go language

How to encrypt data fields in MySQL database using Go language

Jun 17, 2023 pm 06:34 PM
mysql go language data encryption

As database security issues become increasingly prominent, data encryption has become a necessary measure. The efficiency and simplicity of the Go language have attracted much attention, especially in the field of web development. This article will introduce how to use Go language to implement encryption processing of data fields in MySQL database.

1. The significance of MySQL database field encryption

In the context of the modern information age, database systems have become more and more important. However, due to increasing threats, database security has become a major challenge for businesses and organizations. Some studies show that database attacks and data breaches have become one of the biggest security risks to business. Therefore, data encryption has become one of the necessary ways to solve this problem.

The significance of database field encryption is to protect sensitive information in the database, such as user names, phone numbers, email addresses, passwords, etc., to prevent hacker attacks and data leaks. By encrypting this sensitive data, hackers can resist data traversal and information theft when the data is obtained.

2. Method of implementing MySQL database data field encryption using Go language

Go language is an efficient, lightweight, compiled, open source programming language that is widely used in Web development. We can use libraries in Go language to encrypt and decrypt data fields in MySQL database. Here we use the GORM library of Go language.

GORM is an excellent Go language ORM library. It provides code-first database access and supports a variety of databases, including MySQL, SQLite, PostgreSQL, SQL Server, etc. We can easily implement encryption of MySQL database by using the GORM library.

  1. Import dependency packages

Open the development environment of Go language and import the dependency packages you need to use:

import (
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)
Copy after login
  1. Database connection

Use GORM's Open function to connect to the database. The code is as follows:

dsn := "user:password@tcp(127.0.0.1:3306)/database_name?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
Copy after login
  1. Record the encryption and decryption keys

In this example, we AES encryption and decryption mechanism will be used. We need to record the encryption and decryption keys in the code for later use. The code is as follows:

var key = []byte("the-key-has-to-be-32-bytes-long!")
Copy after login
  1. Define encryption and decryption functions

We need to define encryption and decryption functions, AES encryption and CBC encryption modes are used here. The encryption function code is as follows:

func encrypt(data []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    plaintext := padData(data)

    // The IV needs to be unique, but not secure. Therefore it's common to
    // include it at the beginning of the ciphertext.
    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := ciphertext[:aes.BlockSize]
    if _, err := rand.Read(iv); err != nil {
        return nil, err
    }

    mode := cipher.NewCBCEncrypter(block, iv)
    mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

    return []byte(base64.StdEncoding.EncodeToString(ciphertext)), nil
}
Copy after login

The decryption function code is as follows:

func decrypt(data []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    ciphertext, err := base64.StdEncoding.DecodeString(string(data))
    if err != nil {
        return nil, err
    }

    if len(ciphertext) < aes.BlockSize {
        return nil, fmt.Errorf("ciphertext too short")
    }

    iv := ciphertext[:aes.BlockSize]
    ciphertext = ciphertext[aes.BlockSize:]

    // CBC mode always works in whole blocks.
    if len(ciphertext)%aes.BlockSize != 0 {
        return nil, fmt.Errorf("ciphertext is not a multiple of the block size")
    }

    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(ciphertext, ciphertext)

    return unpadData(ciphertext), nil
}
Copy after login
  1. Example: Add an encrypted field in the MySQL database

Let’s look at one Complete example. Suppose we want to add an encrypted field to a table in a MySQL database. Write the model code as follows:

type User struct {
    ID      uint
    Name    string
    Email   string
    Passwd  []byte `gorm:"column:passwd"`
}
Copy after login

Next, rewrite the writing and reading methods of the table name and encrypted fields in the model, the code is as follows:

func (u *User) TableName() string {
    return "users"
}

func (u *User) BeforeSave(tx *gorm.DB) (err error) {
    pData, err := encrypt(u.Passwd)
    if err != nil {
        return
    }

    u.Passwd = pData
    return
}

func (u *User) AfterFind(tx *gorm.DB) (err error) {
    pData, err := decrypt(u.Passwd)
    if err != nil {
        return
    }

    u.Passwd = pData
    return
}
Copy after login

In the BeforeSave() method, add User passwords are encrypted and stored. In the AfterFind() method, decrypt the stored encrypted password and return it. This way we can store the encrypted password field in the MySQL database.

  1. Example: Query encrypted fields in MySQL database

When we use encrypted fields in the table, the data must be decrypted during query. We can automatically decrypt encrypted fields in query results by using the AfterFind hook. The following is the sample code:

users := []User{}
result := db.Find(&users)

if result.Error != nil {
    panic(result.Error)
}

for _, user := range users {
    fmt.Println(user)
}
Copy after login

In the above example, we query all user records and print the returned results to the console. When calling the Find() function, GORM will automatically execute the AfterFind() method to decrypt the result.

3. Summary

In this article, we introduce the method of using Go language and GORM library to implement field encryption in MySQL database. The main steps include connecting to the database, defining encryption and decryption functions, and Decryption operations when writing encrypted fields to tables and querying data. With these operations, we can easily encrypt and protect sensitive information in the MySQL database.

The above is the detailed content of How to encrypt data fields in MySQL database using Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1245
24
MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

How does MySQL differ from Oracle? How does MySQL differ from Oracle? Apr 22, 2025 pm 05:57 PM

MySQL is suitable for rapid development and small and medium-sized applications, while Oracle is suitable for large enterprises and high availability needs. 1) MySQL is open source and easy to use, suitable for web applications and small and medium-sized enterprises. 2) Oracle is powerful and suitable for large enterprises and government agencies. 3) MySQL supports a variety of storage engines, and Oracle provides rich enterprise-level functions.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

See all articles