Golang driver

Updated at: 2025-03-31 09:08
important

This topic contains important information on necessary precautions. We recommend that you read this topic carefully before proceeding.

If you encrypt sensitive data columns of a table in an ApsaraDB RDS for MySQL instance or a PolarDB for MySQL cluster and want to use a Go application to access the plaintext data of the encrypted columns, you can use alibabacloud-encdb-mysql-go-client to connect to the database to which the table belongs. This topic describes how to use alibabacloud-encdb-mysql-go-client to connect to a database and access the plaintext data in encrypted columns.

Background information

The column encryption feature allows you to encrypt specific columns in a database, thereby improving data security. Encrypted data is stored in ciphertext in databases. However, you can use an authorized client to decrypt ciphertext data and view plaintext data.

Alibaba Cloud provides the always-confidential client driver alibabacloud-encdb-mysql-go-client for the Go programming language. You need to only use the driver to connect to the database on the client side and specify the master encryption key (MEK) in the database connection URL to access the encrypted database. The driver automatically decrypts ciphertext data and returns plaintext data.

The MEK that you specify is transmitted from the client to the server by using a secure asymmetric encryption protocol. In this case, the client and the server use the same key, and the data can be transmitted between the client and the server by using symmetric encryption in a secure manner.

The value of the MEK is a 16-byte hexadecimal string that is 32 characters in length.

Warning

An MEK is the root credential that you use to authorize a client to access encrypted data. To ensure security, the always-confidential database feature does not generate, store, or back up your MEK. You must manually generate an MEK and make sure that the MEK is securely stored. To ensure the security of databases for which the always-confidential database feature is enabled, you must store and manage the MEK in a secure manner. We recommend that you back up your MEK.

Prerequisites

  • The column encryption feature is enabled for the required database, and the ciphertext permission (JDBC decryption) is granted to the database account. For more information, see Column encryption.

  • The connection information about the encrypted database is obtained, including the endpoint, port number, database name, and database account.

  • An MEK represented by a 32-bit hexadecimal string is generated. Example: 00112233445566778899aabbccddeeff.

    You can use a password generator or a random() function that is provided by a programming language to generate an MEK.

    Examples:

    • Linux: OpenSSL is pre-installed. You can run the openssl rand -hex 16 command to generate a key.

    • Windows: You must install the OpenSSL package.

Usage notes

  • You must store the MEK and keep it confidential.

  • The Go version must be 1.18 or later.

Procedure

1. Obtain the driver

alibabacloud-encdb-mysql-go-client is fully compatible with Go-MySQL-Driver for MySQL Community Edition and supports the database/sql/driver operation of standard Go. In this case, a database connection can be established without the need to modify code.

The open source code of the driver is available on GitHub. For more information, see alibabacloud-encdb-mysql-go-client.

Run the following command to obtain the driver:

go get github.com/aliyun/alibabacloud-encdb-mysql-go-client@latest

2. Configure the MEK parameter and connect to the database

Note
  • If you obtain the driver by configuring a URL, you can use ampersands (&) to concatenate multiple parameters.

  • The MEK parameter and other parameters are configured on the client side and are transmitted to the server side by using envelope encryption. During the process, the confidentiality of the value of the MEK parameter must be ensured.

Sample code:

// Update the connection information such as the endpoint (hostname), port number (port), instance name (dbname), username (username), and password (password) based on the actual scenario. 
db, err := sql.Open("encmysql", "<username>:<password>@tcp(<hostname>:<port>)/<dbname>?MEK=00112233445566778899aabbccddeeff")
if err != nil {
    panic(err)
}

3. Query the plaintext data of an encrypted column

Sample code:

// Initiate a query.	
rows, err := db.Query("SELECT * FROM sddp_test_mask")
if err != nil {
    log.Fatalf("Failed to query data: %v", err)
}
// Make sure that the query result set is closed after it is used.
defer rows.Close() 

// Define variables to store data for each row.
var id int
var name string
var password string
var age int

// Traverse each row.
for rows.Next() {
    // Extract data from the current row and assign the data to the specified variables.
    err := rows.Scan(&id, &name, &password, &age)
    if err != nil {
        log.Fatalf("Failed to scan row: %v", err)
    }

    // Display the data of the current row.
    fmt.Printf("read data: id=%d, name=%s, password=%s, age=%d\n", id, name, password, age)
}

Complete sample code

For example, you use a database account that has the ciphertext permission (JDBC decryption) to view the plaintext data of the encrypted columns in a PolarDB for MySQL database.

For more information about the database configurations in the following sample code, see Column encryption in a PolarDB for MySQL database in the Verify column encryption results section.

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/aliyun/alibabacloud-encdb-mysql-go-client"
)

func main() {
    // Update the connection information such as the endpoint (hostname), port number (port), instance name (dbname), username (username), and password (password) based on the actual scenario.

    db, err := sql.Open("encmysql", "sddp_02:He******4@tcp(polar***.rwlb.rds.aliyuncs.com:3306)/sddp_test?MEK=00112233445566778899aabbccddeeff")
    if err != nil {
        panic(err)
    }

    rows, err := db.Query("SELECT * FROM user3 LIMIT 3")
    if err != nil {
        log.Fatalf("Failed to query data: %v", err)
    }
	
    // Make sure that the query result set is closed after it is used.
    defer rows.Close() 

    // Define variables to store data for each row.
    var id int
    var name string
    var password string
    var age int

    // Traverse each row.
    for rows.Next() {
        // Extract data from the current row and assign the data to the specified variables.
        err := rows.Scan(&id, &name, &password, &age)
        if err != nil {
            log.Fatalf("Failed to scan row: %v", err)
        }

        // Display the data of the current row.
        fmt.Printf("read data: id=%d, name=%s, password=%s, age=%d\n", id, name, password, age)
    }
}

After the preceding code is called, the decrypted result similar to the following information is returned.

image

  • On this page (1, M)
  • Background information
  • Prerequisites
  • Usage notes
  • Procedure
  • 1. Obtain the driver
  • 2. Configure the MEK parameter and connect to the database
  • 3. Query the plaintext data of an encrypted column
  • Complete sample code
Feedback
phone Contact Us

Chat now with Alibaba Cloud Customer Service to assist you in finding the right products and services to meet your needs.

alicare alicarealicarealicare