Merge pull request #16 from eCollect/feat/handle-unsual-exponent

Feat: handle unsual exponent migrate to node-forge
This commit is contained in:
Dimitar Nanov
2019-11-05 05:58:50 +02:00
committed by GitHub
10 changed files with 604 additions and 46 deletions

View File

@@ -13,10 +13,8 @@ const registerHelpers = () => {
handlebars.registerHelper('now', () => moment().format('HH:mm:ss'));
handlebars.registerHelper('keyExponentBits', k => Buffer.byteLength(k.e()) * 8);
// handlebars.registerHelper('keyExponentBits', k => Buffer.byteLength(new BN(k.key.keyPair.e).toBuffer()) * 8);
handlebars.registerHelper('keyModulusBits', k => k.key.getKeySize());
// return Buffer.byteLength(new BN(k.key.keyPair.e).toBuffer()) * 8;
handlebars.registerHelper('keyModulusBits', k => k.size());
handlebars.registerHelper('keyExponent', k => k.e('hex'));
@@ -24,8 +22,6 @@ const registerHelpers = () => {
handlebars.registerHelper('sha256', (k) => {
const digest = Buffer.from(Crypto.digestPublicKey(k), 'base64').toString('HEX');
// const digest = Buffer.from(k.publicDigest(), 'base64').toString('HEX');
return digest.toUpperCase().match(/.{1,2}/g).join(' ');
});
};

138
lib/keymanagers/Key.js Normal file
View File

@@ -0,0 +1,138 @@
'use strict';
const {
pki: {
rsa,
publicKeyToPem,
privateKeyToPem,
publicKeyFromPem,
privateKeyFromPem,
},
jsbn: {
BigInteger,
},
} = require('node-forge');
const getKeyType = (str) => {
const matches = str.match(/(PRIVATE|PUBLIC) KEY/);
if (!matches)
return null;
return matches[1].toLowerCase();
};
const keyFromPem = (pem) => {
const type = getKeyType(pem);
const isPublic = type === 'public';
const key = isPublic ? publicKeyFromPem(pem) : privateKeyFromPem(pem);
return {
isPublic,
key,
};
};
/**
* Creates a public key from modulus and exponent
* @param {Buffer} mod - the modulus
* @param {Buffer} exp - the exponent
*/
const keyFromModAndExp = (mod, exp) => {
const bnMod = new BigInteger(mod.toString('hex'), 16);
const bnExp = new BigInteger(exp.toString('hex'), 16);
return {
key: rsa.setPublicKey(bnMod, bnExp),
isPublic: true,
};
};
module.exports = class Key {
constructor({
pem = null, mod = null, exp = null, size = 2048,
} = {}) {
// generate new private key
if (!pem && !mod && !exp) {
const keyPair = rsa.generateKeyPair(size);
this.keyIsPublic = false;
this.privateKey = keyPair.privateKey;
this.publicKey = keyPair.publicKey;
return;
}
// new key from pem string
if (pem) {
const { key, isPublic } = keyFromPem(pem);
this.keyIsPublic = isPublic;
this.privateKey = isPublic ? null : key;
this.publicKey = isPublic ? key : null;
return;
}
// new key from mod and exp
if (mod && exp) {
const { key, isPublic } = keyFromModAndExp(mod, exp);
this.keyIsPublic = isPublic;
this.privateKey = isPublic ? null : key;
this.publicKey = isPublic ? key : null;
return;
}
// not good
throw new Error(`Can not create key without ${!mod ? 'modulus' : 'exponent'}.`);
}
static generate(size = 2048) {
return new Key({ size });
}
static importKey({ mod, exp }) {
return new Key({ mod, exp });
}
n(to = 'buff') {
const key = this.keyIsPublic ? this.publicKey : this.privateKey;
const keyN = Buffer.from(key.n.toByteArray());
return to === 'hex' ? keyN.toString('hex', 1) : keyN;
}
e(to = 'buff') {
const key = this.keyIsPublic ? this.publicKey : this.privateKey;
const eKey = Buffer.from(key.e.toByteArray());
return to === 'hex' ? eKey.toString('hex') : eKey;
}
d() {
if (this.keyIsPublic)
throw new Error('Can not get d component out of public key.');
return Buffer.from(this.privateKey.d.toByteArray());
}
isPrivate() {
return !this.keyIsPublic;
}
isPublic() {
return this.keyIsPublic;
}
// eslint-disable-next-line class-methods-use-this
size() {
const keyN = this.n('hex');
const bn = new BigInteger(keyN, 16);
return bn.bitLength();
}
toPem() {
return this.keyIsPublic ? publicKeyToPem(this.publicKey) : privateKeyToPem(this.privateKey);
}
};

View File

@@ -1,8 +1,14 @@
'use strict';
const Key = require('./keyRSA');
// const Key = require('./keyRSA');
const Key = require('./Key');
const keyOrNull = key => (key ? Key(key) : null);
const keyOrNull = (key) => {
if (key instanceof Key)
return key;
return key ? new Key({ pem: key }) : null;
};
module.exports = class Keys {
constructor({
@@ -25,15 +31,15 @@ module.exports = class Keys {
const keys = {};
Object.keys({ A006: '', X002: '', E002: '' }).forEach((key) => {
keys[key] = Key().generate();
keys[key] = Key.generate(); // Key().generate();
});
return new Keys(keys);
}
setBankKeys(bankKeys) {
this.keys.bankX002 = Key().importKey(bankKeys.bankX002);
this.keys.bankE002 = Key().importKey(bankKeys.bankE002);
this.keys.bankX002 = new Key(bankKeys.bankX002); // Key().importKey(bankKeys.bankX002);
this.keys.bankE002 = new Key(bankKeys.bankE002); // Key().importKey(bankKeys.bankE002);
}
a() {

59
lib/keymanagers/_Keys.js Normal file
View File

@@ -0,0 +1,59 @@
'use strict';
const Key = require('./keyRSA');
const keyOrNull = key => (key ? Key(key) : null);
module.exports = class Keys {
constructor({
A006,
E002,
X002,
bankX002,
bankE002,
}) {
this.keys = {
A006: keyOrNull(A006),
E002: keyOrNull(E002),
X002: keyOrNull(X002),
bankX002: keyOrNull(bankX002),
bankE002: keyOrNull(bankE002),
};
console.log('debug');
}
static generate() {
const keys = {};
Object.keys({ A006: '', X002: '', E002: '' }).forEach((key) => {
keys[key] = Key().generate();
});
return new Keys(keys);
}
setBankKeys(bankKeys) {
this.keys.bankX002 = Key().importKey(bankKeys.bankX002);
this.keys.bankE002 = Key().importKey(bankKeys.bankE002);
}
a() {
return this.keys.A006;
}
e() {
return this.keys.E002;
}
x() {
return this.keys.X002;
}
bankX() {
return this.keys.bankX002;
}
bankE() {
return this.keys.bankE002;
}
};

View File

@@ -1,49 +1,228 @@
'use strict';
/* eslint-disable camelcase */
function rsaPublicKeyPem(modulus_b64, exponent_b64) {
function prepadSigned(hexStr) {
const msb = hexStr[0];
if (
(msb >= '8' && msb <= '9') ||
(msb >= 'a' && msb <= 'f') ||
(msb >= 'A' && msb <= 'F'))
return `00${hexStr}`;
return hexStr;
}
function toHex(number) {
const nstr = number.toString(16);
if (nstr.length % 2 === 0) return nstr;
return `0${nstr}`;
}
// encode ASN.1 DER length field
// if <=127, short from
// if >=128, long from
function encodeLengthHex(n) {
if (n <= 127) return toHex(n);
const n_hex = toHex(n);
const length_of_length_byte = 128 + (n_hex.length / 2); // 0x80+numbytes
return toHex(length_of_length_byte) + n_hex;
}
const modulus = Buffer.from(modulus_b64, 'base64');
const exponent = Buffer.from(exponent_b64, 'base64');
let modulus_hex = modulus.toString('hex');
let exponent_hex = exponent.toString('hex');
modulus_hex = prepadSigned(modulus_hex);
exponent_hex = prepadSigned(exponent_hex);
const modlen = modulus_hex.length / 2;
const explen = exponent_hex.length / 2;
const encoded_modlen = encodeLengthHex(modlen);
const encoded_explen = encodeLengthHex(explen);
const encoded_pubkey = `30${
encodeLengthHex(modlen + explen + (encoded_modlen.length / 2) + (encoded_explen.length / 2) + 2)
}02${encoded_modlen}${modulus_hex
}02${encoded_explen}${exponent_hex}`;
let seq2 =
`${'30 0d ' +
'06 09 2a 86 48 86 f7 0d 01 01 01' +
'05 00 ' +
'03'}${encodeLengthHex((encoded_pubkey.length / 2) + 1)
}00${encoded_pubkey}`;
seq2 = seq2.replace(/ /g, '');
let der_hex = `30${encodeLengthHex(seq2.length / 2)}${seq2}`;
der_hex = der_hex.replace(/ /g, '');
const der = Buffer.from(der_hex, 'hex');
const der_b64 = der.toString('base64');
const pem = `-----BEGIN PUBLIC KEY-----\n${
der_b64.match(/.{1,64}/g).join('\n')
}\n-----END PUBLIC KEY-----\n`;
return pem.trim();
}
const BN = require('bn.js');
const NodeRSA = require('node-rsa');
const keyOrNull = (encodedKey) => {
if (encodedKey === null) return new NodeRSA();
const {
pki: {
rsa,
publicKeyToPem,
privateKeyToPem,
publicKeyFromPem,
privateKeyFromPem,
},
jsbn: {
BigInteger,
},
} = require('node-forge');
return (encodedKey instanceof NodeRSA) ? encodedKey : new NodeRSA(encodedKey);
const isKeyInstance = (obj) => {
if (typeof obj !== 'object')
return false;
return ('publicKey' in obj && 'privateKey' in obj);
};
module.exports = encodedKey => ({
key: keyOrNull(encodedKey),
const getKeyType = (str) => {
const matches = str.match(/(PRIVATE|PUBLIC) KEY/);
if (!matches)
return null;
return matches[1].toLowerCase();
};
generate(keySize = 2048) {
return new NodeRSA({ b: keySize });
},
/*
class RsaKeyPair {
constructor() {
this._isPublic = null;
this._publicKey = null;
this._privateKey = null;
}
fromString(str) {
importKey({ mod, exp }) {
this.key = new NodeRSA();
this.key.importKey({ n: mod, e: exp }, 'components-public');
}
}
*/
return this;
},
const keyOrNull = (encodedKey) => {
if (encodedKey === null) return {};
if (typeof encodedKey === 'string') {
const type = getKeyType(encodedKey);
const isPublic = type === 'public';
const key = isPublic ? publicKeyFromPem(encodedKey) : privateKeyFromPem(encodedKey);
key.isPublic = isPublic;
return key;
}
n(to = 'buff') {
const keyN = Buffer.from(this.key.exportKey('components-public').n);
return encodedKey;
// return (isKeyInstance(encodedKey)) ? encodedKey;
return to === 'hex'
? keyN.toString('hex', 1)
: keyN;
},
/* const k = (encodedKey instanceof NodeRSA) ? encodedKey : new NodeRSA(encodedKey);
if (k.keyPair.e === 16777216)
k.keyPair.e = 4294967311;
return k; */
};
e(to = 'buff') {
const eKey = new BN(this.key.exportKey('components-public').e).toBuffer();
module.exports = (encodedKey) => {
if (encodedKey && encodedKey.__RsaKey)
return encodedKey;
return {
__RsaKey: true,
key: keyOrNull(encodedKey),
return to === 'hex'
? eKey.toString('hex')
: eKey;
},
generate(keySize = 2048) {
const keyPair = rsa.generateKeyPair(keySize);
this.key = keyPair.privateKey;
this.key.isPublic = false;
this.publicKey = keyPair.publicKey;
return this;
// return rsa.generateKeyPair(keySize);
// return new NodeRSA({ b: keySize });
},
d() {
return this.key.keyPair.d.toBuffer();
},
importKey({
mod,
exp,
modulus,
exponent,
}) {
this.key = rsa.setPublicKey(new BigInteger(mod.toString('hex'), 16), new BigInteger(exp.toString('hex'), 16));
this.key.isPublic = true;
// const k = rsa.generateKeyPair();
// k.publicKey = rsa.setPublicKey(mod, exp);
// this.key = k;
// this.key.publicKey.
toPem() {
return this.key.isPrivate() ? this.key.exportKey('pkcs1-private-pem') : this.key.exportKey('pkcs8-public-pem');
},
});
// .this.key.importKey({ n: mod, e: exp }, 'components-public');
/*
this.pempem = modulus && exponent ? {
modulus,
exponent,
} : null;
*/
return this;
},
n(to = 'buff') {
const key = this.publicKey || this.key;
const keyN = Buffer.from(key.n.toByteArray());
return to === 'hex'
? keyN.toString('hex', 1)
: keyN;
},
e(to = 'buff') {
const key = this.publicKey || this.key;
const eKey = Buffer.from(key.e.toByteArray()); // new BN(this.key.exportKey('components-public').e).toBuffer();
return to === 'hex'
? eKey.toString('hex')
: eKey;
},
d() {
return Buffer.from(this.key.d.toByteArray());
// return this.key.keyPair.d.toBuffer();
},
isPrivate() {
return !this.key.isPublic;
},
isPublic() {
return this.key.isPublic;
// return this.key.isPublic();
},
size() {
return 2048;
// return this.key.getKeySize();
},
toPem() {
if (this.isPublic())
return publicKeyToPem(this.key);
return privateKeyToPem(this.key);
/*
if (this.pempem)
return rsaPublicKeyPem(this.pempem.modulus, this.pempem.exponent);
const isPrivate = this.key.isPrivate();
const pem = isPrivate ? this.key.exportKey('pkcs1-private-pem') : this.key.exportKey('pkcs8-public-pem');
return pem;
*/
},
};
};

View File

@@ -127,10 +127,12 @@ module.exports = (xml, keys) => ({
const modulus = xpath.select(".//*[local-name(.)='Modulus']", keyNodes[i])[0].textContent;
const exponent = xpath.select(".//*[local-name(.)='Exponent']", keyNodes[i])[0].textContent;
const mod = new BN(Buffer.from(modulus, 'base64'), 2).toBuffer();
const exp = new BN(Buffer.from(exponent, 'base64')).toNumber();
bankKeys[`bank${type}`] = { mod, exp };
const mod = Buffer.from(modulus, 'base64');
const exp = Buffer.from(exponent, 'base64');
bankKeys[`bank${type}`] = {
mod,
exp,
};
}
return bankKeys;