💯 RSA tools. Lightweight. Zero Dependencies. Great tests. Universal compatibility.
rsa
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

51 lines
1.4 KiB

'use strict';
/*global Promise*/
var PEM = require('./pem.js');
var x509 = require('./x509.js');
var ASN1 = require('./asn1.js');
// Hacky-do, wrappy-do
module.exports.generate = function (opts) {
if (!opts) { opts = {}; }
return new Promise(function (resolve, reject) {
try {
var modlen = opts.modulusLength || 2048;
var exp = opts.publicExponent || 0x10001;
var pair = require('./generate-privkey.js')(modlen,exp);
if (pair.private) { resolve(pair); return; }
pair = toJwks(pair);
resolve({ private: pair.private , public: pair.public });
} catch(e) {
reject(e);
}
});
};
// PKCS1 to JWK only
function toJwks(oldpair) {
var block = PEM.parseBlock(oldpair.privateKeyPem);
var asn1 = ASN1.parse(block.bytes);
var jwk = { kty: 'RSA', n: null, e: null };
jwk = x509.parsePkcs1(block.bytes, asn1, jwk);
return { private: jwk, public: neuter(jwk) };
}
// Copied from rsa.js to prevent circular dep
var privates = [ 'p', 'q', 'd', 'dp', 'dq', 'qi' ];
function neuter(priv) {
var pub = {};
Object.keys(priv).forEach(function (key) {
if (!privates.includes(key)) {
pub[key] = priv[key];
}
});
return pub;
}
if (require.main === module) {
module.exports.generate().then(function (pair) {
console.info(JSON.stringify(pair.private, null, 2));
console.info(JSON.stringify(pair.public, null, 2));
});
}