Home >Database >Mysql Tutorial >How to encrypt data fields in MySQL database using Go language
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.
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" )
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{})
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!")
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 }
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 }
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"` }
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 }
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.
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) }
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!