如何使用 WebCrypto 界面导入我的密钥



我的应用程序 密码学目前利用伪造库进行加密、解密、派生密钥和导入密钥。我最近开始阅读HTML5规范中新的加密功能,并希望做一个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 界面导入我的密钥?

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

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

最新更新