我尝试在Web密码API / SubtleCrypto中导出生成的密钥。

当我执行crypto.subtle.exportKey时,我收到以下错误消息:
在Chrome中:


  DOMException:密钥无法提取(InvalidAccessError)


并在Firefox中


  基础对象不支持参数或操作(InvalidAccessError)


cryptoTestObject = crypto.subtle.generateKey(
            {
                name: "AES-CBC",
                length: 256, //can be  128, 192, or 256
            },
            false, //whether the key is extractable (i.e. can be used in exportKey)
            ["encrypt", "decrypt"] //can "encrypt", "decrypt", "wrapKey", or "unwrapKey"
        )
        .then(function (key) {
            //returns a key object
            saveKeyInLocalStorage(keyName, key);
            console.log('CryptoPromise' + key);
        })
        .catch(function (err) {
            console.log(err);
        });

function saveKeyInLocalStorage(keyName, aesKey) {
    var exportPromise = crypto.subtle.exportKey('raw', aesKey);
    exportPromise.then(function (aesKey_RAW) {
        localStorage.setItem(keyName + 'key', aesKey_RAW);
        console.log("saved.");
    });
}


我如何生成可以原始格式导出的密钥。

最佳答案

您正在将可提取设置设置为false的情况下生成密钥。将其设置为true

crypto.subtle.generateKey(
    {
        name: "AES-CBC",
        length: 256
    },
    true, // <-- here
    ["encrypt", "decrypt"]
)

10-05 21:03