【问题标题】:How do I import my key using the WebCrypto interface?如何使用 WebCrypto 界面导入我的密钥?
【发布时间】:2017-05-20 14:27:33
【问题描述】:

我的应用程序 Cryptography 目前使用forge 库进行加密、解密、派生密钥和导入密钥。我最近开始阅读有关 the new cryptographic features that are part of the HTML5 spec 的文章,并想做一个 POC,看看它是否可行以及对性能的影响。

该功能目前似乎无法使用。我什至无法导入我的任何密钥。

字节编码密钥"#a×iKº|UF?îçàÂ{ÙîµËËã-cØÊz"

B64 编码密钥"I2HXaUu6fFVGP4fu5+CJwh57HtnutcvL4y0XY9icyno="

无符号 8 位整数数组密钥表示[35, 97, 215, 105, 75, 186, 124, 85, 70, 63, 135, 238, 231, 224, 137, 194, 30, 123, 30, 217, 238, 181, 203, 203, 227, 45, 23, 99, 216, 156, 202, 122]

我尝试使用JWK 导入我的密钥:

window.crypto.subtle.importKey(
    "jwk", //can be "jwk" or "raw"
    {   //this is an example jwk key, "raw" would be an ArrayBuffer
        kty: "oct",
        k: "I2HXaUu6fFVGP4fu5+CJwh57HtnutcvL4y0XY9icyno=",
        alg: "A256GCM",
        ext: true,
    },
    {   //this is the algorithm options
        name: "AES-GCM",
    },
    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 the symmetric key
    console.log(key);
})
.catch(function(err){
    console.error(err);
});

但这只会导致永远不会解决的承诺。然后我尝试使用“原始”类型导入我的密钥并将其传递给上面的 arrayBuffer:

window.crypto.subtle.importKey(
    "raw", //can be "jwk" or "raw"
    arrayBuffer,
    {   //this is the algorithm options
        name: "AES-GCM",
    },
    true, //whether the key is extractable (i.e. can be used in exportKey)
    ["encrypt", "decrypt"] //can "encrypt", "decrypt", "wrapKey", or "unwrapKey"
)
.then(function(key){
    //returns the symmetric key
    console.log(key);
})
.catch(function(err){
    console.error(err);
});

但这也只会导致一个永远不会解决的承诺。

如何使用WebCrypto 接口导入我的密钥?

【问题讨论】:

  • 请注意,对于 raw 输入是 ArrayBuffer,并且该对象有关于如何创建它的描述。否则,您可以使用 this answer 为 raw 创建一个数组。

标签: javascript html google-chrome security encryption


【解决方案1】:

您的 base64 编码是正确的,但是 JWK 需要使用 base64url。在该编码中,密钥变为:I2HXaUu6fFVGP4fu5-CJwh57HtnutcvL4y0XY9icyno

当我将k 更改为该值时,我可以成功导入您的密钥。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2018-12-04
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多