请问如何进行SM2key的初始化?

阅读 644
1 个回答

可以参考demo:

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer, util } from '@kit.ArkTS';
import { hilog } from '@kit.PerformanceAnalysisKit';

// 加密消息
async function encryptMessagePromise(publicKey: cryptoFramework.PubKey, plainText: cryptoFramework.DataBlob) {
  //密钥类型为SM2_256、摘要算法为SM3的Cipher
  let cipher = cryptoFramework.createCipher('SM2_256|SM3');
  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, publicKey, null);
  let encryptData = await cipher.doFinal(plainText);
  return encryptData;
}

export async function convertStrToPubKey(keyStr: string): Promise<cryptoFramework.PubKey> {
  let pubKeyStr = keyStr.startsWith("04") ? keyStr.slice(2) : keyStr
  let pkPart1 = pubKeyStr.slice(0, pubKeyStr.length / 2)
  let pkPart2 = pubKeyStr.slice(pubKeyStr.length / 2)
  let pk: cryptoFramework.Point = {
    x: BigInt("0x" + pkPart1),
    y: BigInt("0x" + pkPart2),
  }
  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()
}

async function main() {
  let base64 = new util.Base64Helper();
  //十六进制的公私钥
  let pubKeyStr = "十六进制的公私钥"

 //base64的公私钥 需要转成十六进制公钥
  let pubKeyStr2 = "base64的公私钥"
  let u8aP = base64.decodeSync(pubKeyStr2)
  console.error('Uint8Array u8aP result string:' + u8aP);
  let buf = buffer.from(u8aP);
  console.log('hex u8aP result string:' + buf.toString('hex'));
  let hexpubKeyStr ="十六进制公钥"

  let pubKey = await convertStrToPubKey(hexpubKeyStr)
  // let priKey = await convertStrToPriKey(priKeyStr)


  // 此处为明文
  let message = 'thisistes';
  // 把字符串按utf-8解码为Uint8Array
  let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
  let encryptText = await encryptMessagePromise(pubKey, plainText);
  console.error("encryptText=======>" + buffer.from(encryptText.data).toString('hex'))

  //reslut 是加密后的密文数据
  let spec: cryptoFramework.SM2CipherTextSpec = cryptoFramework.SM2CryptoUtil.getCipherTextSpec(encryptText, 'C1C2C3');
  /*
  * C1 = spec.xCoordinate.toString(16) + spec.yCoordinate.toString(16)
  * C2 = buffer.from(spec.cipherTextData).toString('hex')
  * C3 = buffer.from(spec.hashData).toString('hex')
  * */
  let str = "04" + spec.xCoordinate.toString(16) + spec.yCoordinate.toString(16) + buffer.from(spec.cipherTextData).toString('hex') + buffer.from(spec.hashData).toString('hex')
  console.error("C1C2C3解码后16进制数据=======>" + str)

  let Base64Str = base64.encodeToStringSync(new Uint8Array(buffer.from(str, 'hex').buffer))
  console.error("C1C2C3解码后数据Base64Str=======>" + Base64Str)
}


@Entry
@Component
struct SM2Crypto {
  @State message: string = '点击开始';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            main();
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进