In Go, the /tjfoc/gmsm/sm2 package can be used to implement SM2 encryption and decryption.
The sample code is as follows:
package main import ( "fmt" "crypto/rand" "encoding/hex" "/tjfoc/gmsm/sm2" ) func main() { // Generate key pair priKey, err := () if err != nil { (err) return } pubKey := & // plain text message message := "Hello, world!" // Encryption cipher, err := ([]byte(message), ) if err != nil { (err) return } ("Encrypted ciphertext: %s\n", (cipher)) // Decrypt plain, err := (cipher) if err != nil { (err) return } ("Decrypted plain text: %s\n", string(plain)) }
In this example, we first use the function to generate a key pair, where , is a random number generator. Then, we encrypt the plaintext message using the public key to obtain the ciphertext represented by a byte array. We use the function to convert the ciphertext into a hexadecimal string and output the encrypted ciphertext.
Next, we use the private key to decrypt the ciphertext and output the decrypted plaintext. Note that decryption operations require the use of a private key, while encryption operations require the use of a public key. When decrypting, we use the string function to convert the byte array into a string.
It should be noted that the SM2 algorithm needs to use a specific key format, i.e. the PKCS#8 format. Therefore, if you need to save the key to a file or database, you need to use the x509.MarshalPKCS8PrivateKey and functions to convert the key to a byte array.
This is the article about the example code for Go language to implement Sm2 encryption and decryption. For more information about Go Sm2 encryption and decryption, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!