aardio 文档
aardio 范例: 国密 SM2 示例
国密 SM4
//国密 SM2 示例
//国密 SM4: https://www.aardio.com/zh-cn/doc/example/Text/Crypt/sm4.html
import console;
import BouncyCastle.SM2;
SM2 = BouncyCastle.SM2;
//========== SM2 加密示例 ==========
// 1. 生成密钥对
var pubKey,privateKey = SM2.generateKeyPair();
console.hex("公钥:", pubKey);
console.hex("私钥:", privateKey);
// 2. 加密数据
var plainText = "Hello SM2 国密算法";
var encrypted = SM2.encrypt(plainText, pubKey);
console.hex("密文 (C1C3C2):", encrypted);
// 3. 解密数据
var decrypted = SM2.decrypt(encrypted, privateKey);
console.log("解密结果:", decrypted);
//========== SM2 签名验签示例 ==========
// 4. 签名
var dataToSign = "需要签名的重要数据";
var signature = SM2.sign(dataToSign, privateKey);
console.hex("签名:", signature);
// 5. 验签
var isValid = SM2.verify(dataToSign, signature, pubKey);
console.status(isValid,"验签结果:");
//========== C1C2C3 模式加密 ==========
// 使用 C1C2C3 格式(某些在线工具使用)
var encryptedC1C2C3 = SM2.encrypt(plainText,pubKey,"C1C2C3");
console.log("密文 (C1C2C3):", string.hex(encryptedC1C2C3));
// 解密 C1C2C3 格式
var decryptedC1C2C3 = SM2.decrypt(encryptedC1C2C3,privateKey, "C1C2C3");
console.log("解密结果(C1C2C3):", decryptedC1C2C3);
//========== 带用户 ID 的签名验签 ==========
var userId = "user@example.com";
var signWithId = SM2.sign(dataToSign, privateKey, userId);
var verifyWithId = SM2.verify(dataToSign, signWithId, pubKey, userId);
console.status(verifyWithId,"带用户 ID 的验签:");
console.log("========== 示例:与外部系统交互例 ==========");
// 假设从外部系统获取的公钥(无 04 前缀)
var externalPubKeyHex = "DB742A8F195A15089872E59ED7B3FEF08E7DA2E1F597911D5EF425007FBF01739971355F2D9A7A1CF2057B252C70CA30778BAE80945A0ACB77BA2ACBE3D58BEA";
var externalPubKey = string.unhex(externalPubKeyHex);
// 添加 04 前缀
var publicKey = SM2.addPublicKeyPrefix(externalPubKey);
// 加密数据发送给外部系统
var message = "发送给外部系统的消息";
var encrypted = SM2.encrypt(message, publicKey, "C1C2C3");
// 如果外部系统需要去掉 04 前缀的密文
var encryptedForExternal = SM2.stripPublicKeyPrefix(encrypted);
console.log("发送给外部系统的密文:", string.hex(encryptedForExternal));
// 签名格式转换(如果外部系统使用平面格式 R+S)
var pubKey,privateKey = SM2.generateKeyPair();
var signature = SM2.sign(message, privateKey);
// ASN.1 DER 格式转换为平面格式
var plainSignature = SM2.signatureAsn1ToPlain(signature);
// 从平面格式转回 ASN.1 DER 格式
var asn1Signature = SM2.signaturePlainToAsn1(plainSignature);
var verifyResult = SM2.verify(message, asn1Signature, pubKey);
console.status(verifyResult,"转换后验签:");
console.hex("平面格式签名 (R+S):", plainSignature);
console.pause();
Markdown 格式