Javascript 使用WebCryptoAPI包装和打开密钥
我正在使用Javascript 使用WebCryptoAPI包装和打开密钥,javascript,encryption,webcrypto-api,Javascript,Encryption,Webcrypto Api,我正在使用webcryptoapi在客户端进行一些加密工作。 虽然我无法包装和展开关键帧,但浏览器始终返回以下错误 DOMException [OperationError: "The operation failed for an operation-specific reason" 你和我不能处理这个错误,所以我粘贴了我的代码 function wrapPrivateKey(privateKey, wrappingKey) { var iv = window.crypto.getR
webcryptoapi
在客户端进行一些加密工作。
虽然我无法包装和展开关键帧,但浏览器始终返回以下错误
DOMException [OperationError: "The operation failed for an operation-specific reason"
你和我不能处理这个错误,所以我粘贴了我的代码
function wrapPrivateKey(privateKey, wrappingKey) {
var iv = window.crypto.getRandomValues(new Uint8Array(12));
return window.crypto.subtle.wrapKey(
"jwk",
privateKey,
wrappingKey,
{
name: "AES-GCM",
length: 256,
iv: iv,
}
)
.then(function (key) {
return {
"key": StringToB64(arrayBufferToString(key)),
"iv": StringToB64(arrayBufferToString(iv))
};
})
.catch(function (err) {
console.error(err);
return false;
});
}
function unwrapPrivateKey(wrappedPrivateKey, unwrappingKey) {
var obj = JSON.parse(B64ToString(wrappedPrivateKey));
var key = stringToArrayBuffer(B64ToString(obj["key"]));
var iv = stringToArrayBuffer(B64ToString(obj["iv"]));
return window.crypto.subtle.unwrapKey(
"jwk",
key,
unwrappingKey,
{
name: "AES-GCM",
length: 256,
iv: iv,
},
{
name: "RSA-OAEP",
hash: {name: "SHA-256"},
},
true,
["encrypt", "decrypt"]
)
.then(function (key) {
return key;
})
.catch(function (err) {
console.error(err);
return false;
});
}
我不知道问题是否与将键对象转换为字符串有关。不幸的是,我需要将其转换为字符串以将其保存在数据库中。这里是密钥包装/展开的简单示例。此代码在Chrome/Mozilla中工作
const rsaAlg = {
name: "RSA-OAEP",
hash: "SHA-256",
publicExponent: new Uint8Array([1, 0, 1]),
modulusLength: 2048
};
const aesAlg = {
name: "AES-GCM",
length: 256,
iv: crypto.getRandomValues(new Uint8Array(12)),
};
crypto.subtle.generateKey(rsaAlg, true, ["encrypt", "decrypt"])
.then((rsaKeys) => {
return crypto.subtle.generateKey(aesAlg, true, ["encrypt", "decrypt", "wrapKey", "unwrapKey"])
.then((aesKey) => {
return crypto.subtle.wrapKey("jwk", rsaKeys.privateKey, aesKey, aesAlg)
.then((wrappedKey) => {
console.log(wrappedKey); // ArrayBuffer
// Unwrap key
return crypto.subtle.unwrapKey("jwk", wrappedKey, aesKey, aesAlg, rsaAlg, true, ["decrypt"])
})
.then((unwrappedKey) => {
console.log(unwrappedKey);
})
})
})
.catch((err) => {
console.error(err);
})
webcryptoapi在不同的浏览器中是不同的。最好使用一些可以修复它的模块
我还看到您使用了
var key=stringToArrayBuffer(B64ToString(obj[“key”])代码>。但密钥必须是加密密钥
。如果您拥有对称密钥的原始版本,则必须使用importKey
函数通过WebCryptoAPI从raw
创建CryptoKey
,这一点很重要,您还需要显示浏览器版本,因为支持度最低。我确实看到您尝试在一行中执行所有操作:将该行拆分,至少找出哪种方法是罪魁祸首。这是基本的调试。