wip: migrate to node-forge

This commit is contained in:
Vladislav Hristov 2019-10-31 18:57:42 +02:00
parent 1c1f112ff5
commit 4149c01695
7 changed files with 384 additions and 38 deletions

View File

@ -25,7 +25,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(' ');
});
};

View File

@ -1,49 +1,219 @@
'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

@ -126,12 +126,15 @@ module.exports = (xml, keys) => ({
const type = lastChild(keyNodes[i].parentNode).textContent;
const modulus = xpath.select(".//*[local-name(.)='Modulus']", keyNodes[i])[0].textContent;
const exponent = xpath.select(".//*[local-name(.)='Exponent']", keyNodes[i])[0].textContent;
const modulusBuffer = Buffer.from(modulus, 'base64');
const mod = new BN(Buffer.from(modulus, 'base64'), 2).toBuffer('be', modulusBuffer.length);
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,
modulus,
exponent,
};
}
return bankKeys;

View File

@ -33,6 +33,7 @@
"handlebars": "^4.4.3",
"js2xmlparser": "^4.0.0",
"moment": "^2.24.0",
"node-forge": "^0.9.1",
"node-rsa": "^1.0.6",
"request": "^2.88.0",
"uuid": "^3.3.3",

44
test/exponentHandle.js Normal file
View File

@ -0,0 +1,44 @@
'use strict';
const { assert } = require('chai');
const H004Response = require('../lib/orders/H004/response');
describe('H004 response parsing', () => {
it('parses bank keys exp', () => {
const response = H004Response('<xml/>', {});
const x002mod = 'AJ2/0OoIZydb9sgKbiwqDcwA0NtcUMIYi6GK7PqoRszu1uytGnxJjQhGt62kMslWvLgebUSwdq/T3YyGsa3KQeIGaUUn9iqyu3BoNOMdo2DLN4NdGMY1WR/HbYRKR3JHyURhTBKw27KScRRdKGl6jY+VcXcTKJL8PjXMQH5cD6Gz'; // 'ALr6oSdqbbpRxlJmKtwTjjaCA1zlA61Vd7NfPML1NxY/U3Dt8galrieRjBM0SDn4vD2+AJCQY4zzkdE2m8u/p+3KGtmZtGaaxs11TNRm9GhtwQGw2hW73RduTSwLZJrSilv/GH18vPar8uvlBAXTmtVEy2kfvT3+t1mvqrut/LnUg3t63nx3WVdWylEdVDmf9Ylp+W+2quLyE0TzTVl5OXhvB3tpVs2B4OfsmOHJAaKIdSuXDMJebPiM9uIlraiJVeRMjkW3Xxmrazc7+kuy8RZ4BBgi+Xve6lNaQHGqxPV5q5SeXR5fS0D2sPeewJWbjhaVRBObIV2ZEoEWKx79pnE=';
const e002mod = 'AOzWaiT7aGESXcI3dqLY3RRD36inlZTGmNNprKd/t9uHfoMeLwZHeMwtjCRWjsuZEyBupkNSFWb3vBlxDyhcyTgpbbbcHsDGqF2zCJaK85xUphoH9mKHxbnA8ZlXzmtHwDmwVSns0FAslIqD+Xr+WycQpeCBEK12D8Ii032YS814ZUKHJ1MkS65A5PE0lcvMTyIE7ruG1kFz85F4nX8eWq77mDEiBONkA5RSUb5duGnRohdNYBgO8K6Wn18aDdISGDyPyXHNvC70v8tfWbF9VGE3rXVGcgjpezZZxC8d47vL0x6lOeslgl7s8N456ntAa+oGHRurt5mEhDz1DZg+EJc=';
const exponent = 'AQAB'; // 'AQAAAA8=';
response.orderData = () => `<?xml version="1.0" encoding="UTF-8"?>
<HPBResponseOrderData xmlns="urn:org:ebics:H004" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<AuthenticationPubKeyInfo>
<PubKeyValue>
<ds:RSAKeyValue>
<ds:Modulus>${x002mod}</ds:Modulus>
<ds:Exponent>${exponent}</ds:Exponent>
</ds:RSAKeyValue>
<TimeStamp>2015-02-25T08:01:13.061Z</TimeStamp>
</PubKeyValue>
<AuthenticationVersion>X002</AuthenticationVersion>
</AuthenticationPubKeyInfo>
<EncryptionPubKeyInfo>
<PubKeyValue>
<ds:RSAKeyValue>
<ds:Modulus>${e002mod}</ds:Modulus>
<ds:Exponent>${exponent}</ds:Exponent>
</ds:RSAKeyValue>
<TimeStamp>2015-02-25T08:01:12.344Z</TimeStamp>
</PubKeyValue>
<EncryptionVersion>E002</EncryptionVersion>
</EncryptionPubKeyInfo>
<HostID>SBKPR01</HostID>
</HPBResponseOrderData>`;
const bankKeys = response.bankKeys();
assert.equal(bankKeys.bankX002.mod.toString('base64'), x002mod);
assert.equal(bankKeys.bankE002.mod.toString('base64'), e002mod);
});
});

