#鸿蒙通关秘籍#如何在HarmonyOS中实现AES加密的数据持久化存储?

HarmonyOS
2024-12-02 13:39:22
794浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
时光笔ETL

在HarmonyOS中使用AES加密进行数据持久化存储,可以通过封装工具类化简代码使用:

import { PreferencesUtil } from '@pura/harmony-utils';
import { JhEncryptUtils } from './JhEncryptUtils';

// AES 加密存储类
export class JhAESPreferencesUtils {
  // 存储 String 类型
  public static saveString(key: string, value: string) {
    key = JhEncryptUtils.aesEncrypt(key);
    value = JhEncryptUtils.aesEncrypt(value);
    PreferencesUtil.putSync(key, value);
  }

  // 获取 String 类型
  public static getString(key: string): string | null {
    key = JhEncryptUtils.aesEncrypt(key);
    const enValue = PreferencesUtil.getStringSync(key);
    return JhEncryptUtils.aesDecrypt(enValue);
  }

  // 存储 boolean 类型
  public static saveBool(key: string, value: boolean) {
    const newValue = value ? 'TRUE' : 'FALSE';
    JhAESPreferencesUtils.saveString(key, newValue);
  }

  // 获取 boolean 类型
  public static getBool(key: string): boolean {
    const value = JhAESPreferencesUtils.getString(key);
    return value === 'TRUE';
  }

  // 存储 number 类型
  public static saveNumber(key: string, value: number) {
    const newValue = value.toString();
    JhAESPreferencesUtils.saveString(key, newValue);
  }

  // 获取 number 类型
  public static getNumber(key: string): number {
    let value = JhAESPreferencesUtils.getString(key);
    value = value || '0';
    return Number(value);
  }

  // 存储对象
  public static saveModel(key: string, value: Object) {
    const jsonString = JSON.stringify(value);
    JhAESPreferencesUtils.saveString(key, jsonString);
  }

  // 获取对象
  public static getModel(key: string): Object | null {
    const jsonStr = JhAESPreferencesUtils.getString(key);
    return jsonStr ? JSON.parse(jsonStr) : null;
  }

  // 删除单个存储项
  public static delete(key: string) {
    key = JhEncryptUtils.aesEncrypt(key);
    PreferencesUtil.deleteSync(key);
  }

  // 清空所有存储
  public static clear() {
    PreferencesUtil.clear();
  }

  // 检查存储项是否存在
  public static has(key: string): boolean {
    key = JhEncryptUtils.aesEncrypt(key);
    return PreferencesUtil.hasSync(key);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
分享
微博
QQ
微信
回复
2024-12-02 16:12:21
相关问题
如何实现应用数据持久存储
3423浏览 • 1回复 待解决
关于数据持久存储如何实现
1604浏览 • 2回复 待解决
卡片开发如何实现数据持久
3273浏览 • 1回复 待解决
HarmonyOS 持久存储方案
1176浏览 • 1回复 待解决