HarmonyOS NEXT api12
@ohos.security.asset (关键资产存储服务)
import { asset } from '@kit.AssetStoreKit';
import { buffer } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
import { YXUniversalTool } from "../YXUniversalTool";
export class YXAssetStore {
public static strToUint8Array(src: string, encoding: buffer.BufferEncoding = 'utf-8'): Uint8Array {
return YXUniversalTool.strToUint8Array(src,encoding);
}
public static unit8ArrayToStr(src: Uint8Array, encoding: buffer.BufferEncoding = 'utf-8'): string {
return YXUniversalTool.unit8ArrayToStr(src,encoding);
}
static setSync(key: string, value: string) {
let attr: asset.AssetMap = new Map();
attr.set(asset.Tag.ALIAS, YXAssetStore.strToUint8Array(key));
attr.set(asset.Tag.SECRET, YXAssetStore.strToUint8Array(value));
attr.set(asset.Tag.ACCESSIBILITY,asset.Accessibility.DEVICE_POWERED_ON);
attr.set(asset.Tag.REQUIRE_PASSWORD_SET,false);
attr.set(asset.Tag.AUTH_TYPE,asset.AuthType.NONE);
attr.set(asset.Tag.SYNC_TYPE, asset.SyncType.THIS_DEVICE);
attr.set(asset.Tag.IS_PERSISTENT,true);
attr.set(asset.Tag.CONFLICT_RESOLUTION, asset.ConflictResolution.OVERWRITE);
try {
asset.addSync(attr);
} catch (err) {
let error = err as BusinessError;
console.log(`AssetStore-set-异常 ~ code: ${error.code} -·- message: ${error.message}`);
}
}
static getSync(key: string): string {
let attr: asset.AssetMap = new Map();
attr.set(asset.Tag.ALIAS, YXAssetStore.strToUint8Array(key));
attr.set(asset.Tag.RETURN_TYPE, asset.ReturnType.ALL);
attr.set(asset.Tag.ACCESSIBILITY,asset.Accessibility.DEVICE_POWERED_ON);
attr.set(asset.Tag.REQUIRE_PASSWORD_SET,false);
attr.set(asset.Tag.AUTH_TYPE,asset.AuthType.NONE);
try {
let res = asset.querySync(attr);
if (res.length == 0) {
return "";
}
let map: asset.AssetMap = res[0];
let arr = map.get(asset.Tag.SECRET) as Uint8Array;
if (arr) {
let value = YXAssetStore.unit8ArrayToStr(arr);
return value;
}
} catch (err) {
let error = err as BusinessError;
console.log(`AssetStore-set-异常 ~ code: ${error.code} -·- message: ${error.message}`);
}
return "";
}
static removeSync(key: string) {
let attr: asset.AssetMap = new Map();
attr.set(asset.Tag.ALIAS, YXAssetStore.strToUint8Array(key));
try {
asset.removeSync(attr);
} catch (err) {
let error = err as BusinessError;
console.log(`AssetStore-set-异常 ~ code: ${error.code} -·- message: ${error.message}`);
}
}
}