HarmonyOS 读取沙箱中的某个文件,如何转换成Uint8Array格式

let xmlContent: Uint8Array = getContext().resourceManager.getRawFileContentSync("mibook.xml");  

读取沙箱文件有没有类似读取raw文件这样的直接获取到Uint8Array对象。

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

参考示例demo,这个demo里边先创建文件,它会把工程里边的raw底下的xml文件复制到应用沙箱目录下面,然后再点击读取文件他会读取刚才复制到沙箱的文件然后进行解密:

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer, HashMap, util, xml } from '@kit.ArkTS';
import fs, { Options, ReadTextOptions } from '@ohos.file.fs';


let key = 'Q0Rza0M4VGJjNVhwYTBSUg=='
let cipherAlgName = 'AES128|ECB|PKCS7';
let symAlgName = 'AES128';
let base64Helper = new util.Base64Helper;

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  private fileDir: string = ''

  createFile(){
    let xmlContent: Uint8Array = getContext().resourceManager.getRawFileContentSync("mibook.xml");
    let cacheDir = getContext().filesDir;
    this.fileDir = cacheDir + '/HelloWorldlee.xml'
    let file = fs.openSync(this.fileDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    let writeLen = fs.writeSync(file.fd, xmlContent.buffer);
    console.info("write data to file succeed and size is:" + writeLen);
    fs.closeSync(file)
  }
  
  readFile(){
    let stat = fs.statSync(this.fileDir);
    let arraybuf:ArrayBuffer = new ArrayBuffer(stat.size)
    let file = fs.openSync(this.fileDir, fs.OpenMode.READ_WRITE)
    fs.readSync(file.fd,arraybuf)
    let uint8Array: Uint8Array = new Uint8Array(arraybuf);
    let plainText: cryptoFramework.DataBlob = { data: uint8Array };
    this.AES_CBC_Update(plainText)
  }

  build() {
    Column() {
      Scroll() {
        Text(this.message)
          .id('HelloWorld')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .alignRules({
            center: { anchor: '__container__', align: VerticalAlign.Center },
            middle: { anchor: '__container__', align: HorizontalAlign.Center }
          })
      }

      Button('加解密数据')
        .onClick(() => {
          //获取加密文件
          let xmlContent: Uint8Array = getContext().resourceManager.getRawFileContentSync("mibook.xml");
          let plainText: cryptoFramework.DataBlob = { data: xmlContent };
          this.AES_CBC_Update(plainText)
        })
      Button('创建文件')
        .onClick(() => {
          this.createFile();
        })
      Button('读取文件')
        .onClick(() => {
          this.readFile();
        })
    }
    .height('100%')
    .width('100%')
  }
  
  async AES_CBC_Update(plainText: cryptoFramework.DataBlob) {
    //解密
    await this.aesDecryptAll(plainText, key);
  }

  // 解密
  async aesDecrypt(globalCipherText: cryptoFramework.DataBlob, key: string) {
    let globalPlainText = "";
    try {
      let globalCipher = cryptoFramework.createCipher(cipherAlgName);
      let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
      let dataUint8Array = base64Helper.decodeSync(key)
      let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array }
      /*
      * 偏移量
      * */
      let cbcParamsSpec: cryptoFramework.IvParamsSpec = {
        iv: { data: stringToUint8Array("your-iv-your-iva") },
        algName: 'IvParamsSpec'
      };

      let promiseSymKey = await symKeyGenerator.convertKey(keyBlob)
      await globalCipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, promiseSymKey, null);
      let updateLength = 1024;
      for (let i = 0; i <= globalCipherText.data.length / updateLength; i++) {
        let messageArr = globalCipherText.data.slice(i * updateLength, (i + 1) * updateLength);
        let message = new Uint8Array(messageArr);
        let messageBlob: cryptoFramework.DataBlob = { data: message };
        let updateOutput = await globalCipher.update(messageBlob);
        if (updateOutput) {
          globalPlainText += uint8ArrayToString(updateOutput.data);
        }
      }
      let finalOutput = await globalCipher.doFinal(null);
      globalPlainText += uint8ArrayToString(finalOutput.data)
      let strXml = globalPlainText
      let textEncoder: util.TextEncoder = new util.TextEncoder();
      let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
      let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
      let options: xml.ParseOptions = {
        supportDoctype: false,
        ignoreNameSpace: false,
        tagValueCallbackFunction: func,
        attributeValueCallbackFunction: func1
      };
      that.parse(options);
      console.info(str); // 一次打印出所有的属性及其值
      console.log("解密后的明文==》" + globalPlainText.length)
    } catch (err) {
      console.log(err.message)
    }
  }

  // 解密
  async aesDecryptAll(globalCipherText: cryptoFramework.DataBlob, key: string) {
    let globalPlainText = "";
    try {
      let globalCipher = cryptoFramework.createCipher(cipherAlgName);
      let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
      let dataUint8Array = base64Helper.decodeSync(key)
      let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array }
      let promiseSymKey = await symKeyGenerator.convertKey(keyBlob)
      await globalCipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, promiseSymKey, null);
      let updateOutput = await globalCipher.update(globalCipherText);
      let finalOutput = await globalCipher.doFinal(null);
      globalPlainText = uint8ArrayToString(updateOutput.data) + uint8ArrayToString(finalOutput.data)
      let strXml = globalPlainText
      namesMap.clear()
      let textEncoder: util.TextEncoder = new util.TextEncoder();
      let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
      let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer as object as ArrayBuffer, 'UTF-8');
      let options: xml.ParseOptions = {
        supportDoctype: true,
        ignoreNameSpace: true,
        tagValueCallbackFunction: func,
        attributeValueCallbackFunction: func1,
      };
      namesMap.length
      that.parse(options);
      console.info("解析后的属性:" + str1); // 一次打印出所有的属性及其值
      console.log("解密后的明文==》" + globalPlainText.length)
    } catch (err) {
      console.log(err.message)
    }
  }
}

