Files
MoonTVPlus/src/lib/crypto.ts

87 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-08-15 13:49:08 +08:00
import CryptoJS from 'crypto-js';
2025-12-26 21:13:12 +08:00
/**
* SHA256
* @param data
* @returns SHA256
*/
export function sha256(data: string): string {
return CryptoJS.SHA256(data).toString(CryptoJS.enc.Hex);
}
/**
* key
* @param folderName
* @param existingKeys key
* @returns keySHA256 10
*/
export function generateFolderKey(folderName: string, existingKeys: Set<string> = new Set()): string {
let hash = sha256(folderName);
let key = hash.substring(0, 10);
// 如果遇到冲突,继续 sha256 直到不冲突
while (existingKeys.has(key)) {
hash = sha256(hash);
key = hash.substring(0, 10);
}
return key;
}
2025-08-15 13:49:08 +08:00
/**
*
* 使 AES
*/
export class SimpleCrypto {
/**
*
* @param data
* @param password
* @returns
*/
static encrypt(data: string, password: string): string {
try {
const encrypted = CryptoJS.AES.encrypt(data, password).toString();
return encrypted;
} catch (error) {
throw new Error('加密失败');
}
}
/**
*
* @param encryptedData
* @param password
* @returns
*/
static decrypt(encryptedData: string, password: string): string {
try {
const bytes = CryptoJS.AES.decrypt(encryptedData, password);
const decrypted = bytes.toString(CryptoJS.enc.Utf8);
if (!decrypted) {
throw new Error('解密失败,请检查密码是否正确');
}
return decrypted;
} catch (error) {
throw new Error('解密失败,请检查密码是否正确');
}
}
/**
*
* @param encryptedData
* @param password
* @returns
*/
static canDecrypt(encryptedData: string, password: string): boolean {
try {
const decrypted = this.decrypt(encryptedData, password);
return decrypted.length > 0;
} catch {
return false;
}
}
}