У меня есть следующий код, который должен зашифровать строку с паролем в 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
Операция не удалась по причине, специфичной для операции: сбой задания шифрования. ⇐ Javascript
Форум по Javascript
1763387007
Anonymous
У меня есть следующий код, который должен зашифровать строку с паролем в nodeJS. Вы можете найти пример здесь: https://jsfiddle.net/ujr4gev3/1/
Я также попробовал этот подход здесь: https://gist.github.com/chrisveness/43bcda93af9f646d083fad678071b90a, и это приводит к той же ошибке.
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")
});
Подробнее здесь: [url]https://stackoverflow.com/questions/79822363/the-operation-failed-for-an-operation-specific-reason-cipher-job-failed[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия