Home Java javaTutorial How to implement the encryption, decryption and interconnection of the national secret SM4 and SM2 algorithms in Go?

How to implement the encryption, decryption and interconnection of the national secret SM4 and SM2 algorithms in Go?

Apr 19, 2025 pm 06:27 PM
git go language tool ai

Detailed explanation of the encryption, decryption and interconnection of Go language SM4 and SM2

This article explains in detail how to use Go language to implement the encryption and decryption of the SM4 and SM2 algorithms, and ensure interoperability with Java applications (such as those using the hutool toolkit). This requires the combination of asymmetric encryption algorithm SM2 and symmetric encryption algorithm SM4 to take into account data security and efficiency.

How to implement the encryption, decryption and interconnection of the national secret SM4 and SM2 algorithms in Go?

Encryption process:

  1. SM4 symmetric encryption: The sender first randomly generates a session key secretidcontent . Use this key to SM4 encryption of the message body. The encrypted result is used as the body content of the final message. Go language can use the github.com/emmansun/gmsm library to implement SM4 encryption. The code example is as follows:
 package main

import (
    "fmt"
    "github.com/emmansun/gmsm/sm4"
)

func main() {
    // ... (Get the message body, generate secretidcontent) ...
    cipher, _ := sm4.NewCipher([]byte(secretidcontent))
    // ... (SM4 encryption body) ...
}
Copy after login
  1. SM2 asymmetric encryption: Then, using the receiving party's public key, SM2 encryption is performed on secretidcontent generated in step 1. The encryption result is stored in the secretid field of the message header. The github.com/emmansun/gmsm library also provides SM2 encryption function. Code example:
 package main

import (
    "fmt"
    "github.com/emmansun/gmsm/sm2"
)

func main() {
    // ... (Get the receiver's public key, secretidcontent) ...
    publicKey, _ := sm2.ParsePublicKey(publicKeyBytes)
    encryptedSecretid, _ := sm2.Encrypt(publicKey, []byte(secretidcontent))
    // ... (Put encryptedsecretid into header's secretid) ...
}
Copy after login

Decryption process:

  1. SM2 asymmetric decryption: After receiving the message, the receiver extracts secretid content from the header. Use your own private key to perform SM2 decryption to obtain the secretidcontent key generated in step 1.
 package main

import (
    "fmt"
    "github.com/emmansun/gmsm/sm2"
)

func main() {
    // ... (get private key, secretid in header) ...
    privateKey, _ := sm2.ParsePrivateKey(privateKeyBytes)
    secretidcontent, _ := sm2.Decrypt(privateKey, encryptedSecretid)
    // ...
}
Copy after login
  1. SM4 symmetric decryption: Finally, use the secretidcontent key obtained by decryption to SM4 decrypt the message body to obtain the original message content.
 package main

import (
    "fmt"
    "github.com/emmansun/gmsm/sm4"
)

func main() {
    // ... (get body, secretIdContent) ...
    cipher, _ := sm4.NewCipher([]byte(secretIdContent))
    // ... (SM4 decrypted body) ...
}
Copy after login

Important tips: The above code is for reference only. In actual applications, error handling, parameter verification, and security issues such as key management are required. Please read the documentation of github.com/emmansun/gmsm library carefully and learn in-depth its functions and usage methods.

The above is the detailed content of How to implement the encryption, decryption and interconnection of the national secret SM4 and SM2 algorithms in Go?. 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)

Recommended top ten digital currency APPs in the world (authoritative release in 2025) Recommended top ten digital currency APPs in the world (authoritative release in 2025) Apr 21, 2025 pm 12:09 PM

The world's leading ten digital currency apps include: 1. OKX, 2. Binance, 3. Huobi, 4. Matcha (MXC), 5. Bitget, 6. BitMEX, 7. Pionex, 8. Deribit, 9. Bybit, 10. Kraken. These platforms have their own characteristics in security, transaction services, technical architecture, risk control team, user experience and ecosystem.

Rexas Finance (RXS) can surpass Solana (Sol), Cardano (ADA), XRP and Dogecoin (Doge) in 2025 Rexas Finance (RXS) can surpass Solana (Sol), Cardano (ADA), XRP and Dogecoin (Doge) in 2025 Apr 21, 2025 pm 02:30 PM

