闽公网安备 35020302035485号
SM4:无线局域网标准的分组数据算法,属于对称加密,密钥长度和分组长度均为128位。
const { sm2 } = require('sm-crypto');
const keyPair = sm2.generateKeyPairHex(); // 生成密钥对
const publicKey = keyPair.publicKey; // 公钥
const privateKey = keyPair.privateKey; // 私钥
const message = 'Hello, SM2!'; // 待加密的消息
const encrypted = sm2.doEncrypt(message, publicKey, { hash: true }); // 使用公钥加密
const decrypted = sm2.doDecrypt(encrypted, privateKey, { hash: true, raw: true }); // 使用私钥解密
console.log('加密结果:', encrypted);
console.log('解密结果:', decrypted.toString()); // 输出原始消息

const { sm3 } = require('sm-crypto');
const message = 'Hello, SM3!'; // 待计算摘要的消息
const digest = sm3(message); // 计算SM3摘要值
console.log('SM3摘要值:', digest);

const sm4 = require('sm-crypto').sm4; |
const sm4 = require('sm-crypto').sm4;
const key = '0123456789abcdeffedcba9876543210'; // 16字节的SM4密钥
const message = 'Hello, SM4!'; // 待加密的消息
const encrypted = sm4.encrypt(Buffer.from(message), Buffer.from(key, 'hex')); // 加密
const decrypted = sm4.decrypt(encrypted, Buffer.from(key, 'hex')); // 解密
// 堆代码 duidaima.com
console.log('加密结果:', encrypted.toString('hex'));
console.log('解密结果:', decrypted.toString()); // 输出原始消息
4、签名/验签const { sm2 } = require('sm-crypto');
const keyPair = sm2.generateKeyPairHex(); // 生成密钥对
const publicKey = keyPair.publicKey; // 公钥
const privateKey = keyPair.privateKey; // 私钥
const message = '这是要签名的消息'; // 替换为实际要签名的消息
// 使用私钥对消息进行签名
let sigValueHex = sm2.doSignature(message, privateKey);
console.log('签名结果:', sigValueHex);
验签(Verify Signature)
const message = '这是要验证签名的消息'; // 应与签名时使用的消息相同
const sigValueHex = '签名值'; // 替换为实际的签名值字符串,即签名步骤中生成的sigValueHex
// 使用公钥验证签名是否有效
let verifyResult = sm2.doVerifySignature(message, sigValueHex, publicKey);
console.log('验签结果:', verifyResult); // 如果验证成功,应输出true;否则输出false
实战例子// smCrypto.js
import { sm2 } from 'sm-crypto' // 引入加密库
export const doEncrypt = ( // 加密
data,
pKey = publicKey,
cipherMode = 0
) =>
sm2.doEncrypt(
typeof data === 'object'
? JSON.stringify(data) : data,
pKey,
cipherMode
)
export const encryptionPwd = async data => { // 加密密码高阶
let servePublicKey = ''
await user.getSm2Pkeys()
.then(res => {
servePublicKey = res.data.content
})
return doEncrypt(
data,
servePublicKey
)
}
sm-crypto作为一款基于Node.js的国密算法库,为开发者提供了丰富的密码学功能。通过调用sm-crypto的内部方法,开发者可以轻松地实现SM2加密与解密、SM3摘要计算以及SM4分组加密等操作。这些功能在保障数据安全、构建安全应用等方面发挥着重要作用。同时,开发者在使用sm-crypto时,也需要注意遵循最佳的安全实践,确保密钥的安全存储和管理,以防止潜在的安全风险。