let str: string = '';
let tempName = ""
let namesMap: HashMap<string, string> = new HashMap()
let chapterNamesMap: HashMap<string, string> = new HashMap()
let chaptersXml = false
function isNull(content: string): boolean {
  return content == null || content == undefined || content.length <= 0 || content.indexOf("\n") != -1
}

function func(name: string, value: string): boolean {
  if (!isNull(name)) {
    if ("chapters" == name) {
      chaptersXml = !chaptersXml
    }
    tempName = name
  }
  if (!isNull(value) && !isNull(tempName)) {
    if (chaptersXml) {
      chapterNamesMap.set(tempName, value)
    } else {
      namesMap.set(tempName, value)
    }
  }
  str = name + value;
  console.info('xml解析 func :', "name:" + name + " value:" + value);
  return true; //true:继续解析 false:停止解析
}

let str1: string = '';

function func1(name: string, value: string): boolean {
  str1 += name + ' ' + value + ' ';
  console.log("func1", "解析属性值 name:" + name + " value:" + value)
  return true; // true:继续解析 false:停止解析
}

let str2: string = '';
function func2(name: xml.EventType, value: xml.ParseInfo): boolean {
  str2 = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度
  console.info(str2)
  return true; //true:继续解析 false:停止解析
}

// 字符串转成字节流
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;
}
分享
微博
QQ
微信
回复
1天前
相关问题
Uint8Array和string之间相互转换
3143浏览 • 1回复 待解决
HarmonyOS Uint8Array格式转字符串方法
858浏览 • 1回复 待解决
HarmonyOS 录音发送Uint8Array
67浏览 • 1回复 待解决
HarmonyOS string转Uint8Array
23浏览 • 2回复 待解决
Uint8Array如何转成ArrayBuffer
1593浏览 • 1回复 待解决
如何Uint8Array转ArrayBuffer?
529浏览 • 1回复 待解决
Uint8Array 如何直接转为String or Json
2727浏览 • 1回复 待解决
Uint8Array是@Sendable类吗?
275浏览 • 1回复 待解决
HarmonyOS 如何Uint8Array转为ArrayBuffer
34浏览 • 1回复 待解决
HarmonyOS Uint8Array怎么正确转ArrayBuffer
1461浏览 • 1回复 待解决
ArrayBuffer怎么转Uint8Array
600浏览 • 1回复 待解决
HarmonyOS Uint8Array转16进制
25浏览 • 2回复 待解决
HarmonyOS string怎么与Uint8Array互转?
432浏览 • 1回复 待解决
如何Uint8Array转字符串?
607浏览 • 1回复 待解决
如何将字符串转为Uint8Array
812浏览 • 1回复 待解决
Uint8Array 在native层去解析提示过期
621浏览 • 1回复 待解决
如何某个时间转换成距现在时间
617浏览 • 1回复 待解决