源代码:https ://github.com/HectorAnadon/Crypto-NodeJS-window.crypto
我正在使用 AES-128-GCM 将加密图片从 node.js 服务器发送到我试图解密它的服务工作者(在 Web 浏览器背景中运行的脚本)。通信效果很好,因为未加密的图片显示在网络浏览器中。
问题是:当我在服务工作者中解密时,在承诺 cryptoSubtle.decrypt 中,我得到一个异常,这是控制台为我打印的内容:解密错误:OperationError:(匿名函数)@ service_worker.js:310
service_worker.js 中的第 310 行是:console.error("解密错误:" + err); //第310行
你知道我做错了什么吗?非常感谢,我真的很感激。
这是使用 Crypto Node.js 的加密代码(此处的文档:https ://nodejs.org/api/crypto.html )
// Nodejs encryption with GCM
// Does not work with nodejs v0.10.31
var fs = require('fs');
var crypto = require('crypto');
var algorithm = 'aes-128-gcm';
var key = '3zTvzr3p67VC61jm';
// generate a new iv for each encryption
// As this is for testing I always use the same iv
var iv = '60iP0h6vJoEa';
function encrypt(text) {
var cipher = crypto.createCipheriv(algorithm, key, iv)
var encrypted = cipher.update(text);
return encrypted;
}
var text = fs.readFileSync('mustang_encrypted.jpg');
var hw = encrypt(text);
这是使用 window.crypto 的 Service Worker 中的解密代码(此处的文档:https ://developer.mozilla.org/en-US/docs/Web/API/Window/crypto )
//ArrayBuffer of the data we received
function(bodyArrayBuffer) {
var cryptoObj = crypto;
var cryptoSubtle = cryptoObj.subtle;
/*
* IMPORT KEY
*/
string2ArrayBuffer("3zTvzr3p67VC61jm", function (keyBuffer) {
console.log("keyBuffer length: " + keyBuffer.byteLength);
cryptoSubtle.importKey(
"raw", //can be "jwk" or "raw"
keyBuffer,
{ //this is the algorithm options
name: "AES-GCM",
},
false, //whether the key is extractable (i.e. can be used in exportKey)
["encrypt", "decrypt"] //can be any combination of "encrypt" and "decrypt"
).then(function(key){
//returns the symmetric key
/*
* DECRYPTION
*/
string2ArrayBuffer("60iP0h6vJoEa",function (myIV) {
cryptoSubtle.decrypt(
{
name: "AES-GCM",
iv: myIV, //The initialization vector you used to encrypt
tagLength: 128, //The tagLength you used to encrypt
},
key, //from generateKey or importKey above
bodyArrayBuffer //ArrayBuffer of the data
)
.then(function(decrypted){
//returns an ArrayBuffer containing the decrypted data
console.log(new Uint8Array(decrypted));
//send response
var newResponse = new Response(decrypted, init);
console.log("Returning \"decrypted\" response!");
accept(newResponse);
})
.catch(function(err){
console.error("Decryption error: " + err); //Line 310
});
});
})
.catch(function(err){
console.error(err);
});
});
}