WebCrypto:使用 crypto.subtle.importKey 导入带有模数和指数的 rsa public 密钥

WebCrypto: Importing rsa public key with modulus and exponent using crypto.subtle.importKey

我通过jsbn生成了rsa密钥:

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

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

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

这是我发现的错误:

DOMException: The JWK member "n" could not be base64url decoded or contained padding

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

看下面我的代码。

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);
     }); 

您需要提供一个 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 使用 promises 并且是异步的。我改变了

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

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