HarmonyOS AES解密报错

我有一段 aes 加密的字符串,已确定该段字符串可以正常解析,解析后是一段json

但是我使用如下所示的 EncryptUtils.aesDecrypt() 进行aes 解密报错,是哪里不对

EncryptUtils.aesEncrypt() 是正确的能正常运行逻辑

import cryptoFramework from '@ohos.security.cryptoFramework'; 
import util from '@ohos.util'; 
import buffer from '@ohos.buffer'; 
 
export default class EncryptUtils { 
  // aes 加密 key 
  private static readonly AES_KEY = "sgg45xxxx23455"; 
  // aes 偏移向量 
  private static readonly AES_IV = "8NONxxxxxxysWpM"; 
 
  static async aesEncrypt(content: string): Promise<string> { 
    let symKey = await EncryptUtils.genSymKeyByData() 
    let iv = EncryptUtils.genIvParamsSpec(); 
    let cipher = cryptoFramework.createCipher("AES128|CBC|PKCS7"); 
    await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv) 
    let cipherData = await cipher.doFinal({ 
      data: new Uint8Array(buffer.from(content, 'utf-8').buffer) 
    }) 
    let that = new util.Base64Helper(); 
    let result = that.encodeToStringSync(cipherData.data) 
    return result; 
  } 
 
  static async aesDecrypt(content: string): Promise<string> { 
 
    let symKey = await EncryptUtils.genSymKeyByData() 
    let iv = EncryptUtils.genIvParamsSpec(); 
    let decoder = cryptoFramework.createCipher('AES128|CBC|PKCS7'); 
    await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv); 
    let plainText: cryptoFramework.DataBlob = { 
      data: new Uint8Array(buffer.from(content, 'utf-8').buffer) 
    }; 
    let decryptData = await decoder.doFinal(plainText); 
    let that = new util.Base64Helper(); 
    let result = that.encodeToStringSync(decryptData.data) 
    return result; 
  } 
 
  private static genIvParamsSpec() { 
    const dataIv = EncryptUtils.strToUint8Array(EncryptUtils.AES_IV); 
    let ivBlob: cryptoFramework.DataBlob = {data: dataIv}; 
    let ivParamsSpec: cryptoFramework.IvParamsSpec = { 
      algName: "IvParamsSpec", 
      iv: ivBlob 
    }; 
    return ivParamsSpec; 
  } 
 
  private static async genSymKeyByData() { 
    let aesGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 
    let pubKey = EncryptUtils.strToUint8Array(EncryptUtils.AES_KEY); 
    let pubKeyBlob: cryptoFramework.DataBlob = { 
      data: pubKey 
    }; 
    let symKey = await aesGenerator.convertKey(pubKeyBlob) 
    return symKey; 
  } 
 
  private static strToUint8Array(str: string): Uint8Array { 
    const arr: number[] = []; 
    for (let i = 0, j = str.length; i < j; ++i) { 
      arr.push(str.charCodeAt(i)); 
    } 
    return new Uint8Array(arr); 
  } 
}
HarmonyOS
2024-08-13 15:28:26
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

密文在加密时通常会被编码为Base64格式,解密时需要先将Base64编码的密文解码回原始的二进制格式。需要在解密之前使用Base64解码密文字符串,然后再将其传递给 doFinal 方法进行解密。可参考:

import cryptoFramework from '@ohos.security.cryptoFramework'; 
import buffer from '@ohos.buffer'; 
import util from '@ohos.util'; 
 
