I m 试图加密档案,将其上载到云层,并用Node.js诉21.6.2在当地加以加密。 不幸的是,我遇到麻烦,难以使加密发挥作用。 能够产生关键和加密的Im,但脱轨在据称是ArrayBuffer的四处失败,但应当如此。 是否有更好的办法确保四舍五入为缓冲,以便我能够适当加密档案? 我已注意到,加密数据物体没有定义,我不敢确定这一问题。 没有人对我做错做什么有什么想法? 我发现的错误如下:
node:internal/webidl:181
const err = new TypeError(message);
^
TypeError: Failed to execute decrypt on SubtleCrypto : 3rd argument is not instance of ArrayBuffer, Buffer, TypedArray, or DataView.
at codedTypeError (node:internal/webidl:181:15)
at makeException (node:internal/webidl:190:10)
at converters.BufferSource (node:internal/crypto/webidl:206:11)
at SubtleCrypto.decrypt (node:internal/crypto/webcrypto:961:28)
at decrypt (/Users/me/code/encryptiontest/aes/aes.js:31:43)
at testEncryptionDecryption (/Users/me/code/encryptiontest/aes/aes.js:52:29) {
code: ERR_INVALID_ARG_TYPE
}
我的守则是:
const { subtle } = globalThis.crypto;
async function generateAesKey(length = 256) {
const key = await subtle.generateKey({
name: AES-CBC ,
length,
}, true, [ encrypt , decrypt ]);
return key;
}
async function aesEncrypt(plaintext) {
const ec = new TextEncoder();
const key = await generateAesKey();
const iv = crypto.getRandomValues(new Uint8Array(16));
const ciphertext = await crypto.subtle.encrypt({
name: AES-CBC ,
iv,
}, key, ec.encode(plaintext));
return {
key,
iv,
ciphertext,
};
}
async function decrypt(ciphertext, key, iv) {
const dec = new TextDecoder();
const plaintext = await crypto.subtle.decrypt({
name: AES-CBC ,
iv,
}, key, ciphertext);
return dec.decode(plaintext);
}
// takes Uint8Array and returns ArrayBuffer
function typedArrayToBuffer(array) {
return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset);
}
async function testEncryptionDecryption() {
const data = "Hello, world!";
console.log("ENCRYPTING DATA");
const { key, iv, encrypted } = await aesEncrypt(data);
console.log(iv);
console.log("DECRYPTING DATA");
console.log(typeof iv.buffer);
const decrypted = await decrypt(encrypted, key, typedArrayToBuffer(iv));
console.log("Original:", data);
console.log("Decrypted:", decrypted);
}
testEncryptionDecryption();
我利用四、四、四、四、四、四、四、五。 加密中的斜体,但我对四分五裂的错误不是ArrayBuffer、Buffer、PedArray或数据观察。