HarmonyOS 国密SM2转换公钥失败

使用SM2转换我们现有公钥时,一直失败,我们使用的SM2是C1C3C2格式,请问有SM2具体的demo嘛

HarmonyOS
2024-12-25 07:53:00
822浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

请参考如下demo示例:

public async generateSM2KeyTest() {
  let pkData = new Uint8Array([48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45, 3, 66, 0, 4, 90, 3, 58, 157, 190, 248, 76, 7, 132, 200, 151, 208, 112, 230, 96, 140, 90, 238, 211, 155, 128, 109, 248, 40, 83, 214, 78, 42, 104, 106, 55, 148, 249, 35, 61, 32, 221, 135, 143, 100, 45, 97, 194, 176, 52, 73, 136, 174, 40, 70, 70, 34, 103, 103, 161, 99, 27, 187, 13, 187, 109, 244, 13, 7])
  let skData = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 54, 41, 239, 240, 63, 188, 134, 113, 31, 102, 149, 203, 245, 89, 15, 15, 47, 202, 170, 60, 38, 154, 28, 169, 189, 100, 251, 76, 112, 223, 156, 159, 160, 10, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45])
  let pubKeyBlob: cryptoFramework.DataBlob = { data: pkData }
  let priKeyBlob: cryptoFramework.DataBlob = { data: skData }
  let sm2Generator = cryptoFramework.createAsyKeyGenerator('SM2_256');
  let keyPair = await sm2Generator.convertKey(pubKeyBlob, priKeyBlob);
  const pubKey = keyPair.pubKey
  const priKey = keyPair.priKey
  this.sm2PubKey = pubKey
  this.sm2PubKeyString = this.uint8ArrayToHexString(pubKey.getEncoded().data)
  // this.sm2PubKeyArr = pubKey.getEncoded().data
  this.sm2PriKey = priKey
  this.sm2PriKeyString = this.uint8ArrayToHexString(priKey.getEncoded().data)
}
// 指定生成 sm2 密钥对
public async convertSM2AsyKey(pubKeyStr: string, priKeyStr: string): Promise<boolean> {
  const promise = new Promise<boolean>((resolve, reject) => {
    let pubKeyArray = this.hexStringToUint8Array(pubKeyStr)
    let priKeyArray = this.hexStringToUint8Array(priKeyStr)
    let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray };
    let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray };
    let generator = cryptoFramework.createAsyKeyGenerator('SM2_256');
    generator.convertKey(pubKeyBlob, priKeyBlob, (error, data) => {
      if (error) {
        console.error(`convertKey failed, ${error.code}, ${error.message}`);
        resolve(false)
        return;
      }
      this.sm2PubKey = data.pubKey
      this.sm2PubKeyString = pubKeyStr
      this.sm2PriKey = data.priKey
      this.sm2PriKeyString = priKeyStr
      console.info('convertKey success');
      resolve(true)
    });
  })
  return promise

}
/**
   *  SM2 加密
   *  模式:SM2_256|SM3 默认
   */
  public async EncryptWithSM2(plainText: string): Promise<string> {
    const pubKey = this.sm2PubKey
    if (plainText.length <= 0 || pubKey === undefined) {
      return ''
    }
    try {
      const dataBlob: cryptoFramework.DataBlob = { data: this.normalStringToUint8Array(plainText) }
      const cipher = cryptoFramework.createCipher('SM2_256|SM3')
      await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null)
      const encryptData = await cipher.doFinal(dataBlob)
      return this.uint8ArrayToHexString(encryptData.data)
    } catch (e) {
      console.error(`[YLog] encrypt error with ${JSON.stringify(e)}`)
      return ''
    }
  }

  /**
   *  SM2 解密
   *  模式:SM2_256|SM3 默认
   */
  public async DecryptWithSM2(cipherText: string): Promise<string> {
    const priKey = this.sm2PriKey
    if (cipherText.length <= 0 || priKey === undefined) {
      return ''
    }
    try {
      const dataBlob: cryptoFramework.DataBlob = { data: this.hexStringToUint8Array(cipherText) }
      const decoder = cryptoFramework.createCipher('SM2_256|SM3')
      await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, priKey, null)
      const decryptData = await decoder.doFinal(dataBlob)
      return this.uint8ArrayToNormalString(decryptData.data)
    } catch (e) {
      console.error(`[YLog] decrypt error with ${JSON.stringify(e)}`)
      return ''
    }
  }

 /**
   * string Uint8Array相互转换 (正常字符串)
   */
  public normalStringToUint8Array(str: string) {
    let en = new util.TextEncoder()
    let result = en.encodeInto(str)
    return result
  }
  public uint8ArrayToNormalString(array: Uint8Array) {
    let de = util.TextDecoder.create('utf-8', { ignoreBOM : true })
    let result = de.decodeWithStream(array, {stream: false})
    return result
  }

  /**
   * Uint8Array & String 互相转换 (取高4位和低4位) (16进制字符串)
   */
  private uint8ArrayToHexString(array: Uint8Array, lower: boolean = true) {
    let temp = ""
    const hexDigits = this.hexDigits
    for (let i = 0; i < array.length; ++i) {
      const data = array[i]
      // 高四位
      let high = hexDigits[(data & 0xf0) >> 4]
      temp += high
      // 低四位
      let low = hexDigits[data & 0x0f]
      temp += low
    }
    return lower ? temp : temp.toUpperCase()
  }
  private hexStringToUint8Array(plain: string, lower: boolean = true) {
    let result: Uint8Array = new Uint8Array(plain.length / 2)
    for (let i = 0; i < plain.length - 1; i = i + 2) {
      const lowString = plain.charAt(i+1)
      const highString = plain.charAt(i)
      // 低四位
      let low = parseInt(lowString, 16).toString(2)
      while (low.length < 4) { low = '0'+ low }
      // 高四位
      let high = parseInt(highString, 16).toString(2)
      while (high.length < 4) { high = '0' + high }
      // 全八位转10进制
      const res = parseInt(high+low, 2)
      // 放入Uint8Array
      result[i / 2] = res
    }
    return result
  }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
分享
微博
QQ
微信
回复
2024-12-25 11:34:59
相关问题
HarmonyOS SM2PEM读取接口
906浏览 • 1回复 待解决
如何使用SM2算法进行加解密
6438浏览 • 1回复 待解决
HarmonyOS SM2SM4加解密使用demo
1099浏览 • 1回复 待解决
HarmonyOS SM2密钥对转换失败
1566浏览 • 1回复 待解决
HarmonyOS SM2公私钥转换
809浏览 • 1回复 待解决
HarmonyOS sm2验签失败
885浏览 • 1回复 待解决
HarmonyOS 指定私钥生成SM2的方法
804浏览 • 1回复 待解决
huks sm2签名验签失败
1064浏览 • 1回复 待解决
HarmonyOS生成的SM2文服务端无法解析
665浏览 • 1回复 待解决
HarmonyOS SM2密钥问题
786浏览 • 1回复 待解决
HarmonyOS SM2密钥交换
627浏览 • 1回复 待解决