国密算法
国密算法¶
国密算法是指由国家密码管理局认定的国产商用密码算法,旨在保障国家信息安全,减少对外部密码产品的依赖。以下是国密算法的主要组成部分及其特点:
对称加密算法¶
- SM1:不公开的对称加密算法,主要用于芯片等硬件加密产品,适合小数据量加密。
- SM4:分组密码算法,分组长度和密钥长度均为128位,安全性与AES相当,适合数据加密传输和存储。
- SM7:用于非接触式IC卡等场景,如门禁卡、公交卡等。
非对称加密算法¶
- SM2:基于椭圆曲线密码学的公钥密码算法,用于数字签名、密钥交换和数据加密,安全性高且计算效率优于RSA。
- SM9:基于标识的非对称密码算法,适用于物联网等场景,支持群签名和简化身份管理。
杂凑算法¶
- SM3:哈希算法,输出长度为256位,用于数字签名、消息完整性验证,具有高安全性和抗碰撞性。
流加密算法¶
- ZUC:流加密算法,主要用于3GPP LTE通信中的加密和解密操作。
国密算法的应用场景¶
国密算法广泛应用于金融、通信、电子政务、物联网、区块链等领域,为敏感数据提供保护。例如: - 金融领域:用于网上银行、证券交易等,保障交易数据的安全。 - 电子政务:用于电子公文交换系统,确保公文的保密性和完整性。 - 物联网:用于设备身份认证和数据加密。
优势¶
- 高安全性:经过严格的安全评估,能够抵御多种攻击。
- 自主可控:自主研发,减少对外部密码技术的依赖。
- 高效性:计算速度快,适合大规模数据处理。
随着技术的发展,国密算法将继续在信息安全领域发挥重要作用,为国家信息安全和经济发展提供有力保障。
js实现国密算法¶
在 JavaScript 中实现国密算法,常见的库有 sm-crypto 和 gmssl。以下是这两个库的详细介绍以及对应的代码示例。
sm-crypto 库¶
sm-crypto 是一个纯 JavaScript 实现的国密算法库,支持 SM2、SM3 和 SM4 算法。它适用于前端开发,支持浏览器和 Node.js 环境。
安装¶
示例代码¶
SM2(非对称加密/签名)¶
const sm2 = require('sm-crypto').sm2;
// 生成密钥对
const keypair = sm2.generateKeyPairHex();
const publicKey = keypair.publicKey; // 公钥
const privateKey = keypair.privateKey; // 私钥
console.log("Public Key:", publicKey);
console.log("Private Key:", privateKey);
// 加密
const msg = "Hello, SM2!";
const encrypted = sm2.doEncrypt(msg, publicKey, 1); // 1 表示 C1C3C2 模式
console.log("Encrypted:", encrypted);
// 解密
const decrypted = sm2.doDecrypt(encrypted, privateKey, 1);
console.log("Decrypted:", decrypted);
// 签名
const signature = sm2.doSignature(msg, privateKey);
console.log("Signature:", signature);
// 验证签名
const verify = sm2.doVerifySignature(msg, signature, publicKey);
console.log("Verify Signature:", verify);
SM3(哈希算法)¶
const sm3 = require('sm-crypto').sm3;
const msg = "Hello, SM3!";
const hash = sm3(msg);
console.log("SM3 Hash:", hash);
SM4(对称加密)¶
const sm4 = require('sm-crypto').sm4;
const msg = "Hello, SM4!";
const key = "0123456789abcdeffedcba9876543210"; // 128位密钥
const encrypted = sm4.encrypt(msg, key);
console.log("Encrypted:", encrypted);
const decrypted = sm4.decrypt(encrypted, key);
console.log("Decrypted:", decrypted);
gmssl 库¶
gmssl 是一个功能更强大的国密算法库,支持 SM2、SM3、SM4、SM9 等多种算法。它更适合在 Node.js 环境中使用。
安装¶
示例代码¶
SM2(非对称加密/签名)¶
const gmssl = require('gmssl');
// 生成密钥对
const keyPair = gmssl.sm2.generateKeyPair();
const publicKey = keyPair.publicKey;
const privateKey = keyPair.privateKey;
console.log("Public Key:", publicKey);
console.log("Private Key:", privateKey);
// 加密
const msg = "Hello, SM2!";
const encrypted = gmssl.sm2.encrypt(msg, publicKey);
console.log("Encrypted:", encrypted);
// 解密
const decrypted = gmssl.sm2.decrypt(encrypted, privateKey);
console.log("Decrypted:", decrypted);
// 签名
const signature = gmssl.sm2.sign(msg, privateKey);
console.log("Signature:", signature);
// 验证签名
const verify = gmssl.sm2.verify(msg, signature, publicKey);
console.log("Verify Signature:", verify);
SM3(哈希算法)¶
const gmssl = require('gmssl');
const msg = "Hello, SM3!";
const hash = gmssl.sm3(msg);
console.log("SM3 Hash:", hash);
SM4(对称加密)¶
const gmssl = require('gmssl');
const msg = "Hello, SM4!";
const key = "0123456789abcdef"; // 128位密钥
const encrypted = gmssl.sm4.encrypt(msg, key);
console.log("Encrypted:", encrypted);
const decrypted = gmssl.sm4.decrypt(encrypted, key);
console.log("Decrypted:", decrypted);
node-gmssl 库¶
node-gmssl 是一个基于 Node.js 的国密算法库,支持 SM2、SM3、SM4 等算法。它通过 C++ 扩展实现高性能计算。
安装¶
示例代码¶
SM2(非对称加密/签名)¶
const gmssl = require('node-gmssl');
// 生成密钥对
const keyPair = gmssl.sm2.generateKeyPair();
const publicKey = keyPair.publicKey;
const privateKey = keyPair.privateKey;
console.log("Public Key:", publicKey);
console.log("Private Key:", privateKey);
// 加密
const msg = "Hello, SM2!";
const encrypted = gmssl.sm2.encrypt(msg, publicKey);
console.log("Encrypted:", encrypted);
// 解密
const decrypted = gmssl.sm2.decrypt(encrypted, privateKey);
console.log("Decrypted:", decrypted);
// 签名
const signature = gmssl.sm2.sign(msg, privateKey);
console.log("Signature:", signature);
// 验证签名
const verify = gmssl.sm2.verify(msg, signature, publicKey);
console.log("Verify Signature:", verify);
SM3(哈希算法)¶
const gmssl = require('node-gmssl');
const msg = "Hello, SM3!";
const hash = gmssl.sm3(msg);
console.log("SM3 Hash:", hash);
SM4(对称加密)¶
const gmssl = require('node-gmssl');
const msg = "Hello, SM4!";
const key = "0123456789abcdef"; // 128位密钥
const encrypted = gmssl.sm4.encrypt(msg, key);
console.log("Encrypted:", encrypted);
const decrypted = gmssl.sm4.decrypt(encrypted, key);
console.log("Decrypted:", decrypted);
crypto-js(扩展支持)¶
虽然 crypto-js 本身不直接支持国密算法,但可以通过扩展库(如 crypto-js-sm)实现 SM3 和 SM4。
安装¶
示例代码¶
SM3(哈希算法)¶
const CryptoJS = require('crypto-js');
require('crypto-js-sm');
const msg = "Hello, SM3!";
const hash = CryptoJS.SM3(msg);
console.log("SM3 Hash:", hash.toString());
SM4(对称加密)¶
const CryptoJS = require('crypto-js');
require('crypto-js-sm');
const msg = "Hello, SM4!";
const key = CryptoJS.enc.Hex.parse("0123456789abcdef"); // 128位密钥
const encrypted = CryptoJS.SM4.encrypt(msg, key);
console.log("Encrypted:", encrypted);
const decrypted = CryptoJS.SM4.decrypt(encrypted, key);
console.log("Decrypted:", decrypted.toString(CryptoJS.enc.Utf8));
总结¶
sm-crypto:适合前端和 Node.js 环境,实现简单,功能全面。gmssl:功能强大,支持更多算法(如 SM9),适合 Node.js 环境。node-gmssl:高性能实现,适合对性能要求较高的场景。crypto-js(扩展):适合已经使用crypto-js的项目,可以通过扩展库支持国密算法。
根据你的需求选择合适的库即可。
java实现国密算法¶
在 Java 中实现国密算法(如 SM2、SM3、SM4 等),常用的库包括 Bouncy Castle 和 GMSSL。以下是这些库的介绍以及对应的代码示例。
1. Bouncy Castle¶
Bouncy Castle 是一个广泛使用的开源加密库,支持多种密码学算法,包括国密算法(SM2、SM3、SM4 等)。它提供了丰富的 API,适用于 Java 和其他平台。
1.1 添加依赖¶
如果你使用 Maven,可以在 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version> <!-- 使用最新版本 -->
</dependency>
1.2 SM2 示例¶
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.math.ec.ECNamedCurveTable;
import org.bouncycastle.jce.interfaces.ECPrivateKey;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import org.bouncycastle.util.encoders.Hex;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
public class SM2Example {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static void main(String[] args) throws Exception {
// 生成 SM2 密钥对
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
ECParameterSpec ecSpec = new ECParameterSpec(ECNamedCurveTable.getParameterSpec("sm2p256v1").getParameters());
kpg.initialize(ecSpec, new java.security.SecureRandom());
KeyPair keyPair = kpg.generateKeyPair();
ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
// 使用私钥签名
String message = "Hello, SM2!";
byte[] signature = SM2SignUtil.sign(message.getBytes(), privateKey);
System.out.println("Signature: " + Hex.toHexString(signature));
// 使用公钥验证签名
boolean verify = SM2SignUtil.verify(message.getBytes(), signature, publicKey);
System.out.println("Verify: " + verify);
}
}
1.3 SM3 示例¶
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;
public class SM3Example {
public static void main(String[] args) {
String message = "Hello, SM3!";
byte[] data = message.getBytes();
SM3Digest digest = new SM3Digest();
digest.update(data, 0, data.length);
byte[] hash = new byte[digest.getDigestSize()];
digest.doFinal(hash, 0);
System.out.println("SM3 Hash: " + Hex.toHexString(hash));
}
}
1.4 SM4 示例¶
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.SM4Engine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;
public class SM4Example {
public static void main(String[] args) throws Exception {
byte[] key = Hex.decode("0123456789abcdeffedcba9876543210"); // 128位密钥
byte[] iv = Hex.decode("abcdeffedcba9876543210"); // 初始化向量
String plainText = "Hello, SM4!";
byte[] input = plainText.getBytes();
// 加密
CipherParameters params = new ParametersWithIV(new KeyParameter(key), iv);
CBCBlockCipher cipher = new CBCBlockCipher(new SM4Engine());
cipher.init(true, params);
byte[] output = new byte[cipher.getOutputSize(input.length)];
int len = cipher.processBlock(input, 0, output, 0);
cipher.doFinal(output, len);
String encryptedHex = Hex.toHexString(output);
System.out.println("Encrypted: " + encryptedHex);
// 解密
cipher.init(false, params);
byte[] decrypted = new byte[cipher.getOutputSize(output.length)];
len = cipher.processBlock(output, 0, decrypted, 0);
cipher.doFinal(decrypted, len);
System.out.println("Decrypted: " + new String(decrypted));
}
}
2. GMSSL¶
GMSSL 是一个专门用于国密算法的 Java 库,支持 SM2、SM3、SM4 等算法。
2.1 添加依赖¶
如果你使用 Maven,可以在 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>org.gmssl</groupId>
<artifactId>gmssl</artifactId>
<version>1.0.0</version> <!-- 使用最新版本 -->
</dependency>
2.2 示例代码¶
import org.gmssl.crypto.SM2;
import org.gmssl.crypto.SM3;
import org.gmssl.crypto.SM4;
public class GMSSLExample {
public static void main(String[] args) throws Exception {
// SM2 示例
SM2 sm2 = new SM2();
byte[] publicKey = sm2.getPublicKey();
byte[] privateKey = sm2.getPrivateKey();
String message = "Hello, SM2!";
byte[] signature = sm2.sign(message.getBytes(), privateKey);
boolean verify = sm2.verify(message.getBytes(), signature, publicKey);
System.out.println("SM2 Verify: " + verify);
// SM3 示例
SM3 sm3 = new SM3();
byte[] hash = sm3.digest("Hello, SM3!".getBytes());
System.out.println("SM3 Hash: " + Hex.toHexString(hash));
// SM4 示例
SM4 sm4 = new SM4();
byte[] key = Hex.decode("0123456789abcdeffedcba9876543210");
byte[] iv = Hex.decode("abcdeffedcba9876543210");
String plainText = "Hello, SM4!";
byte[] encrypted = sm4.encrypt(plainText.getBytes(), key, iv);
String encryptedHex = Hex.toHexString(encrypted);
System.out.println("Encrypted: " + encryptedHex);
byte[] decrypted = sm4.decrypt(encrypted, key, iv);
System.out.println("Decrypted: " + new String(decrypted));
}
}
总结¶
- Bouncy Castle:功能强大,支持多种加密算法,包括国密算法。适合需要广泛加密功能的场景。
- GMSSL:专注于国密算法,提供了简洁的 API,适合对国密算法有专门需求的场景。
根据你的需求选择合适的库即可。