【问题标题】:WebCrypto: Importing rsa public key with modulus and exponent using crypto.subtle.importKeyWebCrypto:使用 crypto.subtle.importKey 导入具有模数和指数的 rsa 公钥
【发布时间】:2017-09-15 05:53:41
【问题描述】:

我通过 jsbn 生成了 rsa 密钥:

{
  "e": "10001",
  "n": "74a258004dd6c338b27688c1dd13d90da3269321d6dfa3cd8d7cfd7521453d0c5a9828bd507cfc6fe004ddcc09c498d2ceea8e05c214a63ab99d33c9060236f02d5f8bd1e7b334c7f74745948664aeba1a5addf7e7d76911ebf382852aabe86e06f83e0f7669be172380069547f542d8b0848b8bcf53e57c04d5e4163820ced3e4078418efe98df9f8c54c0cda66db3262f20b81464162c44216ca8b63c8f0cfe090dfe1d1950428ad6948204f3f44ba0648de44a9c44d44b91bd8f9ff7cccaceb9f20204f3ba1e228f13249fe04a7fc69cfe57d35e8897e16bc7872f585c909fec9b95a5240ab6589c3ebbe3ad614bfbdc966218daf9d9dddb39fdf6c0d3b49",
  ...}

“e”是指数,“n”是模数

我想使用crypto.subtle.importKey 导入它。

这是我发现的错误:

DOMException: JWK 成员“n”不能被 base64url 解码或包含填充

有人知道问题出在哪里吗?

看看下面我的代码。

var keyData = {
    kty: 'RSA',
    e: hexToBase64(rsaJson.e),
    n: hexToBase64(rsaJson.n),
    alg: 'RSA-OAEP-256',
    ext: true
};
 
var algo = {
    name: 'RSA-OAEP',
    hash: {name: 'SHA-256'}
};

var importedKey = crypto.subtle.importKey('jwk', keyData, algo, false, ['encrypt']).catch(function(err) {
         console.log(err);
     }); 

【问题讨论】:

    标签: encryption import key rsa webcrypto-api


    【解决方案1】:

    您需要提供一个 JWK 密钥,其值以 base64url 编码,这与 base64 略有不同。将hexToBase64的结果转换为base64url编码

    此代码将起作用

    var keyData = {
        kty: 'RSA',
        e: b64tob64u(hexToBase64(rsaJson.e)),
        n: b64tob64u(hexToBase64(rsaJson.n)),
        alg: 'RSA-OAEP-256',
        ext: true
    };
    
    var algo = {
        name: 'RSA-OAEP',
        hash: {name: 'SHA-256'}
    };
    
    crypto.subtle.importKey('jwk', keyData, algo, false, ['encrypt'])
    .then (function (importedKey){
        console.log(importedKey);
    }).catch(function(err) {
        console.log(err);
    }); 
    

    function b64tob64u(a){
        a=a.replace(/\=/g,"");
        a=a.replace(/\+/g,"-");
        a=a.replace(/\//g,"_");
        return a
    }
    

    另请注意,WebCryptographyApi 与 Promise 一起使用并且是异步的。我变了

    var importedKey = crypto.subtle.importKey(params...)
    

    crypto.subtle.importKey(params...).then (function (importedKey)
    

    【讨论】:

    • 太棒了。这对我有用。感谢您的留言,我已经在使用“then”功能了。
    • 嗨。如果我导入公钥进行加密,这会起作用,你知道为什么导入私钥进行解密不起作用吗?
    • 它应该以相同的方式工作。我回答了你的新问题。
    猜你喜欢
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2015-06-22
    • 2023-03-21
    • 2018-09-04
    • 2018-06-10
    • 2012-07-17
    • 2013-10-27
    相关资源
    最近更新 更多