目录

如何实现SM4加解密工具

问题现象

如何实现一个SM4加解密工具,例如其中入参symAlgName的值为SM4_128,symKeyData的长度是32位,请提供一个SM4加解密Demo。

背景知识

解决方案

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer } from '@kit.ArkTS';

@Entry
@Component
struct Index {
  build() {
    Column({ space: 30 }) {
      Text('SM4加密')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .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.info(`wsf: 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);
            if (encryptData){
              console.info(`wsf: 加密成功`);
            }
          } catch (e) {
            console.error(`wsf: 转密钥报错 e = ${e.code} ${e.message}`);
          }
        })
      Text('SM4解密')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .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);
            let arr = [186, 255, 20, 91, 43, 218, 215, 77, 185, 100, 22, 186, 42, 178, 121, 45];
            let dataAad = new Uint8Array(arr);
            let encryptData: cryptoFramework.DataBlob = { data: dataAad };
            let decoder = cryptoFramework.createCipher('SM4_128|ECB|PKCS7');
            await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null);
            let decryptData = await decoder.doFinal(encryptData);
            console.info(`wsf: 解密成功 ${buffer.from(decryptData.data).toString()}`);
          } catch (e) {
            console.error(`wsf: 转密钥报错 e = ${e.code} ${e.message}`);
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}