Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/dev' into preview
Browse files Browse the repository at this point in the history
  • Loading branch information
feiyuchuixue committed Feb 10, 2025
2 parents d6f606c + 80af9af commit e27ebef
Showing 1 changed file with 15 additions and 25 deletions.
40 changes: 15 additions & 25 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isArray } from '@/utils/is';

import forge from 'node-forge';
/**
* @description 获取localStorage
* @param {String} key Storage名称
Expand Down Expand Up @@ -348,32 +348,22 @@ export function isLocalEnv() {
* 使用 AES-GCM 模式加密消息
* @param {string} message - 待加密的消息
* @param {string} secretKey - 加密密钥(16 字节)
* @returns {Promise<{ iv: string, encryptedData: string }>} - 返回加密后的数据和 IV
* @returns {{ iv: string, encryptedData: string }} - 返回加密后的数据和 IV
*/
export async function aesEncrypt(message: string, secretKey: string) {
try {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey('raw', encoder.encode(secretKey), { name: 'AES-GCM' }, false, ['encrypt']);
export function aesEncrypt(message: string, secretKey: string) {
const iv = forge.random.getBytesSync(12); // 生成随机 IV (12 字节)
const key = forge.util.createBuffer(secretKey, 'utf8').bytes();

const iv = crypto.getRandomValues(new Uint8Array(12)); // 生成随机 IV (12 字节)
const encrypted = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv
},
key,
encoder.encode(message)
);
const cipher = forge.cipher.createCipher('AES-GCM', key);
cipher.start({ iv: iv });
cipher.update(forge.util.createBuffer(message, 'utf8'));
cipher.finish();

// 将加密数据转换为 base64 字符串
const encryptedData = btoa(String.fromCharCode(...new Uint8Array(encrypted)));
const encrypted = cipher.output.getBytes();
const tag = cipher.mode.tag.getBytes();

return {
iv: btoa(String.fromCharCode(...iv)),
encryptedData: encryptedData
};
} catch (error) {
console.error('Encryption failed:', error);
throw error;
}
return {
iv: forge.util.encode64(iv),
encryptedData: forge.util.encode64(encrypted + tag)
};
}

0 comments on commit e27ebef

Please sign in to comment.