如何导出CryptoKey?

时间:2016-06-30 09:48:13

标签: javascript html5 encryption aes

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

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

  

DOMException:key不可提取(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.");
    });
}

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

1 个答案:

答案 0 :(得分:1)

您可以将可摘设置设置为false来生成密钥。将其设置为true而不是:

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