Home > Database > Mysql Tutorial > How to use MySQL for encrypted communication in Go language

How to use MySQL for encrypted communication in Go language

WBOY
Release: 2023-06-18 08:31:06
Original
967 people have browsed it

As information security issues become increasingly prominent, encrypted communication has become a basic technology in the modern computer field. When using Go language for web development, MySQL database is a commonly used data storage solution. To ensure the security of sensitive data, we need to use encrypted communications to protect confidentiality and integrity during data transmission. This article will introduce how to use MySQL for encrypted communication in Go language.

Encrypt MySQL connection using SSL/TLS protocol

MySQL supports using SSL/TLS protocol to encrypt the connection. The SSL/TLS protocol is a secure transmission protocol widely used on the Internet to ensure that data is protected during transmission. To use SSL/TLS to encrypt a MySQL connection, you need to enable the SSL/TLS function of the MySQL server first, and then specify the use of the SSL/TLS protocol when the client connects.

The following is how to enable SSL/TLS on the MySQL server:

  1. Generate the server certificate and private key

Use the following command to generate the server SSL certificate and private key:

openssl req -x509 -days 3650 -newkey rsa:2048 -nodes -keyout server-key.pem -out server-cert.pem
Copy after login

This command will generate a private key file named server-key.pem and a file named server-cert in the current directory. Certificate file of pem.

  1. Copy the certificate and private key to the specified directory on the MySQL server

Modify the my.cnf configuration file on the MySQL server and specify the service The paths to the client certificate and private key files are as follows:

[mysqld]
ssl-cert=/path/to/server-cert.pem
ssl-key=/path/to/server-key.pem
Copy after login
  1. Restart the MySQL server

Restart the MySQL server to make the configured SSL/TLS certificate and private key take effect .

When the client connects to the MySQL server, it needs to specify the SSL/TLS protocol. When using the mysql command line client, you can use the following command to connect:

mysql --ssl-mode=REQUIRED --ssl-ca=/path/to/server-cert.pem 
--ssl-cert=/path/to/client-cert.pem --ssl-key=/path/to/client-key.pem 
-h your-mysql-hostname -u username -p
Copy after login

Among them, the --ssl-mode parameter specifies the type of SSL/TLS connection, REQUIRED indicates that the SSL/TLS protocol must be used to connect. The --ssl-ca parameter specifies the MySQL server's certificate, and the --ssl-cert and --ssl-key parameters specify the client's certificate and private key. The -h parameter specifies the host name of the MySQL server.

To use the SSL/TLS protocol to connect to the MySQL server in the Go language, you can use the officially provided MySQL driver github.com/go-sql-driver/mysql. When connecting to the MySQL server, you need to specify the SSL/TLS protocol connection. The code is as follows:

db, err := sql.Open("mysql", "user:password@tcp(hostname:port)/dbname?tls=true&tls-ca=path/to/server-cert.pem&tls-cert=path/to/client-cert.pem&tls-key=path/to/client-key.pem")
Copy after login

Among them, the tls=true parameter indicates enabling SSL/TLS encryption, tls The -ca parameter specifies the certificate of the MySQL server, and the tls-cert and tls-key parameters specify the client's certificate and private key.

Use encrypted password to connect to MySQL

In Go language, you can use github.com/go-sql-driver/mysql driverNewCipher()Function encrypts the password. When connecting to the MySQL server, an encrypted password will be used to connect.

The following is a code example for connecting to MySQL using an encrypted password:

import (
    "crypto/aes"
    "crypto/cipher"
    "database/sql"
    "fmt"
    mysql "github.com/go-sql-driver/mysql"
    "strconv"
)

func main() {
    // MySQL服务器配置
    cfg := mysql.NewConfig()
    cfg.User = "root"
    cfg.Passwd = "password" // 原始密码
    cfg.Addr = "hostname:port"
    cfg.DBName = "dbname"
    // 加密密码
    key := []byte("0123456789abcdef") // 密钥
    plaintext := []byte(cfg.Passwd) // 原始密码
    block, _ := aes.NewCipher(key)
    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := ciphertext[:aes.BlockSize]
    for i := range iv {
        iv[i] = byte(i)
    }
    cfb := cipher.NewCFBEncrypter(block, iv)
    cfb.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
    cfg.Passwd = fmt.Sprintf("%x", ciphertext) // 加密后的密码
    // 连接MySQL服务器
    db, err := sql.Open("mysql", cfg.FormatDSN())
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()
    // 执行SQL语句
    rows, err := db.Query("SELECT * FROM tablename")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer rows.Close()
    // 输出结果
    cols, _ := rows.Columns()
    data := make([][]byte, len(cols))
    pointers := make([]interface{}, len(cols))
    for i := range data {
        pointers[i] = &data[i]
    }
    for rows.Next() {
        rows.Scan(pointers...)
        for i := range data {
            fmt.Print(string(data[i]), "    ")
        }
        fmt.Println()
    }
}
Copy after login

In the code, first use the NewConfig() function to create a MySQL server configuration object and set the user name , password, host name, port number and database name. Then use the NewCipher() function to create the AES encrypted key and cipher. After encrypting the original password, use the encrypted password to connect to the MySQL server.

Using an encrypted password to connect to the MySQL server can avoid being eavesdropped on the plaintext password during network transmission, and can prevent hackers from using dictionary attacks and other methods to crack the password.

Summary

This article introduces the method of using MySQL for encrypted communication in Go language. Data confidentiality and integrity can be ensured by encrypting MySQL connections using the SSL/TLS protocol and using encrypted passwords to connect to the MySQL server. In practical applications, appropriate encryption methods should be selected based on actual conditions to ensure the security of sensitive data.

The above is the detailed content of How to use MySQL for encrypted communication in Go language. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template