使用密钥参数生成 SM2 密钥对用于加密和解密

发布: (2026年2月4日 GMT+8 16:08)
3 分钟阅读
原文: Dev.to

Source: Dev.to

问题

在 SM2 加密和解密中,HarmonyOS 需要 ASN.1 序列化的密钥数据(91 字节的公钥、51 字节的私钥)。然而,大多数 SM2 密钥以原始、未序列化的数据形式提供(64 字节的公钥、32 字节的私钥),这些数据无法直接使用。

如何将原始 SM2 密钥转换为可在 HarmonyOS 平台上使用的 ASN.1 序列化 SM2 密钥对?

简短回答

通过使用 cryptoFramework 并依据相应的 ASN.1 规范,利用原始参数重新构造 SM2 密钥,生成公钥和私钥。

根据原始参数生成 SM2 公钥

/**
 * Generate SM2 public key based on public key parameters
 * @param keyStr The general format of the public key parameter is 04 + x + y.
 * @returns SM2 public key
 */
async function convertStrToPubKey(keyStr: string): Promise {
  let pubKeyStr = keyStr.startsWith("04") ? keyStr.slice(2) : keyStr;
  let pkPart1 = pubKeyStr.slice(0, pubKeyStr.length / 2);
  let pkPart2 = pubKeyStr.slice(pubKeyStr.length / 2);
  // Enter hexadecimal in the corresponding position
  let pk: cryptoFramework.Point = {
    x: BigInt("0x" + pkPart1),
    y: BigInt("0x" + pkPart2),
  };
  // Public key object parameters
  let pubKeySpec: cryptoFramework.ECCPubKeySpec = {
    params: cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_sm2'),
    pk: pk,
    algName: "SM2",
    specType: cryptoFramework.AsyKeySpecType.PUBLIC_KEY_SPEC,
  };
  let keypairGenerator = cryptoFramework.createAsyKeyGeneratorBySpec(pubKeySpec);
  return await keypairGenerator.generatePubKey();
}

根据原始参数生成 SM2 私钥

/**
 * Generate SM2 private key based on private key parameters
 * @param keyStr The private key parameter is generally a 128‑bit string.
 * @returns SM2 private key
 */
async function convertStrToPriKey(keyStr: string): Promise {
  let sk = BigInt("0x" + keyStr);
  // Private key object parameters
  let priKeySpec: cryptoFramework.ECCPriKeySpec = {
    params: cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_sm2'),
    sk: sk,
    algName: "SM2",
    specType: cryptoFramework.AsyKeySpecType.PRIVATE_KEY_SPEC,
  };
  let keypairGenerator = cryptoFramework.createAsyKeyGeneratorBySpec(priKeySpec);
  return await keypairGenerator.generatePriKey();
}

更多细节请参阅文档 SM2 Encryption and Decryption

适用场景

  • 当提供原始 SM2 密钥数据(64 字节公钥、32 字节私钥)时。
  • 当 HarmonyOS 需要 ASN.1 序列化的密钥数据(91 字节公钥、51 字节私钥)用于 SM2 加密和解密时。

参考链接

Back to Blog

相关文章

阅读更多 »

🔒 HTTPS 像5岁小孩一样解释

完整的深度解析并附带代码示例 https://sreekarreddy.com/learn/eli5/https 明信片 vs. 密封信 HTTP 无 S:像明信片——任何处理它的人都可以读取…

JSON.Stringify 的第二个参数

在 JavaScript 中,JSON.stringify 是一个内置方法,用于将 JavaScript 值转换为 JSON 字符串表示。JSON(JavaScript Object Notation)是一种通用的数据交换格式。