@Entry 
@Component 
struct AES_InKey { 
  @State message: string = 'Hello World' 
  build() { 
    Row() { 
      Column() { 
        Text(this.message) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold).onClick(() => { 
          let aes = new AES_CBC(); 
          aes.do(); 
        }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
} 
let key = 'bxxxxf96-f8e4-42' 
let iv = "6c5bd6e53718xxxx980ad0b04d22e7c" 
let base = new util.Base64Helper(); 
export class AES_CBC { 
  async do() { 
    //加密 
    let res = await this.aesEncrypt("枯藤老树昏鸦", key); 
    //解密 
    this.aesDecrypt(res, key); 
  } 
  //加密 
  async aesEncrypt(text: string, key: string): Promise<string> { 
    let globalResult = "" 
    try { 
      let cipherAlgName = 'AES128|CBC|PKCS7'; 
      let globalCipher = cryptoFramework.createCipher(cipherAlgName); 
      let symAlgName = 'AES128'; 
      let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 
      // let dataUint8Array = base.decodeSync(key) 
      // let dataUint8Array =HexStrTouint8Array(key) 
      let dataUint8Array = stringToUint8Array(key) 
      let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array } 
      let promiseSymKey = await symKeyGenerator.convertKey(keyBlob) 
      let globalCbcParams = this.genCBCParamsSpec() 
      //globalCbcParams.iv = { data: stringToUint8Array(iv) } 
      globalCbcParams.iv = { data: HexStrTouint8Array(iv) } 
      await globalCipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, promiseSymKey, globalCbcParams); 
      let plainText: cryptoFramework.DataBlob = { data: stringToUint8Array(text) } 
      let result = await globalCipher.doFinal(plainText) 
      globalResult = base.encodeToStringSync(result.data); 
      let s = uint8ArrayToString(result.data); 
    } catch (err) { 
      console.log(err.message) 
    } 
    return globalResult; 
  } 
  // 解密 
  async aesDecrypt(text: string, key: string) { 
    let globalResult = "" 
    try { 
      let cipherAlgName = 'AES128|CBC|PKCS7'; 
      let globalCipher = cryptoFramework.createCipher(cipherAlgName); 
 
      let symAlgName = 'AES128'; 
      let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 
 
      //let dataUint8Array = base.decodeSync(key) 
      //let dataUint8Array =HexStrTouint8Array(key) 
      let dataUint8Array = stringToUint8Array(key) 
      let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array } 
      let promiseSymKey = await symKeyGenerator.convertKey(keyBlob) 
 
      // /*设置偏移量 */ 
      let globalCbcParams = this.genCBCParamsSpec(); 
      //globalCbcParams.iv = { data: stringToUint8Array(iv) } 
      globalCbcParams.iv = { data: HexStrTouint8Array(iv) } 
      await globalCipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, promiseSymKey, globalCbcParams); 
      let plainText: cryptoFramework.DataBlob = { data: base.decodeSync(text) } 
      let result = await globalCipher.doFinal(plainText) 
      globalResult = uint8ArrayToString(result.data); 
      AlertDialog.show({ message: '解密==》' + globalResult }) 
      console.log("test---解密==》" + globalResult) 
    } catch (err) { 
      console.log(err.message) 
    } 
  } 
  genCBCParamsSpec() { 
    let arr = [0x36, 0x61, 0x38, 0x77, 0x30, 0x63, 0x39, 0x31, 0x6b, 0x63, 0x37, 0x45, 0x55, 0x44, 0x57, 0x46]; 
    let dataIv = new Uint8Array(arr); 
    let ivBlob: cryptoFramework.DataBlob = { 
      data: dataIv 
    }; 
 
    let cbcParamsSpec: cryptoFramework.IvParamsSpec = { 
      iv: ivBlob, 
      algName: 'IvParamsSpec' 
    }; 
    return cbcParamsSpec; 
  } 
} 
// 字符串转成字节流 
function stringToUint8Array(str: string) { 
  return new Uint8Array(buffer.from(str, 'utf-8').buffer); 
} 
 
// 字节流转成可理解的字符串 
function 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; 
} 
 
//十六进制转Uint8Array 
function HexStrTouint8Array(data: string): Uint8Array { 
  return new Uint8Array(buffer.from(data, 'hex').buffer); 
} 
 
//Uint8Array转y十六进制 
function uint8ArrayToHexStr(data: Uint8Array): string { 
  let hexString = ""; 
  let i: number; 
  for (i = 0; i < data.length; i++) { 
    let char = ('00' + data[i].toString(16)).slice(-2); 
    hexString += char; 
  } 
  return hexString; 
}
分享
微博
QQ
微信
回复
2024-08-13 21:49:34
相关问题
RSA加密,使用自有私钥解密报错
43浏览 • 1回复 待解决
HarmonyOS AES解密与java无法通用
353浏览 • 1回复 待解决
使用AES解密时,一直在报解密异常
38浏览 • 1回复 待解决
AES解密长字符串是否需要分段
444浏览 • 1回复 待解决
如何进行不同规格的AES解密
647浏览 • 1回复 待解决
如何对二进制进行AES解密
40浏览 • 1回复 待解决
解密HmacSha1 、HmacSha256、aes参考Demo
1923浏览 • 1回复 待解决
HarmonyOS AES CBC加密问题
329浏览 • 1回复 待解决
HarmonyOS解密 demo
350浏览 • 1回复 待解决
使用32字节秘钥加解密报错
1540浏览 • 1回复 待解决
HarmonyOS RSA解密问题
317浏览 • 1回复 待解决
des解密同步方法解密失败
38浏览 • 1回复 待解决