HarmonyOS 需要一个加解密,SM2,SM4的demo

HarmonyOS
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

SM2,SM4的demo如下:

SM2:

生成SM2密钥对:

async genKeyPairSM2 () {
  const asyGenerator = cryptoFramework.createAsyKeyGenerator('SM2_256')
  this.keyPair = await asyGenerator.generateKeyPair()
  console.info(TAG, 'convertKey success');
  promptAction.showToast({
    message: '生成公私钥成功'
  })
}

加密:

async encodeFun (pubKey: cryptoFramework.PubKey) {
  const plaintextBlob: cryptoFramework.DataBlob = {
    data: new Uint8Array(buffer.from(this.plaintext).buffer)  // 待加密的数据
  }
  const cipher = cryptoFramework.createCipher('SM2_256|SM3')
  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null)
  const secreteBlob = await cipher.doFinal(plaintextBlob)
  console.log(TAG, `加密成功 结果 ${secreteBlob.data}`);
  return secreteBlob
}

解密:

async decodeFun (priKey: cryptoFramework.PriKey) {
     const cipher = cryptoFramework.createCipher('SM2_256|SM3')
     try {
       await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, priKey, null)
       const result = await cipher.doFinal(this.secreteBlob)
       if (result) {
         console.log(TAG, `解密成功`)
         this.decryptData = result
       }
       return result
     } catch (e) {
       console.error(TAG, `解密失败 ${e.code} ${e.message}`)
     }
   }

SM4:根据已有的秘钥参数生成秘钥对象,并加密解密。

Button('SM4')
  .onClick(async () => {
    const symAlgName = 'SM4_128'
    const sKey: string = "9f35eda67432c4ae3892305801b9d0b6";
    const symKeyData = buffer.from(sKey, 'hex')
    let symKeyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(symKeyData.buffer) };
    try {
      let aesGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
      let symKey = await aesGenerator.convertKey(symKeyBlob);
      console.log(`xxx: sm4 转密钥成功`)
      let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from('This is a test', 'utf-8').buffer) };
      const cipher = cryptoFramework.createCipher('SM4_128|ECB|PKCS7')
      await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null)
      const encryptData = await cipher.doFinal(plainText)
      console.log(`xxx: 加密成功`)
      let decoder = cryptoFramework.createCipher('SM4_128|ECB|PKCS7');
      await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null);
      let decryptData = await decoder.doFinal(encryptData);
      console.log(`xxx: 解密成功 ${buffer.from(decryptData.data).toString()}`)
    } catch (e) {
      console.error(`xxx: 转密钥报错 e = ${e.code} ${e.message}`)
    }
  })
分享
微博
QQ
微信
回复
6天前
相关问题
HarmonyOS SM2/SM4结合加解密
107浏览 • 1回复 待解决
HarmonyOS SM2SM4国密加解密使用demo
349浏览 • 1回复 待解决
SM4采用OFB模式进行加解密
1044浏览 • 1回复 待解决
如何使用SM4CBC模式加解密
1058浏览 • 1回复 待解决
HarmonyOS Sm2和DES加解密问题
592浏览 • 1回复 待解决
SM4 CBC模式加解密,有好方案吗?
1166浏览 • 1回复 待解决
如何使用国密SM2算法进行加解密
4622浏览 • 1回复 待解决
HarmonyOS SM2数据签名
54浏览 • 1回复 待解决
HarmonyOS sm4加密有无cbc方式
64浏览 • 1回复 待解决
HarmonyOS 没找到 sm4 cbc 加密
58浏览 • 1回复 待解决
HarmonyOS SM2密钥问题
74浏览 • 1回复 待解决