2017-09-15 435 views
0

导入RSA密钥生成我通过jsbn RSA密钥:WebCrypto:由crypto.subtle.importKey(...)

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

而且我想通过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); 
    }); 

回答

0

您需要提供与base64url这是BASE64略有不同编码值的JWK关键。转换的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与承诺的工作,是异步。我改变

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

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

大。这对我有用。谢谢你的提示,我已经在使用“然后”功能。 – Ana

+0

嗨。如果我导入用于加密的公钥,这是有效的,你知道为什么它不适用于导入私钥进行解密吗? – Ana

+0

它应该以相同的方式工作。我回答了你的新问题。 – pedrofb