43
test/fixtures/keys.js vendored Normal file
View File

@ -0,0 +1,43 @@
'use strict';
const publicSmallExpPEM = '';
const publicSmallExpMod = '';
const publicSmallExpExp = '';
const publicBigPEM = `-----BEGIN PUBLIC KEY-----
MIIBJDANBgkqhkiG9w0BAQEFAAOCAREAMIIBDAKCAQEAuvqhJ2ptulHGUmYq3BOO
NoIDXOUDrVV3s188wvU3Fj9TcO3yBqWuJ5GMEzRIOfi8Pb4AkJBjjPOR0Taby7+n
7coa2Zm0ZprGzXVM1Gb0aG3BAbDaFbvdF25NLAtkmtKKW/8YfXy89qvy6+UEBdOa
1UTLaR+9Pf63Wa+qu638udSDe3refHdZV1bKUR1UOZ/1iWn5b7aq4vITRPNNWXk5
eG8He2lWzYHg5+yY4ckBooh1K5cMwl5s+Iz24iWtqIlV5EyORbdfGatrNzv6S7Lx
FngEGCL5e97qU1pAcarE9XmrlJ5dHl9LQPaw957AlZuOFpVEE5shXZkSgRYrHv2m
cQIFAQAAAA8=
-----END PUBLIC KEY-----`;
const publicBigModString = 'ALr6oSdqbbpRxlJmKtwTjjaCA1zlA61Vd7NfPML1NxY/U3Dt8galrieRjBM0SDn4vD2+AJCQY4zzkdE2m8u/p+3KGtmZtGaaxs11TNRm9GhtwQGw2hW73RduTSwLZJrSilv/GH18vPar8uvlBAXTmtVEy2kfvT3+t1mvqrut/LnUg3t63nx3WVdWylEdVDmf9Ylp+W+2quLyE0TzTVl5OXhvB3tpVs2B4OfsmOHJAaKIdSuXDMJebPiM9uIlraiJVeRMjkW3Xxmrazc7+kuy8RZ4BBgi+Xve6lNaQHGqxPV5q5SeXR5fS0D2sPeewJWbjhaVRBObIV2ZEoEWKx79pnE=';
const publicBigModBytes = [0, 186, 250, 161, 39, 106, 109, 186, 81, 198, 82, 102, 42, 220, 19, 142, 54, 130, 3, 92, 229, 3, 173, 85, 119, 179, 95, 60, 194, 245, 55, 22, 63, 83, 112, 237, 242, 6, 165, 174, 39, 145, 140, 19, 52, 72, 57, 248, 188, 61, 190, 0, 144, 144, 99, 140, 243, 145, 209, 54, 155, 203, 191, 167, 237, 202, 26, 217, 153, 180, 102, 154, 198, 205, 117, 76, 212, 102, 244, 104, 109, 193, 1, 176, 218, 21, 187, 221, 23, 110, 77, 44, 11, 100, 154, 210, 138, 91, 255, 24, 125, 124, 188, 246, 171, 242, 235, 229, 4, 5, 211, 154, 213, 68, 203, 105, 31, 189, 61, 254, 183, 89, 175, 170, 187, 173, 252, 185, 212, 131, 123, 122, 222, 124, 119, 89, 87, 86, 202, 81, 29, 84, 57, 159, 245, 137, 105, 249, 111, 182, 170, 226, 242, 19, 68, 243, 77, 89, 121, 57, 120, 111, 7, 123, 105, 86, 205, 129, 224, 231, 236, 152, 225, 201, 1, 162, 136, 117, 43, 151, 12, 194, 94, 108, 248, 140, 246, 226, 37, 173, 168, 137, 85, 228, 76, 142, 69, 183, 95, 25, 171, 107, 55, 59, 250, 75, 178, 241, 22, 120, 4, 24, 34, 249, 123, 222, 234, 83, 90, 64, 113, 170, 196, 245, 121, 171, 148, 158, 93, 30, 95, 75, 64, 246, 176, 247, 158, 192, 149, 155, 142, 22, 149, 68, 19, 155, 33, 93, 153, 18, 129, 22, 43, 30, 253, 166, 113];
const publicBigExpString = 'AQAAAA8=';
const publicBigExpBytes = [1, 0, 0, 0, 15];
const pblc = {
big: {
pem: publicBigPEM,
mod: {
bytes: publicBigModBytes,
string: publicBigModString,
},
exp: {
bytes: publicBigExpBytes,
string: publicBigExpString,
},
},
small: {
pem: publicSmallExpPEM,
mod: publicSmallExpMod,
exp: publicSmallExpExp,
},
};
module.exports = {
pblc,
};

