如何导出加密密钥?
How to export CryptoKey?
我尝试导出 Web 加密中生成的密钥 API/SubtleCrypto。
当我执行 crypto.subtle.exportKey 时,我收到以下错误消息:
在 Chrome 中:
DOMException: key is not extractable (InvalidAccessError)
在 Firefox 中
A parameter or an operation is not supported by the underlying object (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"]
)
我尝试导出 Web 加密中生成的密钥 API/SubtleCrypto。
当我执行 crypto.subtle.exportKey 时,我收到以下错误消息: 在 Chrome 中:
DOMException: key is not extractable (InvalidAccessError)
在 Firefox 中
A parameter or an operation is not supported by the underlying object (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"]
)