HarmonyOS 加密程序崩溃

//加密
function tcpEncrypt(value: string, iv: string, key: string): Uint8Array {
  let cipher = cryptoFramework.createCipher('AES128|CBC|NoPadding');
  let siv = genIvParamsSpec(iv);
  let symKey = genSymKeyByData(StrUtil.strToUint8Array(key));
  cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, siv);
  let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(value, 'utf-8').buffer) };
  let cipherData = cipher.doFinalSync(plainText);这一行崩溃
  return cipherData.data;
}

崩溃日志:

Error message:do final fail!
Error code:
  Stacktrace:
    at tcpEncrypt (entry/src/main/ets/utils/Aes.ets:116:20)
    at tcpEncryptData (entry/src/main/ets/utils/Aes.ets:14:10)
    at toBuffer (entry/src/main/ets/utils/SQHeaderEx.ets:81:33)
    at send (entry/src/main/ets/utils/TcpSocket.ets:96:20)
    at getTcpPublicKey (entry/src/main/ets/utils/CommonUtil.ets:60:5)
    at anonymous (entry/src/main/ets/utils/TcpSocket.ets:42:7)
HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa

用NoPadding时加密原始数据必须自行保持对齐32字节整数倍,否则会报错,代码中需要自行检测原始数据转换成Uint8Array格式后长度是否为32的倍数以及自行补齐,然后解密时还得操心去除补齐内容,因此可以考虑使用PKCS7替代。

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

@Entry
@Component
struct Index3 {
  @State message: string = 'Hello World';
  stringToUint8Array(str: string) {
    return new Uint8Array(buffer.from(str, 'utf-8').buffer);
  }

  uint8ArrayToString(array: Uint8Array) {
    // 将UTF-8编码转换成Unicode编码
    let out: string = "";
    let index: number = 0;
    let len: number = array.length;
    while (index < len) {
      let character = array[index++];
      switch (character >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
          out += String.fromCharCode(character);
          break;
        case 12:
        case 13:
          out += String.fromCharCode(((character & 0x1F) << 6) | (array[index++] & 0x3F));
          break;
        case 14:
          out += String.fromCharCode(((character & 0x0F) << 12) | ((array[index++] & 0x3F) << 6) |
            ((array[index++] & 0x3F) << 0));
          break;
        default:
          break;
      }
    }
    return out;
  }

  async encryptMessage(src: string, cbc_keys: string, iv_keys: string) {
    try {
      let plainText: cryptoFramework.DataBlob = { data: this.stringToUint8Array(src) };
      let iv: cryptoFramework.IvParamsSpec = {
        algName: 'IvParamsSpec',
        iv: {
          data: this.stringToUint8Array(iv_keys)
        }
      }
      let symAlgName = 'AES128';
      let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
      let dataUint8Array = this.stringToUint8Array(cbc_keys)
      let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array }
      let promiseSymKey: cryptoFramework.SymKey = await symKeyGenerator.convertKey(keyBlob)
      let cipher = cryptoFramework.createCipher('AES128|CBC|NoPadding');
      await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, promiseSymKey, iv);
      let cipherData = await cipher.doFinalSync(plainText);
      return (new util.Base64Helper()).encodeToStringSync(cipherData.data);
    } catch (err) {
      console.info(err)
      return ""
    }
  }

  async decodeString(input: string, cbc_keys: string, iv_keys: string) {
    if (input == '') {
      return ''
    }
    let base = new util.Base64Helper();
    let decoder = cryptoFramework.createCipher('AES128|CBC|NoPadding');
    let iv: cryptoFramework.IvParamsSpec = {
      algName: 'IvParamsSpec',
      iv: {
        data: this.stringToUint8Array(iv_keys)
      }
    }
    let symAlgName = 'AES128';
    let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
    let dataUint8Array = this.stringToUint8Array(cbc_keys)
    let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array }
    let promiseSymKey: cryptoFramework.SymKey = await symKeyGenerator.convertKey(keyBlob)
    await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, promiseSymKey, iv);
    let plainText: cryptoFramework.DataBlob = { data: base.decodeSync(input) }
    let decryptData: cryptoFramework.DataBlob = { data: new Uint8Array() }
    try {
      decryptData = await decoder.doFinal(plainText);
    } catch (e) {
      console.log('=======e', JSON.stringify(e))
    }
    return this.uint8ArrayToString(decryptData.data).toString();
  }

  async aboutToAppear() {
    let key = '62ac6afdd993c395';
    let iv = 'e593c395b953c508';
    let data = '01234567890123456789012345678912';
    let encrypted = await this.encryptMessage(data, key, iv);
    console.log('加密:' + encrypted);
    let newdata = await this.decodeString(encrypted, key, iv);
    console.log('解密:' + newdata);
  }

  build() {
  }
}
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS 引用so库程序崩溃
141浏览 • 1回复 待解决
以下代码导致程序崩溃
576浏览 • 1回复 待解决
程序打开直接崩溃了,如何定位问题
3150浏览 • 1回复 待解决
HarmonyOS AES加密/RSA加密问题
41浏览 • 1回复 待解决
HarmonyOS sendable崩溃问题
37浏览 • 1回复 待解决
HarmonyOS RAS加密,AES加密和解密
160浏览 • 1回复 待解决
HarmonyOS使用HashMap崩溃
527浏览 • 1回复 待解决
HarmonyOS List.clear崩溃
184浏览 • 1回复 待解决
HarmonyOS libuv.so崩溃
397浏览 • 1回复 待解决
HarmonyOS 应用崩溃日志问题
627浏览 • 1回复 待解决
HarmonyOS flutter崩溃问题处理
189浏览 • 1回复 待解决
HarmonyOS API调用崩溃问题
615浏览 • 1回复 待解决
HarmonyOS IDataSource的onDatasetChange()崩溃
161浏览 • 1回复 待解决
HarmonyOS 关于质量-崩溃服务
156浏览 • 1回复 待解决
HarmonyOS 崩溃收集问题咨询
646浏览 • 1回复 待解决