86
test/keys.js Normal file
View File

@ -0,0 +1,86 @@
'use strict';
const { assert } = require('chai');
const fixtures = require('./fixtures/keys');
const Key = require('../lib/keymanagers/keyRSA');
const stripWhitespace = str => str.replace(/\s+/g, '');
describe('Keys management', () => {
describe('generates brand new', () => {
const keySize = 2048;
const newKey = Key().generate(keySize);
// newKey.key = Key().generate(keySize);
it('private key', () => {
assert.isTrue(newKey.isPrivate());
});
it('that has the right key size', () => {
// const newKeySize = newKey.size(); // console.log(newKey.size());
assert(newKey.size(), keySize);
});
});
describe('creates public key from mod and exp', () => {
const { pem, mod, exp } = fixtures.pblc.big;
describe('that are strings', () => {
const m = Buffer.from(mod.string, 'base64');
const e = Buffer.from(exp.string, 'base64');
const newKey = Key().importKey({
mod: m, exp: e, modulus: mod.string, exponent: exp.string,
});
it('and is really public', () => {
assert.isTrue(newKey.isPublic());
});
it('and has a propper mod in bytes', () => {
assert.deepEqual([...newKey.n()], mod.bytes);
});
it('and has a propper pem string', () => {
assert.equal(stripWhitespace(newKey.toPem()), stripWhitespace(pem));
});
});
describe('that are bytes', () => {
const m = Buffer.from(mod.bytes);
const e = Buffer.from(exp.bytes);
const newKey = Key().importKey({
mod: m, exp: e, modulus: mod.string, exponent: exp.string,
});
it('and is really public', () => {
assert.isTrue(newKey.isPublic());
});
it('and has a propper mod as a string', () => {
assert.equal(newKey.n().toString('base64'), mod.string);
});
it('and has a propper pem string', () => {
assert.equal(stripWhitespace(newKey.toPem()), stripWhitespace(pem));
});
});
});
describe('creates public key from pem string', () => {
const { pem, mod, exp } = fixtures.pblc.big;
const newKey = Key(pem);
it('and is really public', () => {
assert.isTrue(newKey.isPublic());
});
it('and has a propper(the same) pem string', () => {
newKey.pempem = {
modulus: mod.string,
exponent: exp.string,
};
assert.equal(stripWhitespace(newKey.toPem()), stripWhitespace(pem));
});
});
});