HarmonyOS 国密SM2转换公钥失败

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

HarmonyOS
2天前
浏览
收藏 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
  }
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS SM2SM4加解密使用demo
299浏览 • 1回复 待解决
HarmonyOS SM2PEM读取接口
18浏览 • 1回复 待解决
如何使用SM2算法进行加解密
4449浏览 • 1回复 待解决
HarmonyOS SM2密钥对转换失败
679浏览 • 1回复 待解决
HarmonyOS sm2验签失败
70浏览 • 1回复 待解决
HarmonyOS 指定私钥生成SM2的方法
20浏览 • 1回复 待解决
huks sm2签名验签失败
252浏览 • 1回复 待解决
HarmonyOS SM2数据签名
19浏览 • 1回复 待解决
HarmonyOS 加解密base64转换
28浏览 • 1回复 待解决
HarmonyOS SM2密钥问题
26浏览 • 1回复 待解决
HarmonyOS SM2/SM4结合加解密
26浏览 • 1回复 待解决
HarmonyOS 算法API
455浏览 • 0回复 待解决
HarmonyOS SM2加密算法
18浏览 • 1回复 待解决