如何使用WebCrypto界面导入密钥?

时间:2017-01-05 21:47:54

标签: javascript html5 google-chrome security encryption

我的应用程序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);
});

但这只是一个永远无法解决的承诺。然后我尝试使用'raw'类型导入我的密钥并将其传递给上面的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界面导入密钥?

1 个答案:

答案 0 :(得分:0)

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

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