HarmonyOS 鸿蒙Next AES加密成功但解密时崩溃

发布于 1周前 作者 ionicwang 最后一次编辑是 5天前 来自 鸿蒙OS

HarmonyOS 鸿蒙Next AES加密成功但解密时崩溃

解密时,出现了crash,请求协助,感谢!

@Entry
@Component
struct Index {
  aboutToAppear(): void {
    AesUtils.encryptCBC('测试hello', 'newaircloud_vjow9Dej#JDj4[oIDF',(str: string) => {
      this.str = str
    })
  }

  @State str?: string = ''
  @State str2?: string = ''

  build() {
    Column() {
      Text('AES加密:' + this.str)
        .height(100)
        .backgroundColor(Color.Pink)
        .onClick(() => {
          AesUtils.encryptCBC('测试hello', 'newaircloud_vjow9Dej#JDj4[oIDF',(str: string) => {
            this.str = str
          })
        })

      Text('AES解密:' + this.str2)
        .height(100)
        .backgroundColor(Color.Pink)
        .onClick(() => {
          AesUtils.decryptCBC(this.str!, 'newaircloud_vjow9Dej#JDj4[oIDF',(str: string) => {
            this.str2 = str
          })
        })

    }
  }
}

以下是工具类代码:

export class AesUtils {
  static async encryptCBC(message: string, pk: string, callBack: Function) {
    try {
      let base64 = new util.Base64Helper();
      let dataUnit = AesUtils.doMdBySync(pk)

      let symKey = await AesUtils.genSymKeyByData(dataUnit);
      let newBuf = buffer.from(buffer.from(message, 'utf-8').buffer);
      let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(newBuf.buffer) };
      let encryptText = await AesUtils.encryptMessagePromise(symKey, plainText);
      let encrypt = base64.encodeToStringSync(encryptText.data)
      if (callBack) {
        callBack(encrypt)
      }

    } catch (error) {
      console.error(JSON.stringify(error));
      if (callBack) {
        let str = JSON.stringify(error)
        callBack(str)
      }
    }
  }

  public static async decryptCBC(message: string, pk: string, callBack: Function) {
    try {
      let dataUnit = AesUtils.doMdBySync(pk)

      let symKey = await AesUtils.genSymKeyByData(dataUnit);
      let newBuf = buffer.from(buffer.from(message, 'utf-8').buffer);
      let encryptText: cryptoFramework.DataBlob = { data: new Uint8Array(newBuf.buffer) };

      let decryptText = await AesUtils.decryptMessagePromise(symKey, encryptText);
      if (decryptText.data.toString()) {
        let decrypt = buffer.from(decryptText.data).toString('utf-8')
        if (callBack) {
          callBack(decrypt)
        }
      } else {
        if (callBack) {
          callBack('decrypt failed')
        }
      }

    } catch (error) {
      if (callBack) {
        let str = JSON.stringify(error)
        callBack('decrypt failed' + str)
      }
    }
  }

  // key生成
  private static async genSymKeyByData(symKeyData: Uint8Array) {
    let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData };
    let aesGenerator = cryptoFramework.createSymKeyGenerator('AES256');
    let symKey = await aesGenerator.convertKey(symKeyBlob);
    console.info('convertKey success:');
    return symKey;
  }

  // 加密消息
  private static async encryptMessagePromise(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {
    let cipher = cryptoFramework.createCipher('AES256|CBC|PKCS7');
    let iv = AesUtils.genIvParamsSpec();
    await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv);
    let cipherData = await cipher.doFinal(plainText);
    return cipherData;
  }

  // 解密消息
  private static async decryptMessagePromise(symKey: cryptoFramework.SymKey, cipherText: cryptoFramework.DataBlob) {
    let decoder = cryptoFramework.createCipher('AES256|CBC|PKCS7');
    let iv = AesUtils.genIvParamsSpec();
    await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv);
    let decryptData = await decoder.doFinal(cipherText);
    return decryptData;
  }

  private static doMdBySync(key: string): Uint8Array {
    let mdAlgName = 'SHA256'; // 摘要算法名
    let md = cryptoFramework.createMd(mdAlgName);
    let firstArray = new Uint8Array(buffer.from(key, 'utf-8').buffer)
    md.updateSync({ data: firstArray });
    let mdResult = md.digestSync();
    let data = new util.Base64Helper().encodeToStringSync(mdResult.data)
    console.info('[Sync]:Md result base64:' + data);
    let hex = buffer.from(mdResult.data).toString('hex')
    console.info('Md result hex:' + hex);
    let mdLen = md.getMdLength();
    console.info("md len: " + mdLen);

    return mdResult.data
  }

  // iv生成
  private static genIvParamsSpec(): cryptoFramework.IvParamsSpec {
    let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes
    let dataIv = new Uint8Array(arr);
    let ivBlob: cryptoFramework.DataBlob = { data: dataIv };
    let ivParamsSpec: cryptoFramework.IvParamsSpec = {
      algName: "IvParamsSpec",
      iv: ivBlob
    };
    return ivParamsSpec;
  }

}

更多关于HarmonyOS 鸿蒙Next AES加密成功但解密时崩溃的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

解码前要base64进行一次decodeSync。 试试

更多关于HarmonyOS 鸿蒙Next AES加密成功但解密时崩溃的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


针对HarmonyOS鸿蒙Next AES加密成功但解密时崩溃的问题,以下是一些可能的解决方向:

  1. 数据格式:确认加密后的数据在解密前未被篡改或损坏,且格式正确。如果数据经过Base64编码,解密前需要先进行Base64解码。
  2. 密钥管理:确保加密和解密使用的密钥完全一致,且密钥管理过程安全无误。
  3. 加密模式与填充方式:检查加密和解密时使用的模式(如CBC、GCM等)和填充方式(如PKCS7等)是否一致。
  4. 资源竞争:如果应用中存在多线程操作,确保加密和解密过程对共享资源的访问是同步的,避免数据竞争。
  5. 系统兼容性:确认HarmonyOS鸿蒙Next的版本与加密算法库的兼容性。

如果已尝试上述所有可能的解决方向,但问题依旧存在,建议检查相关的系统日志或错误报告,以获取更详细的崩溃信息。同时,为确保问题得到及时有效的解决,可以直接联系官网客服。官网地址是:https://www.itying.com/category-93-b0.html

回到顶部