In the volatile cryptocurrency market, investors are looking for alternatives that go beyond popular currencies. Although well-known cryptocurrencies such as Solana (SOL), Cardano (ADA), XRP and Dogecoin (DOGE) also face challenges such as market sentiment, regulatory uncertainty and scalability. However, a new emerging project, RexasFinance (RXS), is emerging. It does not rely on celebrity effects or hype, but focuses on combining real-world assets (RWA) with blockchain technology to provide investors with an innovative way to invest. This strategy makes it hoped to be one of the most successful projects of 2025. RexasFi

A list of top 10 global leading virtual currency trading apps in 2025 A list of top 10 global leading virtual currency trading apps in 2025 Apr 21, 2025 pm 12:06 PM

The top ten leading virtual currency trading apps in the world in 2025 are: 1. Binance, 2. Gate.io, 3. OKX, 4. Huobi Global, 5. Bybit, 6. Kraken, 7. FTX, 8. KuCoin, 9. Coinbase, 10. Crypto.com.

2025 trading platform app that can buy digital currency latest version 2025 trading platform app that can buy digital currency latest version Apr 21, 2025 pm 12:30 PM

In today's digital economy era, cryptocurrencies have become the focus of investors and traders. This article will introduce you in detail the ranking of the world's most popular digital currency trading platforms in 2025 to help you make wise choices. These platforms not only provide a variety of cryptocurrency trading pairs, but also have efficient trading systems and powerful security measures. Let's take a deeper understanding of the characteristics and advantages of these top trading platforms.

How to choose a virtual currency exchange app? 2025 Crypto Circle App Exchange Authoritative Ranking How to choose a virtual currency exchange app? 2025 Crypto Circle App Exchange Authoritative Ranking Apr 21, 2025 pm 12:33 PM

Against the backdrop of the rapid development of today's digital currency market, choosing a reliable exchange app has become the top priority of every investor. The authoritative rankings of the 2025 CNY App Exchange provide you with a detailed guide to help you find the platform that suits you the most among the many options. We will evaluate from multiple dimensions such as security, user experience, handling fees, and transaction volume to ensure that you can find a safe, convenient and efficient trading platform. Next, let’s take a look at what are the top three exchange apps.

Despite the speed of market rewards, every coin will eventually encounter pressure and cannot be ignored. Despite the speed of market rewards, every coin will eventually encounter pressure and cannot be ignored. Apr 21, 2025 pm 01:18 PM

The crypto market is changing with opportunities and risks coexisting, and every cryptocurrency is facing tremendous pressure. This article will analyze the current situation of three cryptocurrencies: Sui, Ethereum and BlockDag, and explore the reasons and future trends behind their price fluctuations. Sui: Price is under pressure, and the future trend is unknown. Sui's price trend shows a classic head and shoulder reversal pattern. The current price hovers around US$2.22, down 8.73% from the neckline of US$2.52. In the past 24 hours, nearly US$1.92 million long positions have been closed, and shorts have dominated. Although the MACD indicator bent slightly upward, the volume was insufficient, with support at $2.16 and $1.42 respectively. Unless the bulls break through the $2.52 resistance level, S

The top ten recommendations for 2025 are authoritatively released by the currency trading platform app The top ten recommendations for 2025 are authoritatively released by the currency trading platform app Apr 21, 2025 pm 04:36 PM

The top ten Apps of the 2024 currency trading platform are: 1. Binance, the world's largest trading volume, suitable for professional traders; 2. Gate.io, supports a wide range of digital assets and provides pledge services; 3. OKX, has many innovative functions, supports multi-chain trading; 4. Coinbase, has a friendly interface, suitable for beginners; 5. FTX, focuses on derivative trading, and provides low-cost tools; 6. Huobi, high liquidity, and global layout; 7. Crypto.com, comprehensive services, rich reward plans; 8. Bybit, derivative trading platform, suitable for high-frequency trading; 9. KuCoin, a new token initial platform, low fees; 10. Phem

List of the top 10 safest virtual currency trading platforms in 2025 List of the top 10 safest virtual currency trading platforms in 2025 Apr 21, 2025 pm 12:39 PM

In the world of virtual currency trading, security is one of the most concerned factors for traders. In 2025, after a series of evaluations and user feedback, we have carefully selected the ten most secure virtual currency trading platforms for you. These platforms not only perform well in security measures, but also have been widely recognized in user experience and service quality. Next, we will introduce the characteristics and advantages of these ten platforms in detail to help you find the trading platform that suits you the most.

See all articles