Операция не удалась по причине, специфичной для операции: сбой задания шифрования.Javascript

Форум по Javascript
Ответить
Anonymous
 Операция не удалась по причине, специфичной для операции: сбой задания шифрования.

Сообщение Anonymous »

У меня есть следующий код, который должен зашифровать строку с паролем в nodeJS. Вы можете найти пример здесь: https://jsfiddle.net/ujr4gev3/1/
Я также попробовал этот подход здесь: https://gist.github.com/chrisveness/43b ... 678071b90a, и это приводит к той же ошибке.
const b64 = (u: Uint8Array) => btoa(String.fromCharCode(...u));
const fromB64 = (s: string) => Uint8Array.from(atob(s), c => c.charCodeAt(0));
const utf8Encode = (s: string | undefined) => new TextEncoder().encode(s);
const utf8Decode = (u: AllowSharedBufferSource | undefined) => new TextDecoder().decode(u);

// Derive an AES-GCM 256-bit key from a password and salt
export async function deriveKeyFromPassword(password: string, salt: Uint8Array, iterations = 200_000) {
const passKey = await crypto.subtle.importKey(
"raw",
utf8Encode(password),
{ name: "PBKDF2" },
false,
["deriveKey"]
);
return crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt,
iterations,
hash: "SHA-256"
},
passKey,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
}

// Encrypt plaintext (string) with password (string). Returns base64 strings.
export async function encryptWithPassword(password: string, plaintext: string) {
const salt = crypto.getRandomValues(new Uint8Array(16)); // 128-bit salt
const iv = crypto.getRandomValues(new Uint8Array(12)); // 96-bit IV for AES-GCM
const key = await deriveKeyFromPassword(password, salt);
const ct = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv, tagLength: 128 },
key,
utf8Encode(plaintext)
);
return {
ciphertext: b64(new Uint8Array(ct)),
iv: b64(iv),
salt: b64(salt),
iterations: 200_000,
algo: "AES-GCM"
};
}

// Decrypt using password and the stored base64 values
export async function decryptWithPassword(password: string, b64ciphertext: string, b64iv: string, b64salt: string, iterations: number) {
const salt = fromB64(b64salt);
const iv = fromB64(b64iv);
const ciphertext = fromB64(b64ciphertext);
const key = await deriveKeyFromPassword(password, salt, iterations);
const pt = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv, tagLength: 128 },
key,
ciphertext
);
return utf8Decode(new Uint8Array(pt));
}

export async function decryptFromCipherStructWithPassword(cipherStruct: any, password: string) {
return decryptWithPassword(password, cipherStruct.ciphertext, cipherStruct.iv, cipherStruct.salt, cipherStruct.iterations);
}

Он тестируется с помощью следующего фрагмента кода, что приводит к ошибке, упомянутой в заголовке (я использую node.js v20.19.2)
test("test encryption", async () => {
const encrypted = await encryptWithPassword("text", "password");
console.log(encrypted)
expect(encrypted).not.toBeNull();
const decrypted = await decryptFromCipherStructWithPassword(encrypted, "password");
expect(decrypted).toBe("text")
});


Подробнее здесь: https://stackoverflow.com/questions/798 ... job-failed
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»