diff --git a/fabric-ca-client/lib/FabricCAClientImpl.js b/fabric-ca-client/lib/FabricCAClientImpl.js index 1367de7497..48ea61a251 100644 --- a/fabric-ca-client/lib/FabricCAClientImpl.js +++ b/fabric-ca-client/lib/FabricCAClientImpl.js @@ -944,8 +944,8 @@ var FabricCAClient = class { //Then we simply base64 decode it and convert to hex string var contents = pem.toString().trim().split(/\r?\n/); //check for BEGIN and END tags - if (!(contents[0].match(/\-\-\-\-\-\s*BEGIN ?([^-]+)?\-\-\-\-\-/) && - contents[contents.length - 1].match(/\-\-\-\-\-\s*END ?([^-]+)?\-\-\-\-\-/))) { + if (!(contents[0].match(/-----\s*BEGIN ?([^-]+)?-----/) && + contents[contents.length - 1].match(/-----\s*END ?([^-]+)?-----/))) { throw new Error('Input parameter does not appear to be PEM-encoded.'); }; contents.shift(); //remove BEGIN diff --git a/fabric-client/lib/impl/CouchDBKeyValueStore.js b/fabric-client/lib/impl/CouchDBKeyValueStore.js index 291a91f863..8afce52e82 100644 --- a/fabric-client/lib/impl/CouchDBKeyValueStore.js +++ b/fabric-client/lib/impl/CouchDBKeyValueStore.js @@ -17,8 +17,6 @@ 'use strict'; var api = require('../api.js'); -var fs = require('fs-extra'); -var path = require('path'); var util = require('util'); var utils = require('../utils'); var nano = require('nano'); @@ -68,14 +66,14 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { // Initialize the CouchDB database client var dbClient = nano(self._url); // Check if the database already exists. If not, create it. - dbClient.db.get(self._name, function (err, body) { + dbClient.db.get(self._name, function (err) { // Check for error if (err) { // Database doesn't exist if (err.error == 'not_found') { logger.debug('No %s found, creating %s', self._name, self._name); - dbClient.db.create(self._name, function (err, body) { + dbClient.db.create(self._name, function (err) { if (err) { return reject(new Error(util.format('Failed to create %s database due to error: %s', self._name, err.stack ? err.stack : err))); } @@ -166,7 +164,7 @@ var CouchDBKeyValueStore = class extends api.KeyValueStore { logger.debug('setValue, _dbInsert', { options: options }); var self = this; return new Promise(function (resolve, reject) { - self._database.insert(options, function (err, body, header) { + self._database.insert(options, function (err) { if (err) { logger.error('setValue, _dbInsert, ERROR: [%s.insert] - ', self._name, err.error); reject(new Error(err.error)); diff --git a/fabric-client/lib/impl/CryptoKeyStore.js b/fabric-client/lib/impl/CryptoKeyStore.js index a5cc1146f1..181c416666 100644 --- a/fabric-client/lib/impl/CryptoKeyStore.js +++ b/fabric-client/lib/impl/CryptoKeyStore.js @@ -19,7 +19,6 @@ var jsrsasign = require('jsrsasign'); var KEYUTIL = jsrsasign.KEYUTIL; -var api = require('../api.js'); var utils = require('../utils.js'); var ECDSAKey = require('./ecdsa/key.js'); @@ -31,44 +30,40 @@ var logger = utils.getLogger('CryptoKeyStore.js'); * with the getKey() and putKey() methods */ var CryptoKeyStoreMixin = (KeyValueStore) => class extends KeyValueStore { - constructor(options) { - return super(options); - } - getKey(ski) { var self = this; // first try the private key entry, since it encapsulates both // the private key and public key return this.getValue(_getKeyIndex(ski, true)) - .then((raw) => { - if (raw !== null) { - var privKey = KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(raw); - // TODO: for now assuming ECDSA keys only, need to add support for RSA keys - return new ECDSAKey(privKey); - } - - // didn't find the private key entry matching the SKI - // next try the public key entry - return self.getValue(_getKeyIndex(ski, false)); - }).then((key) => { - if (ECDSAKey.isInstance(key)) - return key; - - if (key !== null) { - var pubKey = KEYUTIL.getKey(key); - return new ECDSAKey(pubKey); - } - }); + .then((raw) => { + if (raw !== null) { + var privKey = KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(raw); + // TODO: for now assuming ECDSA keys only, need to add support for RSA keys + return new ECDSAKey(privKey); + } + + // didn't find the private key entry matching the SKI + // next try the public key entry + return self.getValue(_getKeyIndex(ski, false)); + }).then((key) => { + if (ECDSAKey.isInstance(key)) + return key; + + if (key !== null) { + var pubKey = KEYUTIL.getKey(key); + return new ECDSAKey(pubKey); + } + }); } putKey(key) { var idx = _getKeyIndex(key.getSKI(), key.isPrivate()); var pem = key.toBytes(); return this.setValue(idx, pem) - .then(() => { - return key; - }); + .then(() => { + return key; + }); } }; diff --git a/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js b/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js index f7f310a57e..92d51adda0 100755 --- a/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js +++ b/fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js @@ -19,7 +19,6 @@ // requires var api = require('../api.js'); -var crypto = require('crypto'); var elliptic = require('elliptic'); var EC = elliptic.ec; var jsrsa = require('jsrsasign'); @@ -50,7 +49,7 @@ var CryptoSuite_ECDSA_AES = class extends api.CryptoSuite { * @param {string} hash Optional. Hash algorithm, supported values are "SHA2" and "SHA3" */ constructor(keySize, hash) { - logger.debug('constructor, keySize: '+keySize); + logger.debug('constructor, keySize: ' + keySize); super(); if (keySize !== 256 && keySize !== 384) { @@ -137,28 +136,34 @@ var CryptoSuite_ECDSA_AES = class extends api.CryptoSuite { var self = this; return new Promise((resolve, reject) => { self._cryptoKeyStore._getKeyStore() - .then ((store) => { - logger.debug('generateKey, store.setValue'); - return store.putKey(key) - .then(() => { - return resolve(key); - }).catch((err) => { - reject(err); - }); - }); + .then((store) => { + logger.debug('generateKey, store.setValue'); + return store.putKey(key) + .then(() => { + return resolve(key); + }).catch((err) => { + reject(err); + }); + }); }); } } /** + * This is an implementation of {@link module:api.CryptoSuite#deriveKey} * To be implemented */ deriveKey(key, opts) { + if (key || opts); throw new Error('Not implemented yet'); } - importKey(raw, opts) { + /** + * This is an implementation of {@link module:api.CryptoSuite#importKey} + * To be implemented + */ + importKey(pem, opts) { logger.debug('importKey - start'); var store_key = true; //default if (typeof opts !== 'undefined' && typeof opts.ephemeral !== 'undefined' && opts.ephemeral === true) { @@ -177,40 +182,40 @@ var CryptoSuite_ECDSA_AES = class extends api.CryptoSuite { // TODO: add support for the following passcode-protected PEM formats // - PKCS#5 encrypted PEM RSA/DSA private // - PKCS#8 encrypted PEM RSA/ECDSA private key - var pemString = Buffer.from(raw).toString(); + var pemString = Buffer.from(pem).toString(); pemString = makeRealPem(pemString); var key = null; var theKey = null; var error = null; try { key = KEYUTIL.getKey(pemString); - } catch(err) { + } catch (err) { error = new Error('Failed to parse key from PEM: ' + err); } if (key && key.type && key.type === 'EC') { theKey = new ECDSAKey(key); - logger.debug('importKey - have the key %j',theKey); + logger.debug('importKey - have the key %j', theKey); } else { error = new Error('Does not understand PEM contents other than ECDSA private keys and certificates'); } - if(!store_key) { - if(error) { - logger.error('importKey - %s',error); + if (!store_key) { + if (error) { + logger.error('importKey - %s', error); throw error; } return theKey; } else { - if(error) { - logger.error('importKey - %j',error); + if (error) { + logger.error('importKey - %j', error); return Promise.reject(error); } return new Promise((resolve, reject) => { return self._cryptoKeyStore._getKeyStore() - .then ((store) => { + .then((store) => { return store.putKey(theKey); }).then(() => { return resolve(theKey); @@ -231,28 +236,38 @@ var CryptoSuite_ECDSA_AES = class extends api.CryptoSuite { } return new Promise((resolve, reject) => { self._cryptoKeyStore._getKeyStore() - .then ((st) => { - store = st; - return store.getKey(ski); - }).then((key) => { - if (ECDSAKey.isInstance(key)) - return resolve(key); - - if (key !== null) { - var pubKey = KEYUTIL.getKey(key); - return resolve(new ECDSAKey(pubKey)); } - }).catch((err) => { - reject(err); - }); + .then((st) => { + store = st; + return store.getKey(ski); + }).then((key) => { + if (ECDSAKey.isInstance(key)) + return resolve(key); + + if (key !== null) { + var pubKey = KEYUTIL.getKey(key); + return resolve(new ECDSAKey(pubKey)); + } + }).catch((err) => { + reject(err); + }); }); } + /** + * This is an implementation of {@link module:api.CryptoSuite#hash} + * The opts argument is not supported. + */ hash(msg, opts) { + if (opts); return this._hashFunction(msg); } - sign(key, digest, opts) { + /** + * This is an implementation of {@link module:api.CryptoSuite#sign} + * Signs digest using key k. + */ + sign(key, digest) { if (typeof key === 'undefined' || key === null) { throw new Error('A valid key is required to sign'); } @@ -294,16 +309,20 @@ var CryptoSuite_ECDSA_AES = class extends api.CryptoSuite { } /** + * This is an implementation of {@link module:api.CryptoSuite#encrypt} * To be implemented. */ - encrypt(key, plaintext, opts) { + encrypt(key, plainText, opts) { + if (key || plainText || opts); throw new Error('Not implemented yet'); } /** + * This is an implementation of {@link module:api.CryptoSuite#decrypt} * To be implemented. */ decrypt(key, cipherText, opts) { + if (key || cipherText || opts); throw new Error('Not implemented yet'); } }; @@ -327,7 +346,7 @@ const halfOrdersForCurve = { function _preventMalleability(sig, curveParams) { var halfOrder = halfOrdersForCurve[curveParams.name]; if (!halfOrder) { - throw new Error('Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curve); + throw new Error('Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curveParams.name); } // in order to guarantee 's' falls in the lower range of the order, as explained in the above link, @@ -344,7 +363,7 @@ function _preventMalleability(sig, curveParams) { function _checkMalleability(sig, curveParams) { var halfOrder = halfOrdersForCurve[curveParams.name]; if (!halfOrder) { - throw new Error('Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curve); + throw new Error('Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curveParams.name); } // first need to unmarshall the signature bytes into the object with r and s values @@ -365,7 +384,7 @@ function _checkMalleability(sig, curveParams) { // Utilitly method to make sure the start and end markers are correct function makeRealPem(pem) { var result = null; - if(typeof pem == 'string') { + if (typeof pem == 'string') { result = pem.replace(/-----BEGIN -----/, '-----BEGIN CERTIFICATE-----'); result = result.replace(/-----END -----/, '-----END CERTIFICATE-----'); result = result.replace(/-----([^-]+) ECDSA ([^-]+)-----([^-]*)-----([^-]+) ECDSA ([^-]+)-----/, '-----$1 EC $2-----$3-----$4 EC $5-----'); @@ -373,30 +392,4 @@ function makeRealPem(pem) { return result; } - -/* - * Convert a PEM encoded certificate to DER format - * @param {string) pem PEM encoded public or private key - * @returns {string} hex Hex-encoded DER bytes - * @throws Will throw an error if the conversation fails - */ -function pemToDER(pem) { - - //PEM format is essentially a nicely formatted base64 representation of DER encoding - //So we need to strip "BEGIN" / "END" header/footer and string line breaks - //Then we simply base64 decode it and convert to hex string - var contents = pem.toString().trim().split(/\r?\n/); - //check for BEGIN and END tags - if (!(contents[0].match(/\-\-\-\-\-\s*BEGIN ?([^-]+)?\-\-\-\-\-/) && - contents[contents.length - 1].match(/\-\-\-\-\-\s*END ?([^-]+)?\-\-\-\-\-/))) { - throw new Error('Input parameter does not appear to be PEM-encoded.'); - }; - contents.shift(); //remove BEGIN - contents.pop(); //remove END - //base64 decode and encode as hex string - var hex = Buffer.from(contents.join(''), 'base64').toString('hex'); - return hex; -} - - module.exports = CryptoSuite_ECDSA_AES; diff --git a/fabric-client/lib/impl/NetworkConfig_1_0.js b/fabric-client/lib/impl/NetworkConfig_1_0.js index 9d5a9ef1cc..7c8abcb3cf 100644 --- a/fabric-client/lib/impl/NetworkConfig_1_0.js +++ b/fabric-client/lib/impl/NetworkConfig_1_0.js @@ -18,7 +18,6 @@ var fs = require('fs-extra'); var path = require('path'); -var util = require('util'); var utils = require('../utils'); var Constants = require('../Constants.js'); var Channel = require('../Channel.js'); diff --git a/fabric-client/lib/impl/bccsp_pkcs11.js b/fabric-client/lib/impl/bccsp_pkcs11.js index 5f95f66a62..0455176851 100644 --- a/fabric-client/lib/impl/bccsp_pkcs11.js +++ b/fabric-client/lib/impl/bccsp_pkcs11.js @@ -62,7 +62,7 @@ function _preventMalleability(sig, curve) { /* * Function name and line number for logger. */ -var __func = function() { +var __func = function () { // 0 is __func itself, 1 is caller of __func return callsite()[1].getFunctionName() + '[' + callsite()[1].getLineNumber() + ']: '; @@ -124,13 +124,12 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { throw new Error(__func() + 'keySize must be specified'); if (typeof keySize === 'string') keySize = parseInt(keySize, 10); if (keySize != 256 && keySize != 384) - throw new Error(__func() + - 'only 256 or 384 bits key sizes are supported'); + throw new Error(__func() + 'only 256 or 384 bits key sizes are supported'); logger.debug(__func() + 'keySize: ' + keySize); /* * If no lib specified, get it from env var or config file. */ - var pkcs11Lib = opts? opts.lib : null; + var pkcs11Lib = opts ? opts.lib : null; if (typeof pkcs11Lib === 'undefined' || pkcs11Lib === null) pkcs11Lib = utils.getConfigSetting('crypto-pkcs11-lib'); if (typeof pkcs11Lib === 'undefined' || pkcs11Lib === null || @@ -153,26 +152,26 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { * If no user type is specified, check env var or config file, then * default to 1 (pkcs11js.CKU_USER) */ - var pkcs11UserType = opts ? opts.usertype: null; + var pkcs11UserType = opts ? opts.usertype : null; if (typeof pkcs11UserType === 'undefined' || pkcs11UserType === null) pkcs11UserType = utils.getConfigSetting('crypto-pkcs11-usertype', 1); if (typeof pkcs11UserType === 'string') { pkcs11UserType = Number.parseInt(pkcs11UserType); } - if(!Number.isInteger(pkcs11UserType)) { + if (!Number.isInteger(pkcs11UserType)) { throw new Error(__func() + 'PKCS11 usertype number invalid'); } /* * If no read write specified, check env var or config file, then * default to true */ - var pkcs11ReadWrite = opts ? opts.readwrite: null; + var pkcs11ReadWrite = opts ? opts.readwrite : null; if (typeof pkcs11ReadWrite === 'undefined' || pkcs11ReadWrite === null) pkcs11ReadWrite = utils.getConfigSetting('crypto-pkcs11-readwrite', true); if (typeof pkcs11ReadWrite === 'string') { - if(pkcs11ReadWrite.toLowerCase() === 'true') { + if (pkcs11ReadWrite.toLowerCase() === 'true') { pkcs11ReadWrite = true; - } else if(pkcs11ReadWrite.toLowerCase() === 'false') { + } else if (pkcs11ReadWrite.toLowerCase() === 'false') { pkcs11ReadWrite = false; } else { throw new Error(__func() + 'PKCS11 readwrite setting must be "true" or "false"'); @@ -184,7 +183,7 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { /* * If no pin specified, get it from env var or config file. */ - var pkcs11Pin = opts ? opts.pin: null; + var pkcs11Pin = opts ? opts.pin : null; if (typeof pkcs11Pin === 'undefined' || pkcs11Pin === null) pkcs11Pin = utils.getConfigSetting('crypto-pkcs11-pin'); if (typeof pkcs11Pin === 'undefined' || pkcs11Pin === null || @@ -295,7 +294,7 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { try { // Getting info about PKCS11 Module logger.debug(__func() + 'C_GetInfo: ' + - util.inspect(pkcs11.C_GetInfo(), {depth: null})); + util.inspect(pkcs11.C_GetInfo(), { depth: null })); // Getting list of slots var slots = pkcs11.C_GetSlotList(true); @@ -303,34 +302,29 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { throw new Error(__func() + 'PKCS11 slot number non-exist'); var slot = slots[pkcs11Slot]; logger.debug(__func() + 'C_GetSlotList: ' + - util.inspect(slots, {depth: null})); + util.inspect(slots, { depth: null })); // Getting info about slot logger.debug(__func() + 'C_GetSlotInfo(' + pkcs11Slot + '): ' + - util.inspect(pkcs11.C_GetSlotInfo(slot), - {depth: null})); + util.inspect(pkcs11.C_GetSlotInfo(slot), { depth: null })); // Getting info about token logger.debug(__func() + 'C_GetTokenInfo(' + pkcs11Slot + '): ' + - util.inspect(pkcs11.C_GetTokenInfo(slot), - {depth: null})); + util.inspect(pkcs11.C_GetTokenInfo(slot), { depth: null })); // Getting info about Mechanism logger.debug(__func() + 'C_GetMechanismList(' + pkcs11Slot + '): ' + - util.inspect(pkcs11.C_GetMechanismList(slot), - {depth: null})); + util.inspect(pkcs11.C_GetMechanismList(slot), { depth: null })); /* * Open session. */ let flags = pkcs11js.CKF_SERIAL_SESSION; - if(pkcs11ReadWrite) { + if (pkcs11ReadWrite) { flags = flags | pkcs11js.CKF_RW_SESSION; } this._pkcs11Session = pkcs11.C_OpenSession(slot, flags); // Getting info about Session logger.debug(__func() + 'C_GetSessionInfo(' + - util.inspect( - this._pkcs11Session, {depth: null}) + '): ' + - util.inspect(pkcs11.C_GetSessionInfo( - this._pkcs11Session), {depth: null})); + util.inspect(this._pkcs11Session, { depth: null }) + '): ' + + util.inspect(pkcs11.C_GetSessionInfo(this._pkcs11Session), { depth: null })); /* * Login with PIN. Error will be thrown if wrong PIN. @@ -342,14 +336,12 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { //pkcs11.C_Logout(session); //pkcs11.C_CloseSession(session); } - catch(e) { + catch (e) { if (this._pkcs11Session != null) pkcs11.C_CloseSession(this._pkcs11Session); pkcs11.C_Finalize(); _initialized = false; - throw(e); - } - finally { + throw (e); } } @@ -361,12 +353,12 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { _pkcs11GenerateKey(pkcs11, pkcs11Session, pkcs11Token) { var ski = this._ski(); var secretKeyTemplate = [ - { type: pkcs11js.CKA_ID, value: ski }, - { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY }, - { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES }, - { type: pkcs11js.CKA_VALUE_LEN, value: this._keySize/8 }, - { type: pkcs11js.CKA_ENCRYPT, value: true }, - { type: pkcs11js.CKA_DECRYPT, value: true }, + { type: pkcs11js.CKA_ID, value: ski }, + { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY }, + { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES }, + { type: pkcs11js.CKA_VALUE_LEN, value: this._keySize / 8 }, + { type: pkcs11js.CKA_ENCRYPT, value: true }, + { type: pkcs11js.CKA_DECRYPT, value: true }, /* * If user is logged in: * - key will be private @@ -379,8 +371,8 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { * accessible, respectively, and has nothing to do with public and * private key pair. */ - { type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login }, - { type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token }, + { type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login }, + { type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token }, ]; try { @@ -408,10 +400,10 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { pkcs11, pkcs11Session, handle, objectTemplate), { depth: null })); - return { ski: ski, key: handle }; + return { ski, key: handle }; } - catch(e) { - throw(e); + catch (e) { + throw (e); } } @@ -424,22 +416,24 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { //var ski = this._ski(); var privateKeyTemplate = [ //{ type: pkcs11js.CKA_ID, value: ski }, - { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PRIVATE_KEY }, - { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC }, - { type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login }, - { type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token }, - { type: pkcs11js.CKA_SIGN, value: true }, - { type: pkcs11js.CKA_DERIVE, value: true }, + { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PRIVATE_KEY }, + { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC }, + { type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login }, + { type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token }, + { type: pkcs11js.CKA_SIGN, value: true }, + { type: pkcs11js.CKA_DERIVE, value: true }, ]; var publicKeyTemplate = [ //{ type: pkcs11js.CKA_ID, value: ski }, - { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PUBLIC_KEY }, - { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC }, - { type: pkcs11js.CKA_PRIVATE, value: false }, - { type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token }, - { type: pkcs11js.CKA_VERIFY, value: true }, - { type: pkcs11js.CKA_EC_PARAMS, - value: Buffer.from(_pkcs11ParamsSizeToOid[this._keySize],'hex') }, + { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PUBLIC_KEY }, + { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC }, + { type: pkcs11js.CKA_PRIVATE, value: false }, + { type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token }, + { type: pkcs11js.CKA_VERIFY, value: true }, + { + type: pkcs11js.CKA_EC_PARAMS, + value: Buffer.from(_pkcs11ParamsSizeToOid[this._keySize], 'hex') + }, ]; try { @@ -477,23 +471,23 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { var ecpt = (this._pkcs11GetAttributeValue( pkcs11, pkcs11Session, handles.publicKey, - [{ type:pkcs11js.CKA_EC_POINT }]))[0].value; + [{ type: pkcs11js.CKA_EC_POINT }]))[0].value; /* * Workaround for opencryptoki bug reporting wrong ecpt length. */ ecpt = this._fixEcpt(ecpt); logger.debug(__func() + 'ecpt[' + ecpt.length + ']: ' + - util.inspect(ecpt, { depth: null })); + util.inspect(ecpt, { depth: null })); /* * Set CKA_ID of public and private key to be SKI. */ var ski = Buffer.from(hashPrimitives.sha2_256(ecpt), 'hex'); this._pkcs11SetAttributeValue( pkcs11, pkcs11Session, handles.publicKey, - [{ type: pkcs11js.CKA_ID, value: ski }, {type: pkcs11js.CKA_LABEL, value: ski.toString('hex')}]); + [{ type: pkcs11js.CKA_ID, value: ski }, { type: pkcs11js.CKA_LABEL, value: ski.toString('hex') }]); this._pkcs11SetAttributeValue( pkcs11, pkcs11Session, handles.privateKey, - [{ type: pkcs11js.CKA_ID, value: ski }, { type: pkcs11js.CKA_LABEL, value: ski.toString('hex')}]); + [{ type: pkcs11js.CKA_ID, value: ski }, { type: pkcs11js.CKA_LABEL, value: ski.toString('hex') }]); logger.debug(__func() + 'pub ski: ' + util.inspect( (this._pkcs11GetAttributeValue( pkcs11, pkcs11Session, handles.publicKey, @@ -505,11 +499,10 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { [{ type: pkcs11js.CKA_ID }]))[0].value, { depth: null })); - return { ski: ski, ecpt: ecpt, - pub: handles.publicKey, priv: handles.privateKey }; + return { ski, ecpt, pub: handles.publicKey, priv: handles.privateKey }; } - catch(e) { - throw(e); + catch (e) { + throw (e); } } @@ -524,9 +517,9 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { * First look for AES key. */ var secretKeyHandle = this._pkcs11FindObjects(pkcs11, pkcs11Session, [ - { type: pkcs11js.CKA_ID, value: ski }, - { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY }, - { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES }, + { type: pkcs11js.CKA_ID, value: ski }, + { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY }, + { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES }, ]); if (secretKeyHandle.length == 1) return { secretKey: secretKeyHandle[0] }; @@ -534,23 +527,23 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { * Then look for ECDSA key pair. */ var privKeyHandle = this._pkcs11FindObjects(pkcs11, pkcs11Session, [ - { type: pkcs11js.CKA_ID, value: ski }, - { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PRIVATE_KEY }, - { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC }, + { type: pkcs11js.CKA_ID, value: ski }, + { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PRIVATE_KEY }, + { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC }, ]); var pubKeyHandle = this._pkcs11FindObjects(pkcs11, pkcs11Session, [ - { type: pkcs11js.CKA_ID, value: ski }, - { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PUBLIC_KEY }, - { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC }, + { type: pkcs11js.CKA_ID, value: ski }, + { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_PUBLIC_KEY }, + { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_EC }, ]); if (pubKeyHandle.length != 1 || privKeyHandle.length != 1) throw new Error(__func() + 'no key with SKI ' + - ski.toString('hex') + ' found'); + ski.toString('hex') + ' found'); return { privateKey: privKeyHandle[0], publicKey: pubKeyHandle[0] }; } - catch(e) { - throw(e); + catch (e) { + throw (e); } } @@ -565,11 +558,12 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { var attribs = this._pkcs11GetAttributeValue( this._pkcs11, this._pkcs11Session, publicKey, - [ { type:pkcs11js.CKA_EC_PARAMS }, - { type:pkcs11js.CKA_EC_POINT }, + [ + { type: pkcs11js.CKA_EC_PARAMS }, + { type: pkcs11js.CKA_EC_POINT }, ]); logger.debug(__func() + 'attribuites: ' + - util.inspect(attribs, { depth: null} )); + util.inspect(attribs, { depth: null })); var ecparams, ecpt; if (attribs[0].type == pkcs11js.CKA_EC_PARAMS) { @@ -586,8 +580,8 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { return { ecparams: ecparams, ecpt: ecpt }; } - catch(e) { - throw(e); + catch (e) { + throw (e); } } @@ -600,24 +594,24 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { * key has been checked to be an ECDSA private key. */ pkcs11.C_SignInit(pkcs11Session, { mechanism: pkcs11js.CKM_ECDSA }, - key._handle); + key._handle); var sig = pkcs11.C_Sign(pkcs11Session, digest, - Buffer.alloc(this._keySize)); + Buffer.alloc(this._keySize)); logger.debug(__func() + 'ECDSA RAW signature: ' + - util.inspect(sig, {depth: null})); + util.inspect(sig, { depth: null })); /* * ASN1 DER encoding against malleability. */ - var r = new BN(sig.slice(0, sig.length/2).toString('hex'), 16); - var s = new BN(sig.slice(sig.length/2).toString('hex'), 16); - var sig = _preventMalleability({r: r, s: s}, this._ecdsaCurve); - var der = (new ecsig({ r: sig.r, s: sig.s})).toDER(); + var r = new BN(sig.slice(0, sig.length / 2).toString('hex'), 16); + var s = new BN(sig.slice(sig.length / 2).toString('hex'), 16); + var signature = _preventMalleability({ r: r, s: s }, this._ecdsaCurve); + var der = (new ecsig({ r: signature.r, s: signature.s })).toDER(); logger.debug(__func() + 'ECDSA DER signature: ' + - util.inspect(Buffer.from(der), {depth: null})); + util.inspect(Buffer.from(der), { depth: null })); return Buffer.from(der); } - catch(e) { - throw(e); + catch (e) { + throw (e); } } @@ -632,25 +626,25 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { */ var rns = new ecsig(signature, 'hex'); logger.debug(__func() + 'ECDSA R+S signature: ' + - util.inspect(rns, {depth: null})); - var sig = Buffer.concat([ rns.r.toArrayLike(Buffer, '', 0), - rns.s.toArrayLike(Buffer, '', 0)]); + util.inspect(rns, { depth: null })); + var sig = Buffer.concat([rns.r.toArrayLike(Buffer, '', 0), + rns.s.toArrayLike(Buffer, '', 0)]); logger.debug(__func() + 'ECDSA RAW signature: ' + - util.inspect(sig, {depth: null})); + util.inspect(sig, { depth: null })); /* * key can be either a private or a public key. */ pkcs11.C_VerifyInit(pkcs11Session, - { mechanism: pkcs11js.CKM_ECDSA }, - key._handle); + { mechanism: pkcs11js.CKM_ECDSA }, + key._handle); return pkcs11.C_Verify(pkcs11Session, digest, sig); } - catch(e) { + catch (e) { /* * Error is thrown when signature verification fails. */ if (e.message.indexOf('CKR_SIGNATURE_INVALID') != -1) return false; - throw(e); + throw (e); } } @@ -665,20 +659,18 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { var iv = pkcs11.C_GenerateRandom(pkcs11Session, Buffer.alloc(16)); pkcs11.C_EncryptInit(pkcs11Session, - { mechanism: pkcs11js.CKM_AES_CBC_PAD, - parameter: iv }, - key._handle); + { mechanism: pkcs11js.CKM_AES_CBC_PAD, parameter: iv }, + key._handle); /* * Prepend iv to ciphertext. */ return Buffer.concat([ iv, - pkcs11.C_Encrypt(pkcs11Session, plainText, - Buffer.alloc((plainText.length+16)&(~15))), + pkcs11.C_Encrypt(pkcs11Session, plainText, Buffer.alloc((plainText.length + 16) & (~15))) ]); } - catch(e) { - throw(e); + catch (e) { + throw (e); } } @@ -693,16 +685,15 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { var iv = cipherText.slice(0, 16); pkcs11.C_DecryptInit(pkcs11Session, - { mechanism: pkcs11js.CKM_AES_CBC_PAD, - parameter: iv }, - key._handle); + { mechanism: pkcs11js.CKM_AES_CBC_PAD, parameter: iv }, + key._handle); return pkcs11.C_Decrypt(pkcs11Session, - cipherText.slice(16, cipherText.length), - Buffer.alloc(cipherText.length-16)); + cipherText.slice(16, cipherText.length), + Buffer.alloc(cipherText.length - 16)); } - catch(e) { - throw(e); + catch (e) { + throw (e); } } @@ -712,53 +703,55 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { _pkcs11DeriveKey(pkcs11, pkcs11Session, key, pub) { var ski = this._ski(); var derivedKeyTemplate = [ - { type: pkcs11js.CKA_ID, value: ski }, - { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY }, - { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES }, - { type: pkcs11js.CKA_VALUE_LEN, value: 256/8 }, - { type: pkcs11js.CKA_ENCRYPT, value: true }, - { type: pkcs11js.CKA_DECRYPT, value: true }, - { type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login }, - { type: pkcs11js.CKA_TOKEN, value: false }, + { type: pkcs11js.CKA_ID, value: ski }, + { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY }, + { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES }, + { type: pkcs11js.CKA_VALUE_LEN, value: 256 / 8 }, + { type: pkcs11js.CKA_ENCRYPT, value: true }, + { type: pkcs11js.CKA_DECRYPT, value: true }, + { type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login }, + { type: pkcs11js.CKA_TOKEN, value: false }, ]; try { return pkcs11.C_DeriveKey( pkcs11Session, - { mechanism: pkcs11js.CKM_ECDH1_DERIVE, - parameter: { type: pkcs11js.CK_PARAMS_EC_DH, - kdf: pkcs11js.CKD_SHA256_KDF, - publicData: pub._ecpt, - } + { + mechanism: pkcs11js.CKM_ECDH1_DERIVE, + parameter: { + type: pkcs11js.CK_PARAMS_EC_DH, + kdf: pkcs11js.CKD_SHA256_KDF, + publicData: pub._ecpt, + } }, key._handle, derivedKeyTemplate); } - catch(e) { - throw(e); + catch (e) { + throw (e); } } _pkcs11CreateObject(pkcs11, pkcs11Session, key, pkcs11Token) { var ski = this._ski(); var keyTemplate = [ - { type: pkcs11js.CKA_ID, value: ski }, - { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY }, - { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES }, + { type: pkcs11js.CKA_ID, value: ski }, + { type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_SECRET_KEY }, + { type: pkcs11js.CKA_KEY_TYPE, value: pkcs11js.CKK_AES }, //SoftHSMv2 prohibits specifying CKA_VALUE_LEN //{ type: pkcs11js.CKA_VALUE_LEN, value: key.length }, - { type: pkcs11js.CKA_VALUE, value: key }, - { type: pkcs11js.CKA_ENCRYPT, value: true }, - { type: pkcs11js.CKA_DECRYPT, value: true }, - { type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login }, - { type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token }, + { type: pkcs11js.CKA_VALUE, value: key }, + { type: pkcs11js.CKA_ENCRYPT, value: true }, + { type: pkcs11js.CKA_DECRYPT, value: true }, + { type: pkcs11js.CKA_PRIVATE, value: this._pkcs11Login }, + { type: pkcs11js.CKA_TOKEN, value: this._pkcs11Login && pkcs11Token }, ]; try { var handle = pkcs11.C_CreateObject(pkcs11Session, keyTemplate); - return { ski: ski, key: handle }; + return { ski, key: handle }; } - catch(e) { - throw(e); + catch (e) { + throw (e); } } @@ -768,16 +761,14 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { * Return array of [ { type:..., value:... }, ... ] */ _pkcs11GetAttributeValue(pkcs11, pkcs11Session, pkcs11Object, pkcs11Template) { - return pkcs11.C_GetAttributeValue(pkcs11Session, pkcs11Object, - pkcs11Template); + return pkcs11.C_GetAttributeValue(pkcs11Session, pkcs11Object, pkcs11Template); } /* * Set PKCS11 object attributes. */ _pkcs11SetAttributeValue(pkcs11, pkcs11Session, pkcs11Object, pkcs11Template) { - return pkcs11.C_SetAttributeValue(pkcs11Session, pkcs11Object, - pkcs11Template); + return pkcs11.C_SetAttributeValue(pkcs11Session, pkcs11Object, pkcs11Template); } /* @@ -797,11 +788,9 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { { type: pkcs11js.CKA_TOKEN }, { type: pkcs11js.CKA_ID }, ]; - logger.debug(__func() + 'obj: ' + - util.inspect(obj, { depth: null })); - logger.debug(__func() + 'attr: ' + util.inspect( - this._pkcs11GetAttributeValue(pkcs11, pkcs11Session, obj, - objectTemplate))); + logger.debug(__func() + 'obj: ' + util.inspect(obj, { depth: null })); + logger.debug(__func() + 'attr: ' + + util.inspect(this._pkcs11GetAttributeValue(pkcs11, pkcs11Session, obj, objectTemplate))); objs.push(obj); obj = pkcs11.C_FindObjects(pkcs11Session); } @@ -834,51 +823,48 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { if (typeof opts === 'undefined' || opts === null || typeof opts.algorithm === 'undefined' || opts.algorithm === null || typeof opts.algorithm !== 'string') - return Promise.reject(Error(__func() + - 'opts.algorithm must be String type')); + return Promise.reject(Error(__func() + 'opts.algorithm must be String type')); - var token = (opts.ephemeral !== 'undefined' && - opts.ephemeral === false) ? true : false; + var token = !opts.ephemeral; var self = this; switch (opts.algorithm.toUpperCase()) { case 'AES': - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { try { if (self._keySize != 256) throw new Error( __func() + 'AES key size must be 256 (bits)'); var attr = self._pkcs11GenerateKey( self._pkcs11, self._pkcs11Session, token); - /* - * Put key in the session cache and return - * promise of the key. - */ + /* + * Put key in the session cache and return + * promise of the key. + */ var key = new aesKey(attr, self._keySize); self._skiToKey[attr.ski.toString('hex')] = key; return resolve(key); } - catch(e) { + catch (e) { return reject(e); } }); - break; case 'ECDSA': var cryptoSuite = this; - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { try { var attr = self._pkcs11GenerateECKeyPair( self._pkcs11, self._pkcs11Session, token); - /* - * Put key in the session cache and return - * promise of the key. - */ + /* + * Put key in the session cache and return + * promise of the key. + */ var key = new ecdsaKey(attr, self._keySize); self._skiToKey[attr.ski.toString('hex')] = key; key._cryptoSuite = cryptoSuite; return resolve(key); } - catch(e) { + catch (e) { return reject(e); } }); @@ -893,15 +879,15 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { * Returns the key this CSP associates to the Subject Key Identifier ski. */ getKey(ski) { - if (typeof ski === 'undefined' || ski === null || !(ski instanceof Buffer || typeof ski === 'string')) - return Promise.reject(Error(__func() + 'ski must be Buffer type')); + if (!ski || !(ski instanceof Buffer || typeof ski === 'string')) + return Promise.reject(Error(__func() + 'ski must be Buffer|string type')); /* * Found the ski in the session key cache. */ var hit = this._skiToKey[ski.toString('hex')]; if (hit !== undefined) { logger.debug(__func() + 'cache hit ' + - util.inspect(hit, { depth: null })); + util.inspect(hit, { depth: null })); return Promise.resolve(hit); } if (typeof ski == 'string') { @@ -909,7 +895,7 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { } var self = this; - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { try { var handle = self._pkcs11SkiToHandle( self._pkcs11, self._pkcs11Session, ski); @@ -921,9 +907,7 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { if (self._keySize != 256) { throw new Error(__func() + 'key size mismatch, class: ' + self._keySize + ', ski: 256'); } - key = new aesKey({ ski: ski, - key: handle.secretKey }, - self._keySize); + key = new aesKey({ ski, key: handle.secretKey }, self._keySize); } /* * ECDSA key. @@ -940,10 +924,8 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { keySize != self._keySize) { throw new Error(__func() + 'key size mismatch, class: ' + self._keySize + ', ski: ' + keySize); } - key = new ecdsaKey({ ski: ski, ecpt: attr.ecpt, - pub: handle.publicKey, - priv: handle.privateKey }, - self._keySize); + key = new ecdsaKey({ ski, ecpt: attr.ecpt, pub: handle.publicKey, priv: handle.privateKey }, + self._keySize); } /* * Put key in the session cache and return @@ -952,7 +934,7 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { self._skiToKey[ski.toString('hex')] = key; return resolve(key); } - catch(e) { + catch (e) { return reject(e); } }); @@ -962,13 +944,11 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { * This is an implementation of {@link module:api.CryptoSuite#sign} * Signs digest using key k. * - * The opts argument is not needed. */ - sign(key, digest, opts) { + sign(key, digest) { if (typeof key === 'undefined' || key === null || !(key instanceof ecdsaKey) || !key.isPrivate()) - throw new Error(__func() + - 'key must be PKCS11_ECDSA_KEY type private key'); + throw new Error(__func() + 'key must be PKCS11_ECDSA_KEY type private key'); if (typeof digest === 'undefined' || digest === null || !(digest instanceof Buffer)) throw new Error(__func() + 'digest must be Buffer type'); @@ -998,73 +978,68 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { } return this._pkcs11Verify(this._pkcs11, this._pkcs11Session, - key.getPublicKey(), digest, signature); + key.getPublicKey(), digest, signature); } /** * This is an implementation of {@link module:api.CryptoSuite#encrypt} * Encrypts plainText using key. - * The opts argument should be appropriate for the algorithm used. + * The opts argument is not supported. */ encrypt(key, plainText, opts) { + if (opts); if (typeof key === 'undefined' || key === null || !(key instanceof aesKey)) throw new Error(__func() + 'key must be PKCS11_AES_KEY type'); if (typeof plainText === 'undefined' || plainText === null || !(plainText instanceof Buffer)) throw new Error(__func() + 'plainText must be Buffer type'); - return this._pkcs11Encrypt(this._pkcs11, this._pkcs11Session, key, - plainText); + return this._pkcs11Encrypt(this._pkcs11, this._pkcs11Session, key, plainText); } /** * This is an implementation of {@link module:api.CryptoSuite#decrypt} * Decrypts cipherText using key. - * The opts argument should be appropriate for the algorithm used. + * The opts argument is not supported yet. */ decrypt(key, cipherText, opts) { + if (opts); if (typeof key === 'undefined' || key === null || !(key instanceof aesKey)) throw new Error(__func() + 'key must be PKCS11_AES_KEY type'); if (typeof cipherText === 'undefined' || cipherText === null || !(cipherText instanceof Buffer)) throw new Error(__func() + 'cipherText must be Buffer type'); - return this._pkcs11Decrypt(this._pkcs11, this._pkcs11Session, key, - cipherText); + return this._pkcs11Decrypt(this._pkcs11, this._pkcs11Session, key, cipherText); } /** * This is an implementation of {@link module:api.CryptoSuite#deriveKey} */ deriveKey(key, opts) { + if (key || opts); throw new Error(__func() + 'not yet supported'); } /** * This is an implementation of {@link module:api.CryptoSuite#importKey} */ - importKey(raw, opts) { - if (typeof opts === 'undefined') { - opts = {}; - } - if (typeof opts.algorithm === 'undefined') { - opts.algorithm = 'X509Certificate'; - } - if (typeof raw === 'undefined' || raw === null || !(raw instanceof Buffer || typeof raw === 'string')) - return Promise.reject(Error(__func() + 'raw must be Buffer type or String type')); - if (typeof opts === 'undefined' || opts === null || - typeof opts.algorithm === 'undefined' || opts.algorithm === null || - typeof opts.algorithm !== 'string') - return Promise.reject(Error(__func() + - 'opts.algorithm must be String type')); + importKey(pem, opts) { + const optsLocal = opts ? opts : {}; + + const algorithm = optsLocal.algorithm ? optsLocal.algorithm : 'X509Certificate'; + + if (!pem || !(pem instanceof Buffer || typeof pem === 'string')) + return Promise.reject(Error(__func() + 'pem must be Buffer type or String type')); + if (typeof algorithm !== 'string') + return Promise.reject(Error(__func() + 'opts.algorithm must be String type')); - var token = (typeof opts.ephemeral !== 'undefined' && - opts.ephemeral) ? false : true; + var token = !optsLocal.ephemeral; var self = this; - switch (opts.algorithm.toUpperCase()) { + switch (algorithm.toUpperCase()) { case 'X509CERTIFICATE': - var key = KEYUTIL.getKey(raw); + var key = KEYUTIL.getKey(pem); var theKey = new ECDSAKey(key); if (token) { return Promise.resolve(theKey); @@ -1072,36 +1047,37 @@ var CryptoSuite_PKCS11 = class extends api.CryptoSuite { return theKey; } case 'AES': - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { try { - if (raw.length != (256/8)) throw new Error( - __func() + 'AES key size must be 256 (bits)'); + if (pem.length != (256 / 8)) + throw new Error(__func() + 'AES key size must be 256 (bits)'); - var attr = self._pkcs11CreateObject( - self._pkcs11, self._pkcs11Session, raw, - token); + var attr = self._pkcs11CreateObject(self._pkcs11, self._pkcs11Session, pem, token); /* - * Put key in the session cache and return - * promise of the key. - */ - var key = new aesKey(attr, raw.length*8); + * Put key in the session cache and return + * promise of the key. + */ + var key = new aesKey(attr, pem.length * 8); self._skiToKey[attr.ski.toString('hex')] = key; return resolve(key); } - catch(e) { + catch (e) { reject(e); } }); case 'ECDSA': - return Promise.reject(Error(__func() + - 'ECDSA key not yet supported')); + return Promise.reject(Error(__func() + 'ECDSA key not yet supported')); default: - return Promise.reject(Error(__func() + - 'only AES or ECDSA key supported')); + return Promise.reject(Error(__func() + 'only AES or ECDSA key supported')); } } + /** + * This is an implementation of {@link module:api.CryptoSuite#hash} + * The opts argument is not supported yet. + */ hash(msg, opts) { + if (opts); return this._hashFunction(msg); } diff --git a/fabric-client/lib/impl/ecdsa/key.js b/fabric-client/lib/impl/ecdsa/key.js index 19bb663ec7..b89deadc95 100644 --- a/fabric-client/lib/impl/ecdsa/key.js +++ b/fabric-client/lib/impl/ecdsa/key.js @@ -124,7 +124,7 @@ module.exports = class ECDSA_KEY { //check to see if this is a private key if (!this.isPrivate()){ throw new Error('A CSR cannot be generated from a public key'); - }; + } try { var csr = asn1.csr.CSRUtil.newCSRPEM({ diff --git a/fabric-client/lib/impl/ecdsa/pkcs11_key.js b/fabric-client/lib/impl/ecdsa/pkcs11_key.js index 9f101fa8f7..7b9dfb2d4e 100644 --- a/fabric-client/lib/impl/ecdsa/pkcs11_key.js +++ b/fabric-client/lib/impl/ecdsa/pkcs11_key.js @@ -19,14 +19,10 @@ var api = require('../../api.js'); var jsrsa = require('jsrsasign'); var asn1 = jsrsa.asn1; -var crypto = jsrsa.crypto; var elliptic = require('elliptic'); var EC = elliptic.ec; -const _spkiBase = { 256: '3059301306072A8648CE3D020106082A8648CE3D030107034200', - 384: '', - }; /** * This module implements the {@link module:api.Key} interface, for ECDSA key management @@ -45,14 +41,14 @@ var PKCS11_ECDSA_KEY = class extends api.Key { if (!(attr.ski instanceof Buffer)) throw new Error('constructor: key SKI must be Buffer type'); if ((typeof attr.priv === 'undefined' || attr.priv === null) && - (typeof attr.pub === 'undefined' || attr.pub === null)) + (typeof attr.pub === 'undefined' || attr.pub === null)) throw new Error('constructor: invalid key handles'); if (typeof attr.priv !== 'undefined' && attr.priv !== null && - !(attr.priv instanceof Buffer)) throw new Error( - 'constructor: private key handle must be Buffer type'); - if (typeof attr.pub !== 'undefined' && attr.pub !== null && - !(attr.pub instanceof Buffer)) throw new Error( - 'constructor: public key handle must be Buffer type'); + !(attr.priv instanceof Buffer)) + throw new Error('constructor: private key handle must be Buffer type'); + if (typeof attr.pub !== 'undefined' && attr.pub !== null && + !(attr.pub instanceof Buffer)) + throw new Error('constructor: public key handle must be Buffer type'); if (size === 'undefined') throw new Error('constructor: size parameter must be specified'); if (size != 256 && size != 384) throw new Error( @@ -109,9 +105,9 @@ var PKCS11_ECDSA_KEY = class extends api.Key { csri.setSubjectByParam(param.subject); csri.setSubjectPublicKeyByGetKey({xy: pubKey.getPublic('hex'), curve: 'secp256r1'}); if (param.ext !== undefined && param.ext.length !== undefined) { - for (var i = 0; i < param.ext.length; i++) { - for (key in param.ext[i]) { - csri.appendExtensionByName(key, param.ext[i][key]); + for (let ext of param.ext) { + for (let key in ext) { + csri.appendExtensionByName(key, ext[key]); } } } @@ -128,7 +124,7 @@ var PKCS11_ECDSA_KEY = class extends api.Key { //check to see if this is a private key if (!this.isPrivate()){ throw new Error('A CSR cannot be generated from a public key'); - }; + } try { var csr = this.newCSRPEM({