SM4 国密加解密
国密 SM4 分组密码算法 · 严格遵循
GB/T 32907-2016 /
GM/T 0002-2012 商用密码标准 · 128 位密钥 · 128 位分组 · 32 轮非线性迭代
字符数: 0 | 字节数: 0
长度: 0 字符
代码示例(SM4 加解密)
// npm install sm-crypto
const sm4 = require('sm-crypto').sm4;
const key = '0123456789abcdeffedcba9876543210'; // 32 hex = 16 bytes
const iv = '00000000000000000000000000000000';
// CBC 加密
const cipher = sm4.encrypt('hello 国密', key, {
mode: 'cbc', iv: iv, output: 'string'
});
console.log('密文(hex):', cipher);
// CBC 解密
const plain = sm4.decrypt(cipher, key, {
mode: 'cbc', iv: iv, output: 'string'
});
console.log('明文:', plain);
// BouncyCastle SM4/CBC/PKCS7Padding
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
Security.addProvider(new BouncyCastleProvider());
byte[] key = hexToBytes("0123456789abcdeffedcba9876543210");
byte[] iv = hexToBytes("00000000000000000000000000000000");
Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE,
new SecretKeySpec(key, "SM4"),
new IvParameterSpec(iv));
byte[] encrypted = cipher.doFinal("hello 国密".getBytes("UTF-8"));
# pip install gmssl
from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
key = bytes.fromhex('0123456789abcdeffedcba9876543210')
iv = bytes.fromhex('00000000000000000000000000000000')
sm4 = CryptSM4()
sm4.set_key(key, SM4_ENCRYPT)
cipher = sm4.crypt_cbc(iv, b'hello')
print(cipher.hex())
package main
import (
"encoding/hex"
"fmt"
"github.com/tjfoc/gmsm/sm4"
)
func main() {
key, _ := hex.DecodeString("0123456789abcdeffedcba9876543210")
iv, _ := hex.DecodeString("00000000000000000000000000000000")
encrypted, _ := sm4.Sm4Cbc(key, []byte("hello"), iv, true)
fmt.Println(hex.EncodeToString(encrypted))
decrypted, _ := sm4.Sm4Cbc(key, encrypted, iv, false)
fmt.Println(string(decrypted))
}
SM4 算法说明
| 参数 | 说明 |
|---|---|
| 标准 | GB/T 32907-2016 / GM/T 0002-2012 国家密码管理局 |
| 密钥长度 | 128 位 (16 字节, 32 Hex 字符) |
| 分组长度 | 128 位 (16 字节) |
| 轮数 | 32 轮非线性迭代 |
| S 盒 | 固定 8×8 S 盒 (Sbox),与 AES 不同 |
| 工作模式 | ECB / CBC / CTR / GCM 等 |
| 典型应用 | 金融交易加密、VPN/IPSec、SSL/TLS 国密套件、密码机、身份认证 |
