源代码:https://github.com/HectorAnadon/Crypto-NodeJS-window.crypto
我正在使用 AES-128-GCM 将加密图片从 Node.js 服务器发送到 Service Worker(在 Web 浏览器后台运行的脚本),我试图在其中解密它。通信效果良好,因为网络浏览器中显示未加密的图片。
问题是:当我在服务 worker 中解密时,在 promise 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);
这是 Service Worker 中使用 window.crypto 的解密代码(此处的文档: 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);
});
});
}
最佳答案
如果我没记错的话,窗口对象在 ServiceWorker 中不可用,因此如果您尝试访问 window.crypto
,将会导致错误。
关于javascript - 在 Service-Worker 中使用 Crypto Node.js 加密并使用 window.crypto 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30733739/