Это происходит, когда я пытаюсь вызвать CryptoJS.AES.decrypt(...).toString(CryptoJS.enc.Utf8).
Вот минимальный пример моего кода:
Код: Выделить всё
import { ref } from 'vue';
import CryptoJS from 'crypto-js';
interface CryptoKeys {
publicKey: string;
privateKey: string;
}
export function useCrypto() {
function encryptData(data: string, key: string, iv?: string): { ciphertext: string; iv: string } {
const ivValue = iv || CryptoJS.lib.WordArray.random(16).toString(CryptoJS.enc.Hex);
const encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Hex.parse(key), {
iv: CryptoJS.enc.Hex.parse(ivValue),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
const ciphertext = encrypted.toString();
return { ciphertext, iv: ivValue };
}
function decryptData(ciphertext: string, iv: string, key: string): string {
console.log('Decrypting - Raw Inputs:', { ciphertext, iv, key });
try {
if (!ciphertext || !iv || !key) {
throw new Error('Missing or invalid decryption parameters');
}
const parsedCiphertext = CryptoJS.enc.Base64.parse(ciphertext);
const parsedIv = CryptoJS.enc.Hex.parse(iv);
const parsedKey = CryptoJS.enc.Hex.parse(key);
console.log('Decrypting - Parsed Inputs:', { parsedCiphertext, parsedIv, parsedKey });
const decrypted = CryptoJS.AES.decrypt(
{ ciphertext: parsedCiphertext },
parsedKey,
{
iv: parsedIv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
}
);
let decryptedStr = decrypted.toString(CryptoJS.enc.Utf8);
if (!decryptedStr) {
console.warn('UTF-8 conversion failed, trying raw data');
decryptedStr = decrypted.toString();
}
if (!decryptedStr) {
throw new Error('Decryption failed: No valid data');
}
console.log('Decrypted Data:', decryptedStr);
return decryptedStr;
} catch (err) {
console.error('Decryption error:', err);
throw err;
}
}
return {
initialized,
generateSalt,
generateKeyPair,
deriveKey,
encryptData,
decryptData,
exportRecoveryKey,
downloadRecoveryKey,
};
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... -crypto-js