acp-ws
Version:
基于 WebSocket 的智能体通信库,提供智能体身份管理和实时通信功能
99 lines (98 loc) • 2.75 kB
JavaScript
import AsyncStorage from '@react-native-async-storage/async-storage';
export class CertAndKeyStore {
// 存储数据
static async storeData(key, value) {
try {
await AsyncStorage.setItem(key, JSON.stringify(value));
}
catch (e) {
console.error(e);
}
}
// 获取数据
static async getData(key) {
try {
const value = await AsyncStorage.getItem(key);
if (value == null)
return null;
let parsed;
try {
parsed = JSON.parse(value);
}
catch (e) {
parsed = value;
}
return parsed;
}
catch (e) {
console.error(e);
return null;
}
}
static async getGuestAid() {
try {
const aids = await this.getAids();
if (aids) {
const firstGuestAid = aids.find((aid) => aid.startsWith('guest'));
if (firstGuestAid) {
return firstGuestAid;
}
}
return null;
}
catch (e) {
console.error('获取访客ID失败:', e);
return null;
}
}
static async getAids() {
const aids = await this.getData(this.aidKey);
if (aids) {
return aids;
}
return [];
}
static async saveAid(aid) {
try {
const aids = await this.getAids();
if (aids) {
if (!aids.includes(aid)) {
const mergedAids = [...aids, aid];
await this.storeData(this.aidKey, mergedAids);
}
}
else {
await this.storeData(this.aidKey, [aid]);
}
}
catch (e) {
console.error('保存数组失败:', e);
}
}
static async getCertificate(aid) {
return this.getData(`cert_${aid}`);
}
static async saveCertificate(aid, cert) {
this.storeData(`cert_${aid}`, cert);
}
static async getCsr(aid) {
return this.getData(`csr_${aid}`);
}
static async saveCsr(aid, csr) {
this.storeData(`csr_${aid}`, csr);
}
static async savePrivateKey(aid, key) {
this.storeData(`private_key_${aid}`, key);
}
static async getPrivateKey(aid) {
try {
const encryptedKey = await this.getData(`private_key_${aid}`);
return encryptedKey;
}
catch (error) {
console.error('获取私钥失败:', error);
throw new Error('获取私钥失败');
}
}
}
CertAndKeyStore.aidKey = 'currentAidKey';