node-ebics-client/packages/ebics-client/lib/keymanagers/keyRSA.js

50 lines
1.0 KiB
JavaScript
Raw Normal View History

'use strict';
const BN = require('bn.js');
const NodeRSA = require('node-rsa');
2018-06-20 09:20:03 +00:00
const keyOrNull = (encodedKey) => {
if (encodedKey === null) return new NodeRSA();
2018-06-20 09:20:03 +00:00
return (encodedKey instanceof NodeRSA) ? encodedKey : new NodeRSA(encodedKey);
};
2018-06-20 09:20:03 +00:00
module.exports = encodedKey => ({
key: keyOrNull(encodedKey),
2018-06-20 09:20:03 +00:00
generate(keySize = 2048) {
return new NodeRSA({ b: keySize });
},
2018-06-20 09:20:03 +00:00
importKey({ mod, exp }) {
this.key = new NodeRSA();
2018-06-20 09:20:03 +00:00
this.key.importKey({ n: mod, e: exp }, 'components-public');
return this;
2018-06-20 09:20:03 +00:00
},
n(to = 'buff') {
const keyN = Buffer.from(this.key.exportKey('components-public').n);
return to === 'hex'
? keyN.toString('hex', 1)
: keyN;
2018-06-20 09:20:03 +00:00
},
e(to = 'buff') {
const eKey = new BN(this.key.exportKey('components-public').e).toBuffer();
return to === 'hex'
? eKey.toString('hex')
: eKey;
2018-06-20 09:20:03 +00:00
},
d() {
return this.key.keyPair.d.toBuffer();
2018-06-20 09:20:03 +00:00
},
toPem() {
return this.key.isPrivate() ? this.key.exportKey('pkcs1-private-pem') : this.key.exportKey('pkcs8-public-pem');
2018-06-20 09:20:03 +00:00
},
});