diff --git a/dist/pouchdb.quick-search.js b/dist/pouchdb.quick-search.js index 4a3770b..2e51e4d 100644 --- a/dist/pouchdb.quick-search.js +++ b/dist/pouchdb.quick-search.js @@ -1,12 +1,12 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PouchQuickSearch = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { + return results.slice(skip); } + return results; +} - return out; -}; - -},{"47":47,"6":6,"97":97}],6:[function(require,module,exports){ -var base = exports; +function rowToDocId(row) { + var val = row.value; + // Users can explicitly specify a joined doc _id, or it + // defaults to the doc _id that emitted the key/value. + var docId = (val && typeof val === 'object' && val._id) || row.id; + return docId; +} -base.Reporter = require(8).Reporter; -base.DecoderBuffer = require(5).DecoderBuffer; -base.EncoderBuffer = require(5).EncoderBuffer; -base.Node = require(7); +function readAttachmentsAsBlobOrBuffer(res) { + res.rows.forEach(function (row) { + var atts = row.doc && row.doc._attachments; + if (!atts) { + return; + } + Object.keys(atts).forEach(function (filename) { + var att = atts[filename]; + atts[filename].data = pouchdbBinaryUtils.base64StringToBlobOrBuffer(att.data, att.content_type); + }); + }); +} -},{"5":5,"7":7,"8":8}],7:[function(require,module,exports){ -var Reporter = require(6).Reporter; -var EncoderBuffer = require(6).EncoderBuffer; -var DecoderBuffer = require(6).DecoderBuffer; -var assert = require(106); +function postprocessAttachments(opts) { + return function (res) { + if (opts.include_docs && opts.attachments && opts.binary) { + readAttachmentsAsBlobOrBuffer(res); + } + return res; + }; +} -// Supported tags -var tags = [ - 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', - 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', - 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', - 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' -]; +function createBuiltInError(name) { + var message = 'builtin ' + name + + ' function requires map values to be numbers' + + ' or number arrays'; + return new BuiltInError(message); +} -// Public methods list -var methods = [ - 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', - 'any', 'contains' -].concat(tags); +function sum(values) { + var result = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + if (typeof num !== 'number') { + if (Array.isArray(num)) { + // lists of numbers are also allowed, sum them separately + result = typeof result === 'number' ? [result] : result; + for (var j = 0, jLen = num.length; j < jLen; j++) { + var jNum = num[j]; + if (typeof jNum !== 'number') { + throw createBuiltInError('_sum'); + } else if (typeof result[j] === 'undefined') { + result.push(jNum); + } else { + result[j] += jNum; + } + } + } else { // not array/number + throw createBuiltInError('_sum'); + } + } else if (typeof result === 'number') { + result += num; + } else { // add number to array + result[0] += num; + } + } + return result; +} -// Overrided methods list -var overrided = [ - '_peekTag', '_decodeTag', '_use', - '_decodeStr', '_decodeObjid', '_decodeTime', - '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', +var builtInReduce = { + _sum: function (keys, values) { + return sum(values); + }, - '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', - '_encodeNull', '_encodeInt', '_encodeBool' -]; + _count: function (keys, values) { + return values.length; + }, -function Node(enc, parent) { - var state = {}; - this._baseState = state; + _stats: function (keys, values) { + // no need to implement rereduce=true, because Pouch + // will never call it + function sumsqr(values) { + var _sumsqr = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + _sumsqr += (num * num); + } + return _sumsqr; + } + return { + sum : sum(values), + min : Math.min.apply(null, values), + max : Math.max.apply(null, values), + count : values.length, + sumsqr : sumsqr(values) + }; + } +}; - state.enc = enc; +function addHttpParam(paramName, opts, params, asJson) { + // add an http param from opts to params, optionally json-encoded + var val = opts[paramName]; + if (typeof val !== 'undefined') { + if (asJson) { + val = encodeURIComponent(JSON.stringify(val)); + } + params.push(paramName + '=' + val); + } +} - state.parent = parent || null; - state.children = null; +function coerceInteger(integerCandidate) { + if (typeof integerCandidate !== 'undefined') { + var asNumber = Number(integerCandidate); + // prevents e.g. '1foo' or '1.1' being coerced to 1 + if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) { + return asNumber; + } else { + return integerCandidate; + } + } +} - // State - state.tag = null; - state.args = null; - state.reverseArgs = null; - state.choice = null; - state.optional = false; - state.any = false; - state.obj = false; - state.use = null; - state.useDecoder = null; - state.key = null; - state['default'] = null; - state.explicit = null; - state.implicit = null; - state.contains = null; +function coerceOptions(opts) { + opts.group_level = coerceInteger(opts.group_level); + opts.limit = coerceInteger(opts.limit); + opts.skip = coerceInteger(opts.skip); + return opts; +} - // Should create new instance on each method - if (!state.parent) { - state.children = []; - this._wrap(); +function checkPositiveInteger(number) { + if (number) { + if (typeof number !== 'number') { + return new QueryParseError('Invalid value for integer: "' + + number + '"'); + } + if (number < 0) { + return new QueryParseError('Invalid value for positive integer: ' + + '"' + number + '"'); + } } } -module.exports = Node; - -var stateProps = [ - 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', - 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', - 'implicit', 'contains' -]; -Node.prototype.clone = function clone() { - var state = this._baseState; - var cstate = {}; - stateProps.forEach(function(prop) { - cstate[prop] = state[prop]; - }); - var res = new this.constructor(cstate.parent); - res._baseState = cstate; - return res; -}; +function checkQueryParseError(options, fun) { + var startkeyName = options.descending ? 'endkey' : 'startkey'; + var endkeyName = options.descending ? 'startkey' : 'endkey'; -Node.prototype._wrap = function wrap() { - var state = this._baseState; - methods.forEach(function(method) { - this[method] = function _wrappedMethod() { - var clone = new this.constructor(this); - state.children.push(clone); - return clone[method].apply(clone, arguments); - }; - }, this); -}; - -Node.prototype._init = function init(body) { - var state = this._baseState; - - assert(state.parent === null); - body.call(this); + if (typeof options[startkeyName] !== 'undefined' && + typeof options[endkeyName] !== 'undefined' && + pouchdbCollate.collate(options[startkeyName], options[endkeyName]) > 0) { + throw new QueryParseError('No rows can match your key range, ' + + 'reverse your start_key and end_key or set {descending : true}'); + } else if (fun.reduce && options.reduce !== false) { + if (options.include_docs) { + throw new QueryParseError('{include_docs:true} is invalid for reduce'); + } else if (options.keys && options.keys.length > 1 && + !options.group && !options.group_level) { + throw new QueryParseError('Multi-key fetches for reduce views must use ' + + '{group: true}'); + } + } + ['group_level', 'limit', 'skip'].forEach(function (optionName) { + var error = checkPositiveInteger(options[optionName]); + if (error) { + throw error; + } + }); +} - // Filter children - state.children = state.children.filter(function(child) { - return child._baseState.parent === this; - }, this); - assert.equal(state.children.length, 1, 'Root node can have only one child'); -}; +function httpQuery(db, fun, opts) { + // List of parameters to add to the PUT request + var params = []; + var body; + var method = 'GET'; -Node.prototype._useArgs = function useArgs(args) { - var state = this._baseState; + // If opts.reduce exists and is defined, then add it to the list + // of parameters. + // If reduce=false then the results are that of only the map function + // not the final result of map and reduce. + addHttpParam('reduce', opts, params); + addHttpParam('include_docs', opts, params); + addHttpParam('attachments', opts, params); + addHttpParam('limit', opts, params); + addHttpParam('descending', opts, params); + addHttpParam('group', opts, params); + addHttpParam('group_level', opts, params); + addHttpParam('skip', opts, params); + addHttpParam('stale', opts, params); + addHttpParam('conflicts', opts, params); + addHttpParam('startkey', opts, params, true); + addHttpParam('start_key', opts, params, true); + addHttpParam('endkey', opts, params, true); + addHttpParam('end_key', opts, params, true); + addHttpParam('inclusive_end', opts, params); + addHttpParam('key', opts, params, true); - // Filter children and args - var children = args.filter(function(arg) { - return arg instanceof this.constructor; - }, this); - args = args.filter(function(arg) { - return !(arg instanceof this.constructor); - }, this); + // Format the list of parameters into a valid URI query string + params = params.join('&'); + params = params === '' ? '' : '?' + params; - if (children.length !== 0) { - assert(state.children === null); - state.children = children; + // If keys are supplied, issue a POST to circumvent GET query string limits + // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options + if (typeof opts.keys !== 'undefined') { + var MAX_URL_LENGTH = 2000; + // according to http://stackoverflow.com/a/417184/680742, + // the de facto URL length limit is 2000 characters - // Replace parent to maintain backward link - children.forEach(function(child) { - child._baseState.parent = this; - }, this); + var keysAsString = + 'keys=' + encodeURIComponent(JSON.stringify(opts.keys)); + if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) { + // If the keys are short enough, do a GET. we do this to work around + // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239) + params += (params[0] === '?' ? '&' : '?') + keysAsString; + } else { + method = 'POST'; + if (typeof fun === 'string') { + body = {keys: opts.keys}; + } else { // fun is {map : mapfun}, so append to this + fun.keys = opts.keys; + } + } } - if (args.length !== 0) { - assert(state.args === null); - state.args = args; - state.reverseArgs = args.map(function(arg) { - if (typeof arg !== 'object' || arg.constructor !== Object) - return arg; - var res = {}; - Object.keys(arg).forEach(function(key) { - if (key == (key | 0)) - key |= 0; - var value = arg[key]; - res[value] = key; - }); - return res; - }); + // We are referencing a query defined in the design doc + if (typeof fun === 'string') { + var parts = parseViewName(fun); + return db.request({ + method: method, + url: '_design/' + parts[0] + '/_view/' + parts[1] + params, + body: body + }).then(postprocessAttachments(opts)); } -}; - -// -// Overrided methods -// - -overrided.forEach(function(method) { - Node.prototype[method] = function _overrided() { - var state = this._baseState; - throw new Error(method + ' not implemented for encoding: ' + state.enc); - }; -}); - -// -// Public methods -// -tags.forEach(function(tag) { - Node.prototype[tag] = function _tagMethod() { - var state = this._baseState; - var args = Array.prototype.slice.call(arguments); + // We are using a temporary view, terrible for performance, good for testing + body = body || {}; + Object.keys(fun).forEach(function (key) { + if (Array.isArray(fun[key])) { + body[key] = fun[key]; + } else { + body[key] = fun[key].toString(); + } + }); + return db.request({ + method: 'POST', + url: '_temp_view' + params, + body: body + }).then(postprocessAttachments(opts)); +} - assert(state.tag === null); - state.tag = tag; +// custom adapters can define their own api._query +// and override the default behavior +/* istanbul ignore next */ +function customQuery(db, fun, opts) { + return new Promise(function (resolve, reject) { + db._query(fun, opts, function (err, res) { + if (err) { + return reject(err); + } + resolve(res); + }); + }); +} - this._useArgs(args); +// custom adapters can define their own api._viewCleanup +// and override the default behavior +/* istanbul ignore next */ +function customViewCleanup(db) { + return new Promise(function (resolve, reject) { + db._viewCleanup(function (err, res) { + if (err) { + return reject(err); + } + resolve(res); + }); + }); +} - return this; +function defaultsTo(value) { + return function (reason) { + /* istanbul ignore else */ + if (reason.status === 404) { + return value; + } else { + throw reason; + } }; -}); - -Node.prototype.use = function use(item) { - assert(item); - var state = this._baseState; - - assert(state.use === null); - state.use = item; - - return this; -}; - -Node.prototype.optional = function optional() { - var state = this._baseState; - - state.optional = true; +} - return this; -}; +// returns a promise for a list of docs to update, based on the input docId. +// the order doesn't matter, because post-3.2.0, bulkDocs +// is an atomic operation in all three adapters. +function getDocsToPersist(docId, view, docIdsToChangesAndEmits) { + var metaDocId = '_local/doc_' + docId; + var defaultMetaDoc = {_id: metaDocId, keys: []}; + var docData = docIdsToChangesAndEmits[docId]; + var indexableKeysToKeyValues = docData.indexableKeysToKeyValues; + var changes = docData.changes; -Node.prototype.def = function def(val) { - var state = this._baseState; + function getMetaDoc() { + if (isGenOne(changes)) { + // generation 1, so we can safely assume initial state + // for performance reasons (avoids unnecessary GETs) + return Promise.resolve(defaultMetaDoc); + } + return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc)); + } - assert(state['default'] === null); - state['default'] = val; - state.optional = true; + function getKeyValueDocs(metaDoc) { + if (!metaDoc.keys.length) { + // no keys, no need for a lookup + return Promise.resolve({rows: []}); + } + return view.db.allDocs({ + keys: metaDoc.keys, + include_docs: true + }); + } - return this; -}; + function processKvDocs(metaDoc, kvDocsRes) { + var kvDocs = []; + var oldKeysMap = {}; -Node.prototype.explicit = function explicit(num) { - var state = this._baseState; - - assert(state.explicit === null && state.implicit === null); - state.explicit = num; - - return this; -}; - -Node.prototype.implicit = function implicit(num) { - var state = this._baseState; + for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) { + var row = kvDocsRes.rows[i]; + var doc = row.doc; + if (!doc) { // deleted + continue; + } + kvDocs.push(doc); + oldKeysMap[doc._id] = true; + doc._deleted = !indexableKeysToKeyValues[doc._id]; + if (!doc._deleted) { + var keyValue = indexableKeysToKeyValues[doc._id]; + if ('value' in keyValue) { + doc.value = keyValue.value; + } + } + } - assert(state.explicit === null && state.implicit === null); - state.implicit = num; + var newKeys = Object.keys(indexableKeysToKeyValues); + newKeys.forEach(function (key) { + if (!oldKeysMap[key]) { + // new doc + var kvDoc = { + _id: key + }; + var keyValue = indexableKeysToKeyValues[key]; + if ('value' in keyValue) { + kvDoc.value = keyValue.value; + } + kvDocs.push(kvDoc); + } + }); + metaDoc.keys = pouchdbMapreduceUtils.uniq(newKeys.concat(metaDoc.keys)); + kvDocs.push(metaDoc); - return this; -}; + return kvDocs; + } -Node.prototype.obj = function obj() { - var state = this._baseState; - var args = Array.prototype.slice.call(arguments); + return getMetaDoc().then(function (metaDoc) { + return getKeyValueDocs(metaDoc).then(function (kvDocsRes) { + return processKvDocs(metaDoc, kvDocsRes); + }); + }); +} - state.obj = true; +// updates all emitted key/value docs and metaDocs in the mrview database +// for the given batch of documents from the source database +function saveKeyValues(view, docIdsToChangesAndEmits, seq) { + var seqDocId = '_local/lastSeq'; + return view.db.get(seqDocId) + .catch(defaultsTo({_id: seqDocId, seq: 0})) + .then(function (lastSeqDoc) { + var docIds = Object.keys(docIdsToChangesAndEmits); + return Promise.all(docIds.map(function (docId) { + return getDocsToPersist(docId, view, docIdsToChangesAndEmits); + })).then(function (listOfDocsToPersist) { + var docsToPersist = pouchdbUtils.flatten(listOfDocsToPersist); + lastSeqDoc.seq = seq; + docsToPersist.push(lastSeqDoc); + // write all docs in a single operation, update the seq once + return view.db.bulkDocs({docs : docsToPersist}); + }); + }); +} - if (args.length !== 0) - this._useArgs(args); +function getQueue(view) { + var viewName = typeof view === 'string' ? view : view.name; + var queue = persistentQueues[viewName]; + if (!queue) { + queue = persistentQueues[viewName] = new TaskQueue(); + } + return queue; +} - return this; -}; +function updateView(view) { + return pouchdbMapreduceUtils.sequentialize(getQueue(view), function () { + return updateViewInQueue(view); + })(); +} -Node.prototype.key = function key(newKey) { - var state = this._baseState; +function updateViewInQueue(view) { + // bind the emit function once + var mapResults; + var doc; - assert(state.key === null); - state.key = newKey; + function emit(key, value) { + var output = {id: doc._id, key: pouchdbCollate.normalizeKey(key)}; + // Don't explicitly store the value unless it's defined and non-null. + // This saves on storage space, because often people don't use it. + if (typeof value !== 'undefined' && value !== null) { + output.value = pouchdbCollate.normalizeKey(value); + } + mapResults.push(output); + } - return this; -}; + var mapFun; + // for temp_views one can use emit(doc, emit), see #38 + if (typeof view.mapFun === "function" && view.mapFun.length === 2) { + var origMap = view.mapFun; + mapFun = function (doc) { + return origMap(doc, emit); + }; + } else { + mapFun = evalfunc(view.mapFun.toString(), emit, sum, log, Array.isArray, + JSON.parse); + } -Node.prototype.any = function any() { - var state = this._baseState; + var currentSeq = view.seq || 0; - state.any = true; + function processChange(docIdsToChangesAndEmits, seq) { + return function () { + return saveKeyValues(view, docIdsToChangesAndEmits, seq); + }; + } - return this; -}; + var queue = new TaskQueue(); + // TODO(neojski): https://github.com/daleharvey/pouchdb/issues/1521 -Node.prototype.choice = function choice(obj) { - var state = this._baseState; + return new Promise(function (resolve, reject) { - assert(state.choice === null); - state.choice = obj; - this._useArgs(Object.keys(obj).map(function(key) { - return obj[key]; - })); + function complete() { + queue.finish().then(function () { + view.seq = currentSeq; + resolve(); + }); + } - return this; -}; + function processNextBatch() { + view.sourceDB.changes({ + conflicts: true, + include_docs: true, + style: 'all_docs', + since: currentSeq, + limit: CHANGES_BATCH_SIZE + }).on('complete', function (response) { + var results = response.results; + if (!results.length) { + return complete(); + } + var docIdsToChangesAndEmits = {}; + for (var i = 0, l = results.length; i < l; i++) { + var change = results[i]; + if (change.doc._id[0] !== '_') { + mapResults = []; + doc = change.doc; -Node.prototype.contains = function contains(item) { - var state = this._baseState; + if (!doc._deleted) { + tryCode(view.sourceDB, mapFun, [doc]); + } + mapResults.sort(sortByKeyThenValue); - assert(state.use === null); - state.contains = item; + var indexableKeysToKeyValues = {}; + var lastKey; + for (var j = 0, jl = mapResults.length; j < jl; j++) { + var obj = mapResults[j]; + var complexKey = [obj.key, obj.id]; + if (pouchdbCollate.collate(obj.key, lastKey) === 0) { + complexKey.push(j); // dup key+id, so make it unique + } + var indexableKey = pouchdbCollate.toIndexableString(complexKey); + indexableKeysToKeyValues[indexableKey] = obj; + lastKey = obj.key; + } + docIdsToChangesAndEmits[change.doc._id] = { + indexableKeysToKeyValues: indexableKeysToKeyValues, + changes: change.changes + }; + } + currentSeq = change.seq; + } + queue.add(processChange(docIdsToChangesAndEmits, currentSeq)); + if (results.length < CHANGES_BATCH_SIZE) { + return complete(); + } + return processNextBatch(); + }).on('error', onError); + /* istanbul ignore next */ + function onError(err) { + reject(err); + } + } - return this; -}; + processNextBatch(); + }); +} -// -// Decoding -// +function reduceView(view, results, options) { + if (options.group_level === 0) { + delete options.group_level; + } -Node.prototype._decode = function decode(input, options) { - var state = this._baseState; + var shouldGroup = options.group || options.group_level; - // Decode root node - if (state.parent === null) - return input.wrapResult(state.children[0]._decode(input, options)); + var reduceFun; + if (builtInReduce[view.reduceFun]) { + reduceFun = builtInReduce[view.reduceFun]; + } else { + reduceFun = evalfunc( + view.reduceFun.toString(), null, sum, log, Array.isArray, JSON.parse); + } - var result = state['default']; - var present = true; + var groups = []; + var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY : + options.group_level; + results.forEach(function (e) { + var last = groups[groups.length - 1]; + var groupKey = shouldGroup ? e.key : null; - var prevKey = null; - if (state.key !== null) - prevKey = input.enterKey(state.key); + // only set group_level for array keys + if (shouldGroup && Array.isArray(groupKey)) { + groupKey = groupKey.slice(0, lvl); + } - // Check if tag is there - if (state.optional) { - var tag = null; - if (state.explicit !== null) - tag = state.explicit; - else if (state.implicit !== null) - tag = state.implicit; - else if (state.tag !== null) - tag = state.tag; - - if (tag === null && !state.any) { - // Trial and Error - var save = input.save(); - try { - if (state.choice === null) - this._decodeGeneric(state.tag, input, options); - else - this._decodeChoice(input, options); - present = true; - } catch (e) { - present = false; - } - input.restore(save); - } else { - present = this._peekTag(input, tag, state.any); - - if (input.isError(present)) - return present; - } - } - - // Push object on stack - var prevObj; - if (state.obj && present) - prevObj = input.enterObject(); - - if (present) { - // Unwrap explicit values - if (state.explicit !== null) { - var explicit = this._decodeTag(input, state.explicit); - if (input.isError(explicit)) - return explicit; - input = explicit; + if (last && pouchdbCollate.collate(last.groupKey, groupKey) === 0) { + last.keys.push([e.key, e.id]); + last.values.push(e.value); + return; } - - var start = input.offset; - - // Unwrap implicit and normal values - if (state.use === null && state.choice === null) { - if (state.any) - var save = input.save(); - var body = this._decodeTag( - input, - state.implicit !== null ? state.implicit : state.tag, - state.any - ); - if (input.isError(body)) - return body; - - if (state.any) - result = input.raw(save); - else - input = body; + groups.push({ + keys: [[e.key, e.id]], + values: [e.value], + groupKey: groupKey + }); + }); + results = []; + for (var i = 0, len = groups.length; i < len; i++) { + var e = groups[i]; + var reduceTry = tryCode(view.sourceDB, reduceFun, + [e.keys, e.values, false]); + if (reduceTry.error && reduceTry.error instanceof BuiltInError) { + // CouchDB returns an error if a built-in errors out + throw reduceTry.error; } + results.push({ + // CouchDB just sets the value to null if a non-built-in errors out + value: reduceTry.error ? null : reduceTry.output, + key: e.groupKey + }); + } + // no total_rows/offset when reducing + return {rows: sliceResults(results, options.limit, options.skip)}; +} - if (options && options.track && state.tag !== null) - options.track(input.path(), start, input.length, 'tagged'); +function queryView(view, opts) { + return pouchdbMapreduceUtils.sequentialize(getQueue(view), function () { + return queryViewInQueue(view, opts); + })(); +} - if (options && options.track && state.tag !== null) - options.track(input.path(), input.offset, input.length, 'content'); +function queryViewInQueue(view, opts) { + var totalRows; + var shouldReduce = view.reduceFun && opts.reduce !== false; + var skip = opts.skip || 0; + if (typeof opts.keys !== 'undefined' && !opts.keys.length) { + // equivalent query + opts.limit = 0; + delete opts.keys; + } - // Select proper method for tag - if (state.any) - result = result; - else if (state.choice === null) - result = this._decodeGeneric(state.tag, input, options); - else - result = this._decodeChoice(input, options); + function fetchFromView(viewOpts) { + viewOpts.include_docs = true; + return view.db.allDocs(viewOpts).then(function (res) { + totalRows = res.total_rows; + return res.rows.map(function (result) { - if (input.isError(result)) - return result; + // implicit migration - in older versions of PouchDB, + // we explicitly stored the doc as {id: ..., key: ..., value: ...} + // this is tested in a migration test + /* istanbul ignore next */ + if ('value' in result.doc && typeof result.doc.value === 'object' && + result.doc.value !== null) { + var keys = Object.keys(result.doc.value).sort(); + // this detection method is not perfect, but it's unlikely the user + // emitted a value which was an object with these 3 exact keys + var expectedKeys = ['id', 'key', 'value']; + if (!(keys < expectedKeys || keys > expectedKeys)) { + return result.doc.value; + } + } - // Decode children - if (!state.any && state.choice === null && state.children !== null) { - state.children.forEach(function decodeChildren(child) { - // NOTE: We are ignoring errors here, to let parser continue with other - // parts of encoded data - child._decode(input, options); + var parsedKeyAndDocId = pouchdbCollate.parseIndexableString(result.doc._id); + return { + key: parsedKeyAndDocId[0], + id: parsedKeyAndDocId[1], + value: ('value' in result.doc ? result.doc.value : null) + }; }); + }); + } + + function onMapResultsReady(rows) { + var finalResults; + if (shouldReduce) { + finalResults = reduceView(view, rows, opts); + } else { + finalResults = { + total_rows: totalRows, + offset: skip, + rows: rows + }; } + if (opts.include_docs) { + var docIds = pouchdbMapreduceUtils.uniq(rows.map(rowToDocId)); - // Decode contained/encoded by schema, only in bit or octet strings - if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { - var data = new DecoderBuffer(result); - result = this._getUse(state.contains, input._reporterState.obj) - ._decode(data, options); + return view.sourceDB.allDocs({ + keys: docIds, + include_docs: true, + conflicts: opts.conflicts, + attachments: opts.attachments, + binary: opts.binary + }).then(function (allDocsRes) { + var docIdsToDocs = {}; + allDocsRes.rows.forEach(function (row) { + if (row.doc) { + docIdsToDocs['$' + row.id] = row.doc; + } + }); + rows.forEach(function (row) { + var docId = rowToDocId(row); + var doc = docIdsToDocs['$' + docId]; + if (doc) { + row.doc = doc; + } + }); + return finalResults; + }); + } else { + return finalResults; } } - // Pop object - if (state.obj && present) - result = input.leaveObject(prevObj); - - // Set key - if (state.key !== null && (result !== null || present === true)) - input.leaveKey(prevKey, state.key, result); - else if (prevKey !== null) - input.exitKey(prevKey); + if (typeof opts.keys !== 'undefined') { + var keys = opts.keys; + var fetchPromises = keys.map(function (key) { + var viewOpts = { + startkey : pouchdbCollate.toIndexableString([key]), + endkey : pouchdbCollate.toIndexableString([key, {}]) + }; + return fetchFromView(viewOpts); + }); + return Promise.all(fetchPromises).then(pouchdbUtils.flatten).then(onMapResultsReady); + } else { // normal query, no 'keys' + var viewOpts = { + descending : opts.descending + }; + if (opts.start_key) { + opts.startkey = opts.start_key; + } + if (opts.end_key) { + opts.endkey = opts.end_key; + } + if (typeof opts.startkey !== 'undefined') { + viewOpts.startkey = opts.descending ? + pouchdbCollate.toIndexableString([opts.startkey, {}]) : + pouchdbCollate.toIndexableString([opts.startkey]); + } + if (typeof opts.endkey !== 'undefined') { + var inclusiveEnd = opts.inclusive_end !== false; + if (opts.descending) { + inclusiveEnd = !inclusiveEnd; + } - return result; -}; + viewOpts.endkey = pouchdbCollate.toIndexableString( + inclusiveEnd ? [opts.endkey, {}] : [opts.endkey]); + } + if (typeof opts.key !== 'undefined') { + var keyStart = pouchdbCollate.toIndexableString([opts.key]); + var keyEnd = pouchdbCollate.toIndexableString([opts.key, {}]); + if (viewOpts.descending) { + viewOpts.endkey = keyStart; + viewOpts.startkey = keyEnd; + } else { + viewOpts.startkey = keyStart; + viewOpts.endkey = keyEnd; + } + } + if (!shouldReduce) { + if (typeof opts.limit === 'number') { + viewOpts.limit = opts.limit; + } + viewOpts.skip = skip; + } + return fetchFromView(viewOpts).then(onMapResultsReady); + } +} -Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { - var state = this._baseState; +function httpViewCleanup(db) { + return db.request({ + method: 'POST', + url: '_view_cleanup' + }); +} - if (tag === 'seq' || tag === 'set') - return null; - if (tag === 'seqof' || tag === 'setof') - return this._decodeList(input, tag, state.args[0], options); - else if (/str$/.test(tag)) - return this._decodeStr(input, tag, options); - else if (tag === 'objid' && state.args) - return this._decodeObjid(input, state.args[0], state.args[1], options); - else if (tag === 'objid') - return this._decodeObjid(input, null, null, options); - else if (tag === 'gentime' || tag === 'utctime') - return this._decodeTime(input, tag, options); - else if (tag === 'null_') - return this._decodeNull(input, options); - else if (tag === 'bool') - return this._decodeBool(input, options); - else if (tag === 'objDesc') - return this._decodeStr(input, tag, options); - else if (tag === 'int' || tag === 'enum') - return this._decodeInt(input, state.args && state.args[0], options); +function localViewCleanup(db) { + return db.get('_local/mrviews').then(function (metaDoc) { + var docsToViews = {}; + Object.keys(metaDoc.views).forEach(function (fullViewName) { + var parts = parseViewName(fullViewName); + var designDocName = '_design/' + parts[0]; + var viewName = parts[1]; + docsToViews[designDocName] = docsToViews[designDocName] || {}; + docsToViews[designDocName][viewName] = true; + }); + var opts = { + keys : Object.keys(docsToViews), + include_docs : true + }; + return db.allDocs(opts).then(function (res) { + var viewsToStatus = {}; + res.rows.forEach(function (row) { + var ddocName = row.key.substring(8); + Object.keys(docsToViews[row.key]).forEach(function (viewName) { + var fullViewName = ddocName + '/' + viewName; + /* istanbul ignore if */ + if (!metaDoc.views[fullViewName]) { + // new format, without slashes, to support PouchDB 2.2.0 + // migration test in pouchdb's browser.migration.js verifies this + fullViewName = viewName; + } + var viewDBNames = Object.keys(metaDoc.views[fullViewName]); + // design doc deleted, or view function nonexistent + var statusIsGood = row.doc && row.doc.views && + row.doc.views[viewName]; + viewDBNames.forEach(function (viewDBName) { + viewsToStatus[viewDBName] = + viewsToStatus[viewDBName] || statusIsGood; + }); + }); + }); + var dbsToDelete = Object.keys(viewsToStatus).filter( + function (viewDBName) { return !viewsToStatus[viewDBName]; }); + var destroyPromises = dbsToDelete.map(function (viewDBName) { + return pouchdbMapreduceUtils.sequentialize(getQueue(viewDBName), function () { + return new db.constructor(viewDBName, db.__opts).destroy(); + })(); + }); + return Promise.all(destroyPromises).then(function () { + return {ok: true}; + }); + }); + }, defaultsTo({ok: true})); +} - if (state.use !== null) { - return this._getUse(state.use, input._reporterState.obj) - ._decode(input, options); - } else { - return input.error('unknown tag: ' + tag); +var viewCleanup = pouchdbMapreduceUtils.callbackify(function () { + var db = this; + if (db.type() === 'http') { + return httpViewCleanup(db); } -}; - -Node.prototype._getUse = function _getUse(entity, obj) { - - var state = this._baseState; - // Create altered use decoder if implicit is set - state.useDecoder = this._use(entity, obj); - assert(state.useDecoder._baseState.parent === null); - state.useDecoder = state.useDecoder._baseState.children[0]; - if (state.implicit !== state.useDecoder._baseState.implicit) { - state.useDecoder = state.useDecoder.clone(); - state.useDecoder._baseState.implicit = state.implicit; + /* istanbul ignore next */ + if (typeof db._viewCleanup === 'function') { + return customViewCleanup(db); } - return state.useDecoder; -}; + return localViewCleanup(db); +}); -Node.prototype._decodeChoice = function decodeChoice(input, options) { - var state = this._baseState; - var result = null; - var match = false; +function queryPromised(db, fun, opts) { + if (db.type() === 'http') { + return httpQuery(db, fun, opts); + } - Object.keys(state.choice).some(function(key) { - var save = input.save(); - var node = state.choice[key]; - try { - var value = node._decode(input, options); - if (input.isError(value)) - return false; + /* istanbul ignore next */ + if (typeof db._query === 'function') { + return customQuery(db, fun, opts); + } - result = { type: key, value: value }; - match = true; - } catch (e) { - input.restore(save); - return false; + function onViewReady(view) { + if (opts.stale === 'ok' || opts.stale === 'update_after') { + if (opts.stale === 'update_after') { + process.nextTick(function () { + updateView(view); + }); + } + return queryView(view, opts); + } else { // stale not ok + return updateView(view).then(function () { + return queryView(view, opts); + }); } - return true; - }, this); - - if (!match) - return input.error('Choice not matched'); + } - return result; -}; + if (opts.saveAs) { + var autoOptions = { + db: db, + saveAs: opts.saveAs, + map: fun.map, + reduce: fun.reduce + }; + if (opts.destroy) { + return createView(autoOptions).then(function (view) { + return view.db.destroy(); + }); + } + checkQueryParseError(opts, fun); + return createView(autoOptions).then(onViewReady); + } -// -// Encoding -// + if (typeof fun !== 'string') { + // temp_view + checkQueryParseError(opts, fun); -Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { - return new EncoderBuffer(data, this.reporter); -}; + var createViewOpts = { + db : db, + viewName : 'temp_view/temp_view', + map : fun.map, + reduce : fun.reduce, + temporary : true + }; + tempViewQueue.add(function () { + return createView(createViewOpts).then(function (view) { + function cleanup() { + return view.db.destroy(); + } + return pouchdbMapreduceUtils.fin(updateView(view).then(function () { + return queryView(view, opts); + }), cleanup); + }); + }); + return tempViewQueue.finish(); + } -Node.prototype._encode = function encode(data, reporter, parent) { - var state = this._baseState; - if (state['default'] !== null && state['default'] === data) - return; - var result = this._encodeValue(data, reporter, parent); - if (result === undefined) - return; + // persistent view + var fullViewName = fun; + var parts = parseViewName(fullViewName); + var designDocName = parts[0]; + var viewName = parts[1]; + return db.get('_design/' + designDocName).then(function (doc) { + var fun = doc.views && doc.views[viewName]; - if (this._skipDefault(result, reporter, parent)) - return; + if (!fun || typeof fun.map !== 'string') { + throw new NotFoundError('ddoc ' + designDocName + + ' has no view named ' + viewName); + } + checkQueryParseError(opts, fun); - return result; -}; + var createViewOpts = { + db : db, + viewName : fullViewName, + map : fun.map, + reduce : fun.reduce + }; -Node.prototype._encodeValue = function encode(data, reporter, parent) { - var state = this._baseState; + return createView(createViewOpts).then(onViewReady); + }); - // Decode root node - if (state.parent === null) - return state.children[0]._encode(data, reporter || new Reporter()); +} - var result = null; +var query = function (fun, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = opts ? coerceOptions(opts) : {}; - // Set reporter to share it with a child class - this.reporter = reporter; + if (typeof fun === 'function') { + fun = {map : fun}; + } - // Check if data is there - if (state.optional && data === undefined) { - if (state['default'] !== null) - data = state['default'] - else - return; + if (fun.saveAs) { + opts.saveAs = fun.saveAs; + delete fun.saveAs; } - // Encode children first - var content = null; - var primitive = false; - if (state.any) { - // Anything that was given is translated to buffer - result = this._createEncoderBuffer(data); - } else if (state.choice) { - result = this._encodeChoice(data, reporter); - } else if (state.contains) { - content = this._getUse(state.contains, parent)._encode(data, reporter); - primitive = true; - } else if (state.children) { - content = state.children.map(function(child) { - if (child._baseState.tag === 'null_') - return child._encode(null, reporter, data); - - if (child._baseState.key === null) - return reporter.error('Child should have a key'); - var prevKey = reporter.enterKey(child._baseState.key); + var db = this; + var promise = Promise.resolve().then(function () { + return queryPromised(db, fun, opts); + }); + pouchdbMapreduceUtils.promisedCallback(promise, callback); + return promise; +}; - if (typeof data !== 'object') - return reporter.error('Child expected, but input is not object'); +function QueryParseError(message) { + this.status = 400; + this.name = 'query_parse_error'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, QueryParseError); + } catch (e) {} +} - var res = child._encode(data[child._baseState.key], reporter, data); - reporter.leaveKey(prevKey); +inherits(QueryParseError, Error); - return res; - }, this).filter(function(child) { - return child; - }); - content = this._createEncoderBuffer(content); - } else { - if (state.tag === 'seqof' || state.tag === 'setof') { - // TODO(indutny): this should be thrown on DSL level - if (!(state.args && state.args.length === 1)) - return reporter.error('Too many args for : ' + state.tag); +function NotFoundError(message) { + this.status = 404; + this.name = 'not_found'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, NotFoundError); + } catch (e) {} +} - if (!Array.isArray(data)) - return reporter.error('seqof/setof, but data is not Array'); +inherits(NotFoundError, Error); - var child = this.clone(); - child._baseState.implicit = null; - content = this._createEncoderBuffer(data.map(function(item) { - var state = this._baseState; +function BuiltInError(message) { + this.status = 500; + this.name = 'invalid_value'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, BuiltInError); + } catch (e) {} +} - return this._getUse(state.args[0], data)._encode(item, reporter); - }, child)); - } else if (state.use !== null) { - result = this._getUse(state.use, parent)._encode(data, reporter); - } else { - content = this._encodePrimitive(state.tag, data); - primitive = true; - } - } +inherits(BuiltInError, Error); - // Encode data itself - var result; - if (!state.any && state.choice === null) { - var tag = state.implicit !== null ? state.implicit : state.tag; - var cls = state.implicit === null ? 'universal' : 'context'; +var index = { + _search_query: query, + _search_viewCleanup: viewCleanup +}; - if (tag === null) { - if (state.use === null) - reporter.error('Tag could be ommited only for .use()'); - } else { - if (state.use === null) - result = this._encodeComposite(tag, primitive, cls, content); - } +module.exports = index; +}).call(this,require(151)) +},{"133":133,"134":134,"140":140,"142":142,"146":146,"151":151,"162":162,"3":3,"5":5}],3:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor } +} - // Wrap in explicit - if (state.explicit !== null) - result = this._encodeComposite(state.explicit, false, 'context', result); +},{}],4:[function(require,module,exports){ +'use strict'; +var immediate = require(109); - return result; -}; +/* istanbul ignore next */ +function INTERNAL() {} -Node.prototype._encodeChoice = function encodeChoice(data, reporter) { - var state = this._baseState; +var handlers = {}; - var node = state.choice[data.type]; - if (!node) { - assert( - false, - data.type + ' not found in ' + - JSON.stringify(Object.keys(state.choice))); - } - return node._encode(data.value, reporter); -}; +var REJECTED = ['REJECTED']; +var FULFILLED = ['FULFILLED']; +var PENDING = ['PENDING']; -Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { - var state = this._baseState; +module.exports = Promise; - if (/str$/.test(tag)) - return this._encodeStr(data, tag); - else if (tag === 'objid' && state.args) - return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); - else if (tag === 'objid') - return this._encodeObjid(data, null, null); - else if (tag === 'gentime' || tag === 'utctime') - return this._encodeTime(data, tag); - else if (tag === 'null_') - return this._encodeNull(); - else if (tag === 'int' || tag === 'enum') - return this._encodeInt(data, state.args && state.reverseArgs[0]); - else if (tag === 'bool') - return this._encodeBool(data); - else if (tag === 'objDesc') - return this._encodeStr(data, tag); - else - throw new Error('Unsupported tag: ' + tag); -}; +function Promise(resolver) { + if (typeof resolver !== 'function') { + throw new TypeError('resolver must be a function'); + } + this.state = PENDING; + this.queue = []; + this.outcome = void 0; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } +} -Node.prototype._isNumstr = function isNumstr(str) { - return /^[0-9 ]*$/.test(str); +Promise.prototype["catch"] = function (onRejected) { + return this.then(null, onRejected); }; +Promise.prototype.then = function (onFulfilled, onRejected) { + if (typeof onFulfilled !== 'function' && this.state === FULFILLED || + typeof onRejected !== 'function' && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } -Node.prototype._isPrintstr = function isPrintstr(str) { - return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); + return promise; }; - -},{"106":106,"6":6}],8:[function(require,module,exports){ -var inherits = require(97); - -function Reporter(options) { - this._reporterState = { - obj: null, - path: [], - options: options || {}, - errors: [] - }; +function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === 'function') { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === 'function') { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } } -exports.Reporter = Reporter; - -Reporter.prototype.isError = function isError(obj) { - return obj instanceof ReporterError; +QueueItem.prototype.callFulfilled = function (value) { + handlers.resolve(this.promise, value); }; - -Reporter.prototype.save = function save() { - var state = this._reporterState; - - return { obj: state.obj, pathLen: state.path.length }; +QueueItem.prototype.otherCallFulfilled = function (value) { + unwrap(this.promise, this.onFulfilled, value); }; - -Reporter.prototype.restore = function restore(data) { - var state = this._reporterState; - - state.obj = data.obj; - state.path = state.path.slice(0, data.pathLen); +QueueItem.prototype.callRejected = function (value) { + handlers.reject(this.promise, value); }; - -Reporter.prototype.enterKey = function enterKey(key) { - return this._reporterState.path.push(key); +QueueItem.prototype.otherCallRejected = function (value) { + unwrap(this.promise, this.onRejected, value); }; -Reporter.prototype.exitKey = function exitKey(index) { - var state = this._reporterState; +function unwrap(promise, func, value) { + immediate(function () { + var returnValue; + try { + returnValue = func(value); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError('Cannot resolve promise with itself')); + } else { + handlers.resolve(promise, returnValue); + } + }); +} - state.path = state.path.slice(0, index - 1); -}; +handlers.resolve = function (self, value) { + var result = tryCatch(getThen, value); + if (result.status === 'error') { + return handlers.reject(self, result.value); + } + var thenable = result.value; -Reporter.prototype.leaveKey = function leaveKey(index, key, value) { - var state = this._reporterState; - - this.exitKey(index); - if (state.obj !== null) - state.obj[key] = value; -}; - -Reporter.prototype.path = function path() { - return this._reporterState.path.join('/'); + if (thenable) { + safelyResolveThenable(self, thenable); + } else { + self.state = FULFILLED; + self.outcome = value; + var i = -1; + var len = self.queue.length; + while (++i < len) { + self.queue[i].callFulfilled(value); + } + } + return self; }; - -Reporter.prototype.enterObject = function enterObject() { - var state = this._reporterState; - - var prev = state.obj; - state.obj = {}; - return prev; +handlers.reject = function (self, error) { + self.state = REJECTED; + self.outcome = error; + var i = -1; + var len = self.queue.length; + while (++i < len) { + self.queue[i].callRejected(error); + } + return self; }; -Reporter.prototype.leaveObject = function leaveObject(prev) { - var state = this._reporterState; +function getThen(obj) { + // Make sure we only access the accessor once as required by the spec + var then = obj && obj.then; + if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') { + return function appyThen() { + then.apply(obj, arguments); + }; + } +} - var now = state.obj; - state.obj = prev; - return now; -}; +function safelyResolveThenable(self, thenable) { + // Either fulfill, reject or reject with error + var called = false; + function onError(value) { + if (called) { + return; + } + called = true; + handlers.reject(self, value); + } -Reporter.prototype.error = function error(msg) { - var err; - var state = this._reporterState; + function onSuccess(value) { + if (called) { + return; + } + called = true; + handlers.resolve(self, value); + } - var inherited = msg instanceof ReporterError; - if (inherited) { - err = msg; - } else { - err = new ReporterError(state.path.map(function(elem) { - return '[' + JSON.stringify(elem) + ']'; - }).join(''), msg.message || msg, msg.stack); + function tryToUnwrap() { + thenable(onSuccess, onError); } - if (!state.options.partial) - throw err; + var result = tryCatch(tryToUnwrap); + if (result.status === 'error') { + onError(result.value); + } +} - if (!inherited) - state.errors.push(err); +function tryCatch(func, value) { + var out = {}; + try { + out.value = func(value); + out.status = 'success'; + } catch (e) { + out.status = 'error'; + out.value = e; + } + return out; +} - return err; -}; +Promise.resolve = resolve; +function resolve(value) { + if (value instanceof this) { + return value; + } + return handlers.resolve(new this(INTERNAL), value); +} -Reporter.prototype.wrapResult = function wrapResult(result) { - var state = this._reporterState; - if (!state.options.partial) - return result; +Promise.reject = reject; +function reject(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); +} - return { - result: this.isError(result) ? null : result, - errors: state.errors - }; -}; +Promise.all = all; +function all(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== '[object Array]') { + return this.reject(new TypeError('must be an array')); + } -function ReporterError(path, msg) { - this.path = path; - this.rethrow(msg); -}; -inherits(ReporterError, Error); + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } -ReporterError.prototype.rethrow = function rethrow(msg) { - this.message = msg + ' at: ' + (this.path || '(shallow)'); - if (Error.captureStackTrace) - Error.captureStackTrace(this, ReporterError); + var values = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); - if (!this.stack) { - try { - // IE only adds stack when thrown - throw new Error(this.message); - } catch (e) { - this.stack = e.stack; + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value, i) { + self.resolve(value).then(resolveFromAll, function (error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values[i] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values); + } } } - return this; -}; +} -},{"97":97}],9:[function(require,module,exports){ -var constants = require(10); +Promise.race = race; +function race(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== '[object Array]') { + return this.reject(new TypeError('must be an array')); + } -exports.tagClass = { - 0: 'universal', - 1: 'application', - 2: 'context', - 3: 'private' -}; -exports.tagClassByName = constants._reverse(exports.tagClass); + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } -exports.tag = { - 0x00: 'end', - 0x01: 'bool', - 0x02: 'int', - 0x03: 'bitstr', - 0x04: 'octstr', - 0x05: 'null_', - 0x06: 'objid', - 0x07: 'objDesc', - 0x08: 'external', - 0x09: 'real', - 0x0a: 'enum', - 0x0b: 'embed', - 0x0c: 'utf8str', - 0x0d: 'relativeOid', - 0x10: 'seq', - 0x11: 'set', - 0x12: 'numstr', - 0x13: 'printstr', - 0x14: 't61str', - 0x15: 'videostr', - 0x16: 'ia5str', - 0x17: 'utctime', - 0x18: 'gentime', - 0x19: 'graphstr', - 0x1a: 'iso646str', - 0x1b: 'genstr', - 0x1c: 'unistr', - 0x1d: 'charstr', - 0x1e: 'bmpstr' -}; -exports.tagByName = constants._reverse(exports.tag); + var i = -1; + var promise = new this(INTERNAL); -},{"10":10}],10:[function(require,module,exports){ -var constants = exports; + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value) { + self.resolve(value).then(function (response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function (error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } +} -// Helper -constants._reverse = function reverse(map) { - var res = {}; +},{"109":109}],5:[function(require,module,exports){ +'use strict'; - Object.keys(map).forEach(function(key) { - // Convert key to integer if it is stringified - if ((key | 0) == key) - key = key | 0; +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - var value = map[key]; - res[value] = key; - }); +var lie = _interopDefault(require(4)); - return res; -}; +/* istanbul ignore next */ +var PouchPromise = typeof Promise === 'function' ? Promise : lie; -constants.der = require(9); +module.exports = PouchPromise; -},{"9":9}],11:[function(require,module,exports){ -var inherits = require(97); +},{"4":4}],6:[function(require,module,exports){ +'use strict'; -var asn1 = require(3); -var base = asn1.base; -var bignum = asn1.bignum; +module.exports = argsArray; -// Import DER constants -var der = asn1.constants.der; +function argsArray(fun) { + return function () { + var len = arguments.length; + if (len) { + var args = []; + var i = -1; + while (++i < len) { + args[i] = arguments[i]; + } + return fun.call(this, args); + } else { + return fun.call(this, []); + } + }; +} +},{}],7:[function(require,module,exports){ +var asn1 = exports; -function DERDecoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; +asn1.bignum = require(22); - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -}; -module.exports = DERDecoder; +asn1.define = require(8).define; +asn1.base = require(10); +asn1.constants = require(14); +asn1.decoders = require(16); +asn1.encoders = require(19); -DERDecoder.prototype.decode = function decode(data, options) { - if (!(data instanceof base.DecoderBuffer)) - data = new base.DecoderBuffer(data, options); +},{"10":10,"14":14,"16":16,"19":19,"22":22,"8":8}],8:[function(require,module,exports){ +var asn1 = require(7); +var inherits = require(111); - return this.tree._decode(data, options); +var api = exports; + +api.define = function define(name, body) { + return new Entity(name, body); }; -// Tree methods +function Entity(name, body) { + this.name = name; + this.body = body; -function DERNode(parent) { - base.Node.call(this, 'der', parent); -} -inherits(DERNode, base.Node); + this.decoders = {}; + this.encoders = {}; +}; -DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { - if (buffer.isEmpty()) - return false; +Entity.prototype._createNamed = function createNamed(base) { + var named; + try { + named = require(196).runInThisContext( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; + } + inherits(named, base); + named.prototype._initNamed = function initnamed(entity) { + base.call(this, entity); + }; - var state = buffer.save(); - var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; + return new named(this); +}; - buffer.restore(state); +Entity.prototype._getDecoder = function _getDecoder(enc) { + enc = enc || 'der'; + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(asn1.decoders[enc]); + return this.decoders[enc]; +}; - return decodedTag.tag === tag || decodedTag.tagStr === tag || - (decodedTag.tagStr + 'of') === tag || any; +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); }; -DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { - var decodedTag = derDecodeTag(buffer, - 'Failed to decode tag of "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; +Entity.prototype._getEncoder = function _getEncoder(enc) { + enc = enc || 'der'; + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(asn1.encoders[enc]); + return this.encoders[enc]; +}; - var len = derDecodeLen(buffer, - decodedTag.primitive, - 'Failed to get length of "' + tag + '"'); +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; - // Failure - if (buffer.isError(len)) - return len; +},{"111":111,"196":196,"7":7}],9:[function(require,module,exports){ +var inherits = require(111); +var Reporter = require(10).Reporter; +var Buffer = require(54).Buffer; - if (!any && - decodedTag.tag !== tag && - decodedTag.tagStr !== tag && - decodedTag.tagStr + 'of' !== tag) { - return buffer.error('Failed to match tag: "' + tag + '"'); +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; } - if (decodedTag.primitive || len !== null) - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); - - // Indefinite length... find END tag - var state = buffer.save(); - var res = this._skipUntilEnd( - buffer, - 'Failed to skip indefinite length body: "' + this.tag + '"'); - if (buffer.isError(res)) - return res; + this.base = base; + this.offset = 0; + this.length = base.length; +} +inherits(DecoderBuffer, Reporter); +exports.DecoderBuffer = DecoderBuffer; - len = buffer.offset - state.offset; - buffer.restore(state); - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; }; -DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { - while (true) { - var tag = derDecodeTag(buffer, fail); - if (buffer.isError(tag)) - return tag; - var len = derDecodeLen(buffer, tag.primitive, fail); - if (buffer.isError(len)) - return len; - - var res; - if (tag.primitive || len !== null) - res = buffer.skip(len) - else - res = this._skipUntilEnd(buffer, fail); +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; - // Failure - if (buffer.isError(res)) - return res; + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); - if (tag.tagStr === 'end') - break; - } + return res; }; -DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, - options) { - var result = []; - while (!buffer.isEmpty()) { - var possibleEnd = this._peekTag(buffer, 'end'); - if (buffer.isError(possibleEnd)) - return possibleEnd; - - var res = decoder.decode(buffer, 'der', options); - if (buffer.isError(res) && possibleEnd) - break; - result.push(res); - } - return result; +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; }; -DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { - if (tag === 'bitstr') { - var unused = buffer.readUInt8(); - if (buffer.isError(unused)) - return unused; - return { unused: unused, data: buffer.raw() }; - } else if (tag === 'bmpstr') { - var raw = buffer.raw(); - if (raw.length % 2 === 1) - return buffer.error('Decoding of string type: bmpstr length mismatch'); +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +} - var str = ''; - for (var i = 0; i < raw.length / 2; i++) { - str += String.fromCharCode(raw.readUInt16BE(i * 2)); - } - return str; - } else if (tag === 'numstr') { - var numstr = buffer.raw().toString('ascii'); - if (!this._isNumstr(numstr)) { - return buffer.error('Decoding of string type: ' + - 'numstr unsupported characters'); - } - return numstr; - } else if (tag === 'octstr') { - return buffer.raw(); - } else if (tag === 'objDesc') { - return buffer.raw(); - } else if (tag === 'printstr') { - var printstr = buffer.raw().toString('ascii'); - if (!this._isPrintstr(printstr)) { - return buffer.error('Decoding of string type: ' + - 'printstr unsupported characters'); - } - return printstr; - } else if (/str$/.test(tag)) { - return buffer.raw().toString(); - } else { - return buffer.error('Decoding of string type: ' + tag + ' unsupported'); - } -}; +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); -DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { - var result; - var identifiers = []; - var ident = 0; - while (!buffer.isEmpty()) { - var subident = buffer.readUInt8(); - ident <<= 7; - ident |= subident & 0x7f; - if ((subident & 0x80) === 0) { - identifiers.push(ident); - ident = 0; - } - } - if (subident & 0x80) - identifiers.push(ident); + var res = new DecoderBuffer(this.base); - var first = (identifiers[0] / 40) | 0; - var second = identifiers[0] % 40; + // Share reporter state + res._reporterState = this._reporterState; - if (relative) - result = identifiers; - else - result = [first, second].concat(identifiers.slice(1)); - - if (values) { - var tmp = values[result.join(' ')]; - if (tmp === undefined) - tmp = values[result.join('.')]; - if (tmp !== undefined) - result = tmp; - } + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +} - return result; -}; +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} -DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { - var str = buffer.raw().toString(); - if (tag === 'gentime') { - var year = str.slice(0, 4) | 0; - var mon = str.slice(4, 6) | 0; - var day = str.slice(6, 8) | 0; - var hour = str.slice(8, 10) | 0; - var min = str.slice(10, 12) | 0; - var sec = str.slice(12, 14) | 0; - } else if (tag === 'utctime') { - var year = str.slice(0, 2) | 0; - var mon = str.slice(2, 4) | 0; - var day = str.slice(4, 6) | 0; - var hour = str.slice(6, 8) | 0; - var min = str.slice(8, 10) | 0; - var sec = str.slice(10, 12) | 0; - if (year < 70) - year = 2000 + year; - else - year = 1900 + year; +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; } else { - return buffer.error('Decoding ' + tag + ' time is not supported yet'); + return reporter.error('Unsupported type: ' + typeof value); } +} +exports.EncoderBuffer = EncoderBuffer; - return Date.UTC(year, mon - 1, day, hour, min, sec, 0); -}; - -DERNode.prototype._decodeNull = function decodeNull(buffer) { - return null; -}; - -DERNode.prototype._decodeBool = function decodeBool(buffer) { - var res = buffer.readUInt8(); - if (buffer.isError(res)) - return res; - else - return res !== 0; -}; +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; -DERNode.prototype._decodeInt = function decodeInt(buffer, values) { - // Bigint, return as it is (assume big endian) - var raw = buffer.raw(); - var res = new bignum(raw); + if (this.length === 0) + return out; - if (values) - res = values[res.toString(10)] || res; + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } - return res; + return out; }; -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getDecoder('der').tree; -}; +},{"10":10,"111":111,"54":54}],10:[function(require,module,exports){ +var base = exports; -// Utility methods +base.Reporter = require(12).Reporter; +base.DecoderBuffer = require(9).DecoderBuffer; +base.EncoderBuffer = require(9).EncoderBuffer; +base.Node = require(11); -function derDecodeTag(buf, fail) { - var tag = buf.readUInt8(fail); - if (buf.isError(tag)) - return tag; +},{"11":11,"12":12,"9":9}],11:[function(require,module,exports){ +var Reporter = require(10).Reporter; +var EncoderBuffer = require(10).EncoderBuffer; +var DecoderBuffer = require(10).DecoderBuffer; +var assert = require(121); - var cls = der.tagClass[tag >> 6]; - var primitive = (tag & 0x20) === 0; +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +]; - // Multi-octet tag - load - if ((tag & 0x1f) === 0x1f) { - var oct = tag; - tag = 0; - while ((oct & 0x80) === 0x80) { - oct = buf.readUInt8(fail); - if (buf.isError(oct)) - return oct; +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); - tag <<= 7; - tag |= oct & 0x7f; - } - } else { - tag &= 0x1f; - } - var tagStr = der.tag[tag]; +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', - return { - cls: cls, - primitive: primitive, - tag: tag, - tagStr: tagStr - }; -} + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; -function derDecodeLen(buf, primitive, fail) { - var len = buf.readUInt8(fail); - if (buf.isError(len)) - return len; +function Node(enc, parent) { + var state = {}; + this._baseState = state; - // Indefinite form - if (!primitive && len === 0x80) - return null; + state.enc = enc; - // Definite form - if ((len & 0x80) === 0) { - // Short form - return len; - } + state.parent = parent || null; + state.children = null; - // Long form - var num = len & 0x7f; - if (num > 4) - return buf.error('length octect is too long'); + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; - len = 0; - for (var i = 0; i < num; i++) { - len <<= 8; - var j = buf.readUInt8(fail); - if (buf.isError(j)) - return j; - len |= j; + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); } - - return len; } +module.exports = Node; -},{"3":3,"97":97}],12:[function(require,module,exports){ -var decoders = exports; - -decoders.der = require(11); -decoders.pem = require(13); - -},{"11":11,"13":13}],13:[function(require,module,exports){ -var inherits = require(97); -var Buffer = require(47).Buffer; +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit', 'contains' +]; -var DERDecoder = require(11); +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; -function PEMDecoder(entity) { - DERDecoder.call(this, entity); - this.enc = 'pem'; +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); }; -inherits(PEMDecoder, DERDecoder); -module.exports = PEMDecoder; -PEMDecoder.prototype.decode = function decode(data, options) { - var lines = data.toString().split(/[\r\n]+/g); +Node.prototype._init = function init(body) { + var state = this._baseState; - var label = options.label.toUpperCase(); + assert(state.parent === null); + body.call(this); - var re = /^-----(BEGIN|END) ([^-]+)-----$/; - var start = -1; - var end = -1; - for (var i = 0; i < lines.length; i++) { - var match = lines[i].match(re); - if (match === null) - continue; + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; - if (match[2] !== label) - continue; +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; - if (start === -1) { - if (match[1] !== 'BEGIN') - break; - start = i; - } else { - if (match[1] !== 'END') - break; - end = i; - break; - } - } - if (start === -1 || end === -1) - throw new Error('PEM section not found for: ' + label); + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); - var base64 = lines.slice(start + 1, end).join(''); - // Remove excessive symbols - base64.replace(/[^a-z0-9\+\/=]+/gi, ''); + if (children.length !== 0) { + assert(state.children === null); + state.children = children; - var input = new Buffer(base64, 'base64'); - return DERDecoder.prototype.decode.call(this, input, options); + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } }; -},{"11":11,"47":47,"97":97}],14:[function(require,module,exports){ -var inherits = require(97); -var Buffer = require(47).Buffer; +// +// Overrided methods +// -var asn1 = require(3); -var base = asn1.base; +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); -// Import DER constants -var der = asn1.constants.der; +// +// Public methods +// -function DEREncoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -}; -module.exports = DEREncoder; + assert(state.tag === null); + state.tag = tag; -DEREncoder.prototype.encode = function encode(data, reporter) { - return this.tree._encode(data, reporter).join(); -}; + this._useArgs(args); -// Tree methods + return this; + }; +}); -function DERNode(parent) { - base.Node.call(this, 'der', parent); -} -inherits(DERNode, base.Node); +Node.prototype.use = function use(item) { + assert(item); + var state = this._baseState; -DERNode.prototype._encodeComposite = function encodeComposite(tag, - primitive, - cls, - content) { - var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + assert(state.use === null); + state.use = item; - // Short form - if (content.length < 0x80) { - var header = new Buffer(2); - header[0] = encodedTag; - header[1] = content.length; - return this._createEncoderBuffer([ header, content ]); - } + return this; +}; - // Long form - // Count octets required to store length - var lenOctets = 1; - for (var i = content.length; i >= 0x100; i >>= 8) - lenOctets++; +Node.prototype.optional = function optional() { + var state = this._baseState; - var header = new Buffer(1 + 1 + lenOctets); - header[0] = encodedTag; - header[1] = 0x80 | lenOctets; + state.optional = true; - for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) - header[i] = j & 0xff; + return this; +}; - return this._createEncoderBuffer([ header, content ]); +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; }; -DERNode.prototype._encodeStr = function encodeStr(str, tag) { - if (tag === 'bitstr') { - return this._createEncoderBuffer([ str.unused | 0, str.data ]); - } else if (tag === 'bmpstr') { - var buf = new Buffer(str.length * 2); - for (var i = 0; i < str.length; i++) { - buf.writeUInt16BE(str.charCodeAt(i), i * 2); - } - return this._createEncoderBuffer(buf); - } else if (tag === 'numstr') { - if (!this._isNumstr(str)) { - return this.reporter.error('Encoding of string type: numstr supports ' + - 'only digits and space'); - } - return this._createEncoderBuffer(str); - } else if (tag === 'printstr') { - if (!this._isPrintstr(str)) { - return this.reporter.error('Encoding of string type: printstr supports ' + - 'only latin upper and lower case letters, ' + - 'digits, space, apostrophe, left and rigth ' + - 'parenthesis, plus sign, comma, hyphen, ' + - 'dot, slash, colon, equal sign, ' + - 'question mark'); - } - return this._createEncoderBuffer(str); - } else if (/str$/.test(tag)) { - return this._createEncoderBuffer(str); - } else if (tag === 'objDesc') { - return this._createEncoderBuffer(str); - } else { - return this.reporter.error('Encoding of string type: ' + tag + - ' unsupported'); - } +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; }; -DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { - if (typeof id === 'string') { - if (!values) - return this.reporter.error('string objid given, but no values map found'); - if (!values.hasOwnProperty(id)) - return this.reporter.error('objid not found in values map'); - id = values[id].split(/[\s\.]+/g); - for (var i = 0; i < id.length; i++) - id[i] |= 0; - } else if (Array.isArray(id)) { - id = id.slice(); - for (var i = 0; i < id.length; i++) - id[i] |= 0; - } +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; - if (!Array.isArray(id)) { - return this.reporter.error('objid() should be either array or string, ' + - 'got: ' + JSON.stringify(id)); - } + assert(state.explicit === null && state.implicit === null); + state.implicit = num; - if (!relative) { - if (id[1] >= 40) - return this.reporter.error('Second objid identifier OOB'); - id.splice(0, 2, id[0] * 40 + id[1]); - } + return this; +}; - // Count number of octets - var size = 0; - for (var i = 0; i < id.length; i++) { - var ident = id[i]; - for (size++; ident >= 0x80; ident >>= 7) - size++; - } +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); - var objid = new Buffer(size); - var offset = objid.length - 1; - for (var i = id.length - 1; i >= 0; i--) { - var ident = id[i]; - objid[offset--] = ident & 0x7f; - while ((ident >>= 7) > 0) - objid[offset--] = 0x80 | (ident & 0x7f); - } + state.obj = true; - return this._createEncoderBuffer(objid); + if (args.length !== 0) + this._useArgs(args); + + return this; }; -function two(num) { - if (num < 10) - return '0' + num; - else - return num; -} +Node.prototype.key = function key(newKey) { + var state = this._baseState; -DERNode.prototype._encodeTime = function encodeTime(time, tag) { - var str; - var date = new Date(time); + assert(state.key === null); + state.key = newKey; - if (tag === 'gentime') { - str = [ - two(date.getFullYear()), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else if (tag === 'utctime') { - str = [ - two(date.getFullYear() % 100), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else { - this.reporter.error('Encoding ' + tag + ' time is not supported yet'); - } - - return this._encodeStr(str, 'octstr'); -}; - -DERNode.prototype._encodeNull = function encodeNull() { - return this._createEncoderBuffer(''); + return this; }; -DERNode.prototype._encodeInt = function encodeInt(num, values) { - if (typeof num === 'string') { - if (!values) - return this.reporter.error('String int or enum given, but no values map'); - if (!values.hasOwnProperty(num)) { - return this.reporter.error('Values map doesn\'t contain: ' + - JSON.stringify(num)); - } - num = values[num]; - } - - // Bignum, assume big endian - if (typeof num !== 'number' && !Buffer.isBuffer(num)) { - var numArray = num.toArray(); - if (!num.sign && numArray[0] & 0x80) { - numArray.unshift(0); - } - num = new Buffer(numArray); - } +Node.prototype.any = function any() { + var state = this._baseState; - if (Buffer.isBuffer(num)) { - var size = num.length; - if (num.length === 0) - size++; + state.any = true; - var out = new Buffer(size); - num.copy(out); - if (num.length === 0) - out[0] = 0 - return this._createEncoderBuffer(out); - } + return this; +}; - if (num < 0x80) - return this._createEncoderBuffer(num); +Node.prototype.choice = function choice(obj) { + var state = this._baseState; - if (num < 0x100) - return this._createEncoderBuffer([0, num]); + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); - var size = 1; - for (var i = num; i >= 0x100; i >>= 8) - size++; + return this; +}; - var out = new Array(size); - for (var i = out.length - 1; i >= 0; i--) { - out[i] = num & 0xff; - num >>= 8; - } - if(out[0] & 0x80) { - out.unshift(0); - } +Node.prototype.contains = function contains(item) { + var state = this._baseState; - return this._createEncoderBuffer(new Buffer(out)); -}; + assert(state.use === null); + state.contains = item; -DERNode.prototype._encodeBool = function encodeBool(value) { - return this._createEncoderBuffer(value ? 0xff : 0); + return this; }; -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getEncoder('der').tree; -}; +// +// Decoding +// -DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { +Node.prototype._decode = function decode(input, options) { var state = this._baseState; - var i; - if (state['default'] === null) - return false; - var data = dataBuffer.join(); - if (state.defaultBuffer === undefined) - state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input, options)); - if (data.length !== state.defaultBuffer.length) - return false; + var result = state['default']; + var present = true; - for (i=0; i < data.length; i++) - if (data[i] !== state.defaultBuffer[i]) - return false; + var prevKey = null; + if (state.key !== null) + prevKey = input.enterKey(state.key); - return true; -}; + // Check if tag is there + if (state.optional) { + var tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; -// Utility methods + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); -function encodeTag(tag, primitive, cls, reporter) { - var res; + if (input.isError(present)) + return present; + } + } - if (tag === 'seqof') - tag = 'seq'; - else if (tag === 'setof') - tag = 'set'; + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); - if (der.tagByName.hasOwnProperty(tag)) - res = der.tagByName[tag]; - else if (typeof tag === 'number' && (tag | 0) === tag) - res = tag; - else - return reporter.error('Unknown tag: ' + tag); + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } - if (res >= 0x1f) - return reporter.error('Multi-octet tag encoding unsupported'); + var start = input.offset; - if (!primitive) - res |= 0x20; + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; - res |= (der.tagClassByName[cls || 'universal'] << 6); + if (state.any) + result = input.raw(save); + else + input = body; + } - return res; -} + if (options && options.track && state.tag !== null) + options.track(input.path(), start, input.length, 'tagged'); -},{"3":3,"47":47,"97":97}],15:[function(require,module,exports){ -var encoders = exports; + if (options && options.track && state.tag !== null) + options.track(input.path(), input.offset, input.length, 'content'); -encoders.der = require(14); -encoders.pem = require(16); + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input, options); + else + result = this._decodeChoice(input, options); -},{"14":14,"16":16}],16:[function(require,module,exports){ -var inherits = require(97); + if (input.isError(result)) + return result; -var DEREncoder = require(14); + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options); + }); + } -function PEMEncoder(entity) { - DEREncoder.call(this, entity); - this.enc = 'pem'; -}; -inherits(PEMEncoder, DEREncoder); -module.exports = PEMEncoder; + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj) + ._decode(data, options); + } + } -PEMEncoder.prototype.encode = function encode(data, options) { - var buf = DEREncoder.prototype.encode.call(this, data); + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); - var p = buf.toString('base64'); - var out = [ '-----BEGIN ' + options.label + '-----' ]; - for (var i = 0; i < p.length; i += 64) - out.push(p.slice(i, i + 64)); - out.push('-----END ' + options.label + '-----'); - return out.join('\n'); -}; + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + else if (prevKey !== null) + input.exitKey(prevKey); -},{"14":14,"97":97}],17:[function(require,module,exports){ -var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -;(function (exports) { - 'use strict'; - - var Arr = (typeof Uint8Array !== 'undefined') - ? Uint8Array - : Array - - var PLUS = '+'.charCodeAt(0) - var SLASH = '/'.charCodeAt(0) - var NUMBER = '0'.charCodeAt(0) - var LOWER = 'a'.charCodeAt(0) - var UPPER = 'A'.charCodeAt(0) - var PLUS_URL_SAFE = '-'.charCodeAt(0) - var SLASH_URL_SAFE = '_'.charCodeAt(0) + return result; +}; - function decode (elt) { - var code = elt.charCodeAt(0) - if (code === PLUS || - code === PLUS_URL_SAFE) - return 62 // '+' - if (code === SLASH || - code === SLASH_URL_SAFE) - return 63 // '/' - if (code < NUMBER) - return -1 //no match - if (code < NUMBER + 10) - return code - NUMBER + 26 + 26 - if (code < UPPER + 26) - return code - UPPER - if (code < LOWER + 26) - return code - LOWER + 26 - } +Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { + var state = this._baseState; - function b64ToByteArray (b64) { - var i, j, l, tmp, placeHolders, arr + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + return this._decodeStr(input, tag, options); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0], options); - if (b64.length % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj) + ._decode(input, options); + } else { + return input.error('unknown tag: ' + tag); + } +}; - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - var len = b64.length - placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 +Node.prototype._getUse = function _getUse(entity, obj) { - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(b64.length * 3 / 4 - placeHolders) + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length +Node.prototype._decodeChoice = function decodeChoice(input, options) { + var state = this._baseState; + var result = null; + var match = false; - var L = 0 + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input, options); + if (input.isError(value)) + return false; - function push (v) { - arr[L++] = v - } + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) - push((tmp & 0xFF0000) >> 16) - push((tmp & 0xFF00) >> 8) - push(tmp & 0xFF) - } + if (!match) + return input.error('Choice not matched'); - if (placeHolders === 2) { - tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) - push(tmp & 0xFF) - } else if (placeHolders === 1) { - tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) - push((tmp >> 8) & 0xFF) - push(tmp & 0xFF) - } + return result; +}; - return arr - } +// +// Encoding +// - function uint8ToBase64 (uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; - function encode (num) { - return lookup.charAt(num) - } +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; - function tripletToBase64 (num) { - return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) - } + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output += tripletToBase64(temp) - } + if (this._skipDefault(result, reporter, parent)) + return; - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1] - output += encode(temp >> 2) - output += encode((temp << 4) & 0x3F) - output += '==' - break - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) - output += encode(temp >> 10) - output += encode((temp >> 4) & 0x3F) - output += encode((temp << 2) & 0x3F) - output += '=' - break - } + return result; +}; - return output - } +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; - exports.toByteArray = b64ToByteArray - exports.fromByteArray = uint8ToBase64 -}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); -},{}],18:[function(require,module,exports){ -(function (module, exports) { - 'use strict'; + var result = null; - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } + // Set reporter to share it with a child class + this.reporter = reporter; - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; } - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); - this.negative = 0; - this.words = null; - this.length = 0; + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); - // Reduction context - this.red = null; + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); } else { - exports.BN = BN; - } + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); - BN.BN = BN; - BN.wordSize = 26; + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); - var Buffer; - try { - Buffer = require('buf' + 'fer').Buffer; - } catch (e) { - } + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; } + } - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be omitted only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } + return result; +}; - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + else + throw new Error('Unsupported tag: ' + tag); +}; - if (number[0] === '-') { - this.negative = 1; - } +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; - this.strip(); +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); +}; - if (endian !== 'le') return; +},{"10":10,"121":121}],12:[function(require,module,exports){ +var inherits = require(111); - this._initArray(this.toArray(), base, endian); +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] }; +} +exports.Reporter = Reporter; - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; - if (endian !== 'le') return; +Reporter.prototype.save = function save() { + var state = this._reporterState; - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; + return { obj: state.obj, pathLen: state.path.length }; +}; - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; +Reporter.prototype.exitKey = function exitKey(index) { + var state = this._reporterState; - r <<= 4; + state.path = state.path.slice(0, index - 1); +}; - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; + this.exitKey(index); + if (state.obj !== null) + state.obj[key] = value; +}; - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; - } +Reporter.prototype.path = function path() { + return this._reporterState.path.join('/'); +}; - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); - }; +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; + var prev = state.obj; + state.obj = {}; + return prev; +}; - r *= mul; +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; + var now = state.obj; + state.obj = prev; + return now; +}; - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; - // '0' - '9' - } else { - r += c; - } - } - return r; + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); } - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; + if (!state.options.partial) + throw err; - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + if (!inherited) + state.errors.push(err); - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; + return err; +}; - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +inherits(ReporterError, Error); - for (i = 0; i < mod; i++) { - pow *= base; - } +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + if (Error.captureStackTrace) + Error.captureStackTrace(this, ReporterError); - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; } - }; + } + return this; +}; - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; +},{"111":111}],13:[function(require,module,exports){ +var constants = require(14); - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; +},{"14":14}],14:[function(require,module,exports){ +var constants = exports; - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; +// Helper +constants._reverse = function reverse(map) { + var res = {}; - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; - /* + var value = map[key]; + res[value] = key; + }); - var zeros = []; - var groupSizes = []; - var groupBases = []; + return res; +}; - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } +constants.der = require(13); - */ +},{"13":13}],15:[function(require,module,exports){ +var inherits = require(111); - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; +var asn1 = require(7); +var base = asn1.base; +var bignum = asn1.bignum; - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; +// Import DER constants +var der = asn1.constants.der; - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); - assert(false, 'Base should be between 2 and 36'); - }; + return this.tree._decode(data, options); +}; - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; +// Tree methods - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); + buffer.restore(state); - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + // Failure + if (buffer.isError(len)) + return len; - res[i] = b; - } + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } - for (; i < reqLength; i++) { - res[i] = 0; - } - } + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + // Indefinite length... find END tag + var state = buffer.save(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); - function toBitArray (num) { - var w = new Array(num.bitLength()); + // Failure + if (buffer.isError(res)) + return res; - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + if (tag.tagStr === 'end') + break; + } +}; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, + options) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; - return w; + var res = decoder.decode(buffer, 'der', options); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); } + return result; +}; - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; + var str = ''; + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); } - return this.clone(); - }; + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; } - return this.clone(); - }; + } + if (subident & 0x80) + identifiers.push(ident); - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } - return this; - }; + return result; +}; - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; - return this.strip(); - }; +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; + if (values) + res = values[res.toString(10)] || res; - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } + return res; +}; - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; - this.length = b.length; +// Utility methods - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + tag <<= 7; + tag |= oct & 0x7f; } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; - this.length = a.length; - - return this.strip(); + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr }; +} - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; + // Indefinite form + if (!primitive && len === 0x80) + return null; - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + // Long form + var num = len & 0x7f; + if (num > 4) + return buf.error('length octect is too long'); - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); + return len; +} - if (bitsLeft > 0) { - bytesNeeded--; - } +},{"111":111,"7":7}],16:[function(require,module,exports){ +var decoders = exports; - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } +decoders.der = require(15); +decoders.pem = require(17); - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } +},{"15":15,"17":17}],17:[function(require,module,exports){ +var inherits = require(111); +var Buffer = require(54).Buffer; - // And remove leading zeroes - return this.strip(); - }; +var DERDecoder = require(15); - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); - var off = (bit / 26) | 0; - var wbit = bit % 26; + var label = options.label.toUpperCase(); - this._expand(off + 1); + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; - if (val) { - this.words[off] = this.words[off] | (1 << wbit); + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; } else { - this.words[off] = this.words[off] & ~(1 << wbit); + if (match[1] !== 'END') + break; + end = i; + break; } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; + var base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9\+\/=]+/gi, ''); - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } +},{"111":111,"15":15,"54":54}],18:[function(require,module,exports){ +var inherits = require(111); +var Buffer = require(54).Buffer; - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } +var asn1 = require(7); +var base = asn1.base; - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } +// Import DER constants +var der = asn1.constants.der; - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; - return this; - }; + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; - if (this.length > num.length) return this.clone().iadd(num); +// Tree methods - return num.clone().iadd(this); - }; +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } - // At this point both numbers are positive - var cmp = this.cmp(num); + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } +}; - this.length = Math.max(this.length, i); +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } - if (a !== this) { - this.negative = 1; - } + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } - return this.strip(); - }; + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; + return this._createEncoderBuffer(objid); +}; - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); } + num = values[num]; + } - return out.strip(); + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = new Buffer(numArray); } - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(new Buffer(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; + + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} + +},{"111":111,"54":54,"7":7}],19:[function(require,module,exports){ +var encoders = exports; + +encoders.der = require(18); +encoders.pem = require(20); + +},{"18":18,"20":20}],20:[function(require,module,exports){ +var inherits = require(111); + +var DEREncoder = require(18); + +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; + +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); + + var p = buf.toString('base64'); + var out = [ '-----BEGIN ' + options.label + '-----' ]; + for (var i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; + +},{"111":111,"18":18}],21:[function(require,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +;(function (exports) { + 'use strict'; + + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array + + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + var PLUS_URL_SAFE = '-'.charCodeAt(0) + var SLASH_URL_SAFE = '_'.charCodeAt(0) + + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS || + code === PLUS_URL_SAFE) + return 62 // '+' + if (code === SLASH || + code === SLASH_URL_SAFE) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } + + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length + + var L = 0 + + function push (v) { + arr[L++] = v + } + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } + + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } + + return arr + } + + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length + + function encode (num) { + return lookup.charAt(num) + } + + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } + + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } + + return output + } + + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + +},{}],22:[function(require,module,exports){ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require(24).Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; var o = out.words; var c = 0; var lo; @@ -5260,7 +6679,7 @@ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; }; Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1); + if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; @@ -5399,7 +6818,7 @@ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; }; })(typeof module === 'undefined' || module, this); -},{}],19:[function(require,module,exports){ +},{"24":24}],23:[function(require,module,exports){ var r; module.exports = function rand(len) { @@ -5418,6 +6837,17 @@ Rand.prototype.generate = function generate(len) { return this._rand(len); }; +// Emulate crypto API using randy +Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); + + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; +}; + if (typeof self === 'object') { if (self.crypto && self.crypto.getRandomValues) { // Modern browsers @@ -5433,7 +6863,9 @@ if (typeof self === 'object') { self.msCrypto.getRandomValues(arr); return arr; }; - } else { + + // Safari's WebWorkers do not have `crypto` + } else if (typeof window === 'object') { // Old junk Rand.prototype._rand = function() { throw new Error('Not implemented yet'); @@ -5442,88 +6874,129 @@ if (typeof self === 'object') { } else { // Node.js or Web worker with no crypto support try { - var crypto = require(20); + var crypto = require(24); + if (typeof crypto.randomBytes !== 'function') + throw new Error('Not supported'); Rand.prototype._rand = function _rand(n) { return crypto.randomBytes(n); }; } catch (e) { - // Emulate crypto API using randy - Rand.prototype._rand = function _rand(n) { - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; - }; } } -},{"20":20}],20:[function(require,module,exports){ +},{"24":24}],24:[function(require,module,exports){ -},{}],21:[function(require,module,exports){ -(function (Buffer){ +},{}],25:[function(require,module,exports){ // based on the aes implimentation in triple sec // https://github.com/keybase/triplesec +// which is in turn based on the one from crypto-js +// https://code.google.com/p/crypto-js/ + +var Buffer = require(161).Buffer + +function asUInt32Array (buf) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + + var len = (buf.length / 4) | 0 + var out = new Array(len) -// which is in turn based on the one from crypto-js -// https://code.google.com/p/crypto-js/ + for (var i = 0; i < len; i++) { + out[i] = buf.readUInt32BE(i * 4) + } -var uint_max = Math.pow(2, 32) -function fixup_uint32 (x) { - var ret, x_pos - ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x - return ret + return out } -function scrub_vec (v) { + +function scrubVec (v) { for (var i = 0; i < v.length; v++) { v[i] = 0 } - return false } -function Global () { - this.SBOX = [] - this.INV_SBOX = [] - this.SUB_MIX = [[], [], [], []] - this.INV_SUB_MIX = [[], [], [], []] - this.init() - this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] -} +function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { + var SUB_MIX0 = SUB_MIX[0] + var SUB_MIX1 = SUB_MIX[1] + var SUB_MIX2 = SUB_MIX[2] + var SUB_MIX3 = SUB_MIX[3] -Global.prototype.init = function () { - var d, i, sx, t, x, x2, x4, x8, xi, _i - d = (function () { - var _i, _results - _results = [] - for (i = _i = 0; _i < 256; i = ++_i) { - if (i < 128) { - _results.push(i << 1) - } else { - _results.push((i << 1) ^ 0x11b) - } + var s0 = M[0] ^ keySchedule[0] + var s1 = M[1] ^ keySchedule[1] + var s2 = M[2] ^ keySchedule[2] + var s3 = M[3] ^ keySchedule[3] + var t0, t1, t2, t3 + var ksRow = 4 + + for (var round = 1; round < nRounds; round++) { + t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] + t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] + t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + s2 = t2 + s3 = t3 + } + + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] + t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] + t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + t0 = t0 >>> 0 + t1 = t1 >>> 0 + t2 = t2 >>> 0 + t3 = t3 >>> 0 + + return [t0, t1, t2, t3] +} + +// AES constants +var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] +var G = (function () { + // Compute double table + var d = new Array(256) + for (var j = 0; j < 256; j++) { + if (j < 128) { + d[j] = j << 1 + } else { + d[j] = (j << 1) ^ 0x11b } - return _results - })() - x = 0 - xi = 0 - for (i = _i = 0; _i < 256; i = ++_i) { - sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + } + + var SBOX = [] + var INV_SBOX = [] + var SUB_MIX = [[], [], [], []] + var INV_SUB_MIX = [[], [], [], []] + + // Walk GF(2^8) + var x = 0 + var xi = 0 + for (var i = 0; i < 256; ++i) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 - this.SBOX[x] = sx - this.INV_SBOX[sx] = x - x2 = d[x] - x4 = d[x2] - x8 = d[x4] - t = (d[sx] * 0x101) ^ (sx * 0x1010100) - this.SUB_MIX[0][x] = (t << 24) | (t >>> 8) - this.SUB_MIX[1][x] = (t << 16) | (t >>> 16) - this.SUB_MIX[2][x] = (t << 8) | (t >>> 24) - this.SUB_MIX[3][x] = t + SBOX[x] = sx + INV_SBOX[sx] = x + + // Compute multiplication + var x2 = d[x] + var x4 = d[x2] + var x8 = d[x4] + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100) + SUB_MIX[0][x] = (t << 24) | (t >>> 8) + SUB_MIX[1][x] = (t << 16) | (t >>> 16) + SUB_MIX[2][x] = (t << 8) | (t >>> 24) + SUB_MIX[3][x] = t + + // Compute inv sub bytes, inv mix columns tables t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) - this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) - this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) - this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) - this.INV_SUB_MIX[3][sx] = t + INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) + INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) + INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) + INV_SUB_MIX[3][sx] = t + if (x === 0) { x = xi = 1 } else { @@ -5531,56 +7004,87 @@ Global.prototype.init = function () { xi ^= d[d[xi]] } } - return true -} -var G = new Global() + return { + SBOX: SBOX, + INV_SBOX: INV_SBOX, + SUB_MIX: SUB_MIX, + INV_SUB_MIX: INV_SUB_MIX + } +})() + +function AES (key) { + this._key = asUInt32Array(key) + this._reset() +} AES.blockSize = 4 * 4 - +AES.keySize = 256 / 8 AES.prototype.blockSize = AES.blockSize +AES.prototype.keySize = AES.keySize +AES.prototype._reset = function () { + var keyWords = this._key + var keySize = keyWords.length + var nRounds = keySize + 6 + var ksRows = (nRounds + 1) * 4 -AES.keySize = 256 / 8 + var keySchedule = [] + for (var k = 0; k < keySize; k++) { + keySchedule[k] = keyWords[k] + } -AES.prototype.keySize = AES.keySize + for (k = keySize; k < ksRows; k++) { + var t = keySchedule[k - 1] -function bufferToArray (buf) { - var len = buf.length / 4 - var out = new Array(len) - var i = -1 - while (++i < len) { - out[i] = buf.readUInt32BE(i * 4) + if (k % keySize === 0) { + t = (t << 8) | (t >>> 24) + t = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (G.SBOX[(t >>> 8) & 0xff] << 8) | + (G.SBOX[t & 0xff]) + + t ^= RCON[(k / keySize) | 0] << 24 + } else if (keySize > 6 && k % keySize === 4) { + t = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (G.SBOX[(t >>> 8) & 0xff] << 8) | + (G.SBOX[t & 0xff]) + } + + keySchedule[k] = keySchedule[k - keySize] ^ t } - return out -} -function AES (key) { - this._key = bufferToArray(key) - this._doReset() -} - -AES.prototype._doReset = function () { - var invKsRow, keySize, keyWords, ksRow, ksRows, t - keyWords = this._key - keySize = keyWords.length - this._nRounds = keySize + 6 - ksRows = (this._nRounds + 1) * 4 - this._keySchedule = [] - for (ksRow = 0; ksRow < ksRows; ksRow++) { - this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t) - } - this._invKeySchedule = [] - for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { - ksRow = ksRows - invKsRow - t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)] - this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]] + + var invKeySchedule = [] + for (var ik = 0; ik < ksRows; ik++) { + var ksR = ksRows - ik + var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] + + if (ik < 4 || ksR <= 4) { + invKeySchedule[ik] = tt + } else { + invKeySchedule[ik] = + G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ + G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ + G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ + G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] + } } - return true + + this._nRounds = nRounds + this._keySchedule = keySchedule + this._invKeySchedule = invKeySchedule +} + +AES.prototype.encryptBlockRaw = function (M) { + M = asUInt32Array(M) + return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) } AES.prototype.encryptBlock = function (M) { - M = bufferToArray(new Buffer(M)) - var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX) - var buf = new Buffer(16) + var out = this.encryptBlockRaw(M) + var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0], 0) buf.writeUInt32BE(out[1], 4) buf.writeUInt32BE(out[2], 8) @@ -5589,12 +7093,15 @@ AES.prototype.encryptBlock = function (M) { } AES.prototype.decryptBlock = function (M) { - M = bufferToArray(new Buffer(M)) - var temp = [M[3], M[1]] - M[1] = temp[0] - M[3] = temp[1] - var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX) - var buf = new Buffer(16) + M = asUInt32Array(M) + + // swap + var m1 = M[1] + M[1] = M[3] + M[3] = m1 + + var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) + var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0], 0) buf.writeUInt32BE(out[3], 4) buf.writeUInt32BE(out[2], 8) @@ -5603,85 +7110,90 @@ AES.prototype.decryptBlock = function (M) { } AES.prototype.scrub = function () { - scrub_vec(this._keySchedule) - scrub_vec(this._invKeySchedule) - scrub_vec(this._key) -} - -AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) { - var ksRow, s0, s1, s2, s3, t0, t1, t2, t3 - - s0 = M[0] ^ keySchedule[0] - s1 = M[1] ^ keySchedule[1] - s2 = M[2] ^ keySchedule[2] - s3 = M[3] ^ keySchedule[3] - ksRow = 4 - for (var round = 1; round < this._nRounds; round++) { - t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++] - t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++] - t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++] - t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++] - s0 = t0 - s1 = t1 - s2 = t2 - s3 = t3 - } - t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] - t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] - t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] - t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] - return [ - fixup_uint32(t0), - fixup_uint32(t1), - fixup_uint32(t2), - fixup_uint32(t3) - ] + scrubVec(this._keySchedule) + scrubVec(this._invKeySchedule) + scrubVec(this._key) } -exports.AES = AES +module.exports.AES = AES -}).call(this,require(47).Buffer) -},{"47":47}],22:[function(require,module,exports){ -(function (Buffer){ -var aes = require(21) -var Transform = require(49) -var inherits = require(97) -var GHASH = require(26) -var xor = require(46) -inherits(StreamCipher, Transform) -module.exports = StreamCipher +},{"161":161}],26:[function(require,module,exports){ +var aes = require(25) +var Buffer = require(161).Buffer +var Transform = require(57) +var inherits = require(111) +var GHASH = require(30) +var xor = require(53) +var incr32 = require(31) -function StreamCipher (mode, key, iv, decrypt) { - if (!(this instanceof StreamCipher)) { - return new StreamCipher(mode, key, iv) +function xorTest (a, b) { + var out = 0 + if (a.length !== b.length) out++ + + var len = Math.min(a.length, b.length) + for (var i = 0; i < len; ++i) { + out += (a[i] ^ b[i]) + } + + return out +} + +function calcIv (self, iv, ck) { + if (iv.length === 12) { + self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) + return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) } + var ghash = new GHASH(ck) + var len = iv.length + var toPad = len % 16 + ghash.update(iv) + if (toPad) { + toPad = 16 - toPad + ghash.update(Buffer.alloc(toPad, 0)) + } + ghash.update(Buffer.alloc(8, 0)) + var ivBits = len * 8 + var tail = Buffer.alloc(8) + tail.writeUIntBE(ivBits, 0, 8) + ghash.update(tail) + self._finID = ghash.state + var out = Buffer.from(self._finID) + incr32(out) + return out +} +function StreamCipher (mode, key, iv, decrypt) { Transform.call(this) - this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])]) - iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])]) + + var h = Buffer.alloc(4, 0) + this._cipher = new aes.AES(key) - this._prev = new Buffer(iv.length) - this._cache = new Buffer('') - this._secCache = new Buffer('') + var ck = this._cipher.encryptBlock(h) + this._ghash = new GHASH(ck) + iv = calcIv(this, iv, ck) + + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) this._decrypt = decrypt this._alen = 0 this._len = 0 - iv.copy(this._prev) this._mode = mode - var h = new Buffer(4) - h.fill(0) - this._ghash = new GHASH(this._cipher.encryptBlock(h)) + this._authTag = null this._called = false } + +inherits(StreamCipher, Transform) + StreamCipher.prototype._update = function (chunk) { if (!this._called && this._alen) { var rump = 16 - (this._alen % 16) if (rump < 16) { - rump = new Buffer(rump) - rump.fill(0) + rump = Buffer.alloc(rump, 0) this._ghash.update(rump) } } + this._called = true var out = this._mode.encrypt(this, chunk) if (this._decrypt) { @@ -5692,93 +7204,76 @@ StreamCipher.prototype._update = function (chunk) { this._len += chunk.length return out } + StreamCipher.prototype._final = function () { - if (this._decrypt && !this._authTag) { - throw new Error('Unsupported state or unable to authenticate data') - } + if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) - if (this._decrypt) { - if (xorTest(tag, this._authTag)) { - throw new Error('Unsupported state or unable to authenticate data') - } - } else { - this._authTag = tag - } + if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') + + this._authTag = tag this._cipher.scrub() } + StreamCipher.prototype.getAuthTag = function getAuthTag () { - if (!this._decrypt && Buffer.isBuffer(this._authTag)) { - return this._authTag - } else { - throw new Error('Attempting to get auth tag in unsupported state') - } + if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') + + return this._authTag } + StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { - if (this._decrypt) { - this._authTag = tag - } else { - throw new Error('Attempting to set auth tag in unsupported state') - } + if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') + + this._authTag = tag } + StreamCipher.prototype.setAAD = function setAAD (buf) { - if (!this._called) { - this._ghash.update(buf) - this._alen += buf.length - } else { - throw new Error('Attempting to set AAD in unsupported state') - } + if (this._called) throw new Error('Attempting to set AAD in unsupported state') + + this._ghash.update(buf) + this._alen += buf.length } -function xorTest (a, b) { - var out = 0 - if (a.length !== b.length) { - out++ - } - var len = Math.min(a.length, b.length) - var i = -1 - while (++i < len) { - out += (a[i] ^ b[i]) - } - return out + +module.exports = StreamCipher + +},{"111":111,"161":161,"25":25,"30":30,"31":31,"53":53,"57":57}],27:[function(require,module,exports){ +var ciphers = require(29) +var deciphers = require(28) +var modes = require(39) + +function getCiphers () { + return Object.keys(modes) } -}).call(this,require(47).Buffer) -},{"21":21,"26":26,"46":46,"47":47,"49":49,"97":97}],23:[function(require,module,exports){ -var ciphers = require(25) exports.createCipher = exports.Cipher = ciphers.createCipher exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv -var deciphers = require(24) exports.createDecipher = exports.Decipher = deciphers.createDecipher exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv -var modes = require(27) -function getCiphers () { - return Object.keys(modes) -} exports.listCiphers = exports.getCiphers = getCiphers -},{"24":24,"25":25,"27":27}],24:[function(require,module,exports){ -(function (Buffer){ -var aes = require(21) -var Transform = require(49) -var inherits = require(97) -var modes = require(27) -var StreamCipher = require(35) -var AuthCipher = require(22) -var ebtk = require(87) +},{"28":28,"29":29,"39":39}],28:[function(require,module,exports){ +var AuthCipher = require(26) +var Buffer = require(161).Buffer +var MODES = require(38) +var StreamCipher = require(41) +var Transform = require(57) +var aes = require(25) +var ebtk = require(93) +var inherits = require(111) -inherits(Decipher, Transform) function Decipher (mode, key, iv) { - if (!(this instanceof Decipher)) { - return new Decipher(mode, key, iv) - } Transform.call(this) + this._cache = new Splitter() this._last = void 0 this._cipher = new aes.AES(key) - this._prev = new Buffer(iv.length) - iv.copy(this._prev) + this._prev = Buffer.from(iv) this._mode = mode this._autopadding = true } + +inherits(Decipher, Transform) + Decipher.prototype._update = function (data) { this._cache.add(data) var chunk @@ -5790,6 +7285,7 @@ Decipher.prototype._update = function (data) { } return Buffer.concat(out) } + Decipher.prototype._final = function () { var chunk = this._cache.flush() if (this._autopadding) { @@ -5798,16 +7294,16 @@ Decipher.prototype._final = function () { throw new Error('data not multiple of block length') } } + Decipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo return this } + function Splitter () { - if (!(this instanceof Splitter)) { - return new Splitter() - } - this.cache = new Buffer('') + this.cache = Buffer.allocUnsafe(0) } + Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]) } @@ -5827,130 +7323,121 @@ Splitter.prototype.get = function (autoPadding) { return out } } + return null } + Splitter.prototype.flush = function () { - if (this.cache.length) { - return this.cache - } + if (this.cache.length) return this.cache } + function unpad (last) { var padded = last[15] + if (padded < 1 || padded > 16) { + throw new Error('unable to decrypt data') + } var i = -1 while (++i < padded) { if (last[(i + (16 - padded))] !== padded) { throw new Error('unable to decrypt data') } } - if (padded === 16) { - return - } - return last.slice(0, 16 - padded) -} + if (padded === 16) return -var modelist = { - ECB: require(33), - CBC: require(28), - CFB: require(29), - CFB8: require(31), - CFB1: require(30), - OFB: require(34), - CTR: require(32), - GCM: require(32) + return last.slice(0, 16 - padded) } function createDecipheriv (suite, password, iv) { - var config = modes[suite.toLowerCase()] - if (!config) { - throw new TypeError('invalid suite type') - } - if (typeof iv === 'string') { - iv = new Buffer(iv) - } - if (typeof password === 'string') { - password = new Buffer(password) - } - if (password.length !== config.key / 8) { - throw new TypeError('invalid key length ' + password.length) - } - if (iv.length !== config.iv) { - throw new TypeError('invalid iv length ' + iv.length) - } + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + if (typeof iv === 'string') iv = Buffer.from(iv) + if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) + + if (typeof password === 'string') password = Buffer.from(password) + if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) + if (config.type === 'stream') { - return new StreamCipher(modelist[config.mode], password, iv, true) + return new StreamCipher(config.module, password, iv, true) } else if (config.type === 'auth') { - return new AuthCipher(modelist[config.mode], password, iv, true) + return new AuthCipher(config.module, password, iv, true) } - return new Decipher(modelist[config.mode], password, iv) + + return new Decipher(config.module, password, iv) } function createDecipher (suite, password) { - var config = modes[suite.toLowerCase()] - if (!config) { - throw new TypeError('invalid suite type') - } + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + var keys = ebtk(password, false, config.key, config.iv) return createDecipheriv(suite, keys.key, keys.iv) } + exports.createDecipher = createDecipher exports.createDecipheriv = createDecipheriv -}).call(this,require(47).Buffer) -},{"21":21,"22":22,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"47":47,"49":49,"87":87,"97":97}],25:[function(require,module,exports){ -(function (Buffer){ -var aes = require(21) -var Transform = require(49) -var inherits = require(97) -var modes = require(27) -var ebtk = require(87) -var StreamCipher = require(35) -var AuthCipher = require(22) -inherits(Cipher, Transform) +},{"111":111,"161":161,"25":25,"26":26,"38":38,"41":41,"57":57,"93":93}],29:[function(require,module,exports){ +var MODES = require(38) +var AuthCipher = require(26) +var Buffer = require(161).Buffer +var StreamCipher = require(41) +var Transform = require(57) +var aes = require(25) +var ebtk = require(93) +var inherits = require(111) + function Cipher (mode, key, iv) { - if (!(this instanceof Cipher)) { - return new Cipher(mode, key, iv) - } Transform.call(this) + this._cache = new Splitter() this._cipher = new aes.AES(key) - this._prev = new Buffer(iv.length) - iv.copy(this._prev) + this._prev = Buffer.from(iv) this._mode = mode this._autopadding = true } + +inherits(Cipher, Transform) + Cipher.prototype._update = function (data) { this._cache.add(data) var chunk var thing var out = [] + while ((chunk = this._cache.get())) { thing = this._mode.encrypt(this, chunk) out.push(thing) } + return Buffer.concat(out) } + +var PADDING = Buffer.alloc(16, 0x10) + Cipher.prototype._final = function () { var chunk = this._cache.flush() if (this._autopadding) { chunk = this._mode.encrypt(this, chunk) this._cipher.scrub() return chunk - } else if (chunk.toString('hex') !== '10101010101010101010101010101010') { + } + + if (!chunk.equals(PADDING)) { this._cipher.scrub() throw new Error('data not multiple of block length') } } + Cipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo return this } function Splitter () { - if (!(this instanceof Splitter)) { - return new Splitter() - } - this.cache = new Buffer('') + this.cache = Buffer.allocUnsafe(0) } + Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]) } @@ -5963,57 +7450,42 @@ Splitter.prototype.get = function () { } return null } + Splitter.prototype.flush = function () { var len = 16 - this.cache.length - var padBuff = new Buffer(len) + var padBuff = Buffer.allocUnsafe(len) var i = -1 while (++i < len) { padBuff.writeUInt8(len, i) } - var out = Buffer.concat([this.cache, padBuff]) - return out -} -var modelist = { - ECB: require(33), - CBC: require(28), - CFB: require(29), - CFB8: require(31), - CFB1: require(30), - OFB: require(34), - CTR: require(32), - GCM: require(32) + + return Buffer.concat([this.cache, padBuff]) } function createCipheriv (suite, password, iv) { - var config = modes[suite.toLowerCase()] - if (!config) { - throw new TypeError('invalid suite type') - } - if (typeof iv === 'string') { - iv = new Buffer(iv) - } - if (typeof password === 'string') { - password = new Buffer(password) - } - if (password.length !== config.key / 8) { - throw new TypeError('invalid key length ' + password.length) - } - if (iv.length !== config.iv) { - throw new TypeError('invalid iv length ' + iv.length) - } + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + if (typeof password === 'string') password = Buffer.from(password) + if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) + + if (typeof iv === 'string') iv = Buffer.from(iv) + if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) + if (config.type === 'stream') { - return new StreamCipher(modelist[config.mode], password, iv) + return new StreamCipher(config.module, password, iv) } else if (config.type === 'auth') { - return new AuthCipher(modelist[config.mode], password, iv) + return new AuthCipher(config.module, password, iv) } - return new Cipher(modelist[config.mode], password, iv) + + return new Cipher(config.module, password, iv) } + function createCipher (suite, password) { - var config = modes[suite.toLowerCase()] - if (!config) { - throw new TypeError('invalid suite type') - } + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + var keys = ebtk(password, false, config.key, config.iv) return createCipheriv(suite, keys.key, keys.iv) } @@ -6021,18 +7493,34 @@ function createCipher (suite, password) { exports.createCipheriv = createCipheriv exports.createCipher = createCipher -}).call(this,require(47).Buffer) -},{"21":21,"22":22,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"47":47,"49":49,"87":87,"97":97}],26:[function(require,module,exports){ -(function (Buffer){ -var zeros = new Buffer(16) -zeros.fill(0) -module.exports = GHASH +},{"111":111,"161":161,"25":25,"26":26,"38":38,"41":41,"57":57,"93":93}],30:[function(require,module,exports){ +var Buffer = require(161).Buffer +var ZEROES = Buffer.alloc(16, 0) + +function toArray (buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] +} + +function fromArray (out) { + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0] >>> 0, 0) + buf.writeUInt32BE(out[1] >>> 0, 4) + buf.writeUInt32BE(out[2] >>> 0, 8) + buf.writeUInt32BE(out[3] >>> 0, 12) + return buf +} + function GHASH (key) { this.h = key - this.state = new Buffer(16) - this.state.fill(0) - this.cache = new Buffer('') + this.state = Buffer.alloc(16, 0) + this.cache = Buffer.allocUnsafe(0) } + // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html // by Juho Vähä-Herttua GHASH.prototype.ghash = function (block) { @@ -6046,17 +7534,20 @@ GHASH.prototype.ghash = function (block) { GHASH.prototype._multiply = function () { var Vi = toArray(this.h) var Zi = [0, 0, 0, 0] - var j, xi, lsb_Vi + var j, xi, lsbVi var i = -1 while (++i < 128) { - xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0 + xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 if (xi) { // Z_i+1 = Z_i ^ V_i - Zi = xor(Zi, Vi) + Zi[0] ^= Vi[0] + Zi[1] ^= Vi[1] + Zi[2] ^= Vi[2] + Zi[3] ^= Vi[3] } // Store the value of LSB(V_i) - lsb_Vi = (Vi[3] & 1) !== 0 + lsbVi = (Vi[3] & 1) !== 0 // V_i+1 = V_i >> 1 for (j = 3; j > 0; j--) { @@ -6065,240 +7556,53 @@ GHASH.prototype._multiply = function () { Vi[0] = Vi[0] >>> 1 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R - if (lsb_Vi) { + if (lsbVi) { Vi[0] = Vi[0] ^ (0xe1 << 24) } } this.state = fromArray(Zi) } -GHASH.prototype.update = function (buf) { - this.cache = Buffer.concat([this.cache, buf]) - var chunk - while (this.cache.length >= 16) { - chunk = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - this.ghash(chunk) - } -} -GHASH.prototype.final = function (abl, bl) { - if (this.cache.length) { - this.ghash(Buffer.concat([this.cache, zeros], 16)) - } - this.ghash(fromArray([ - 0, abl, - 0, bl - ])) - return this.state -} -function toArray (buf) { - return [ - buf.readUInt32BE(0), - buf.readUInt32BE(4), - buf.readUInt32BE(8), - buf.readUInt32BE(12) - ] -} -function fromArray (out) { - out = out.map(fixup_uint32) - var buf = new Buffer(16) - buf.writeUInt32BE(out[0], 0) - buf.writeUInt32BE(out[1], 4) - buf.writeUInt32BE(out[2], 8) - buf.writeUInt32BE(out[3], 12) - return buf +GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + this.ghash(chunk) + } } -var uint_max = Math.pow(2, 32) -function fixup_uint32 (x) { - var ret, x_pos - ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x - return ret + +GHASH.prototype.final = function (abl, bl) { + if (this.cache.length) { + this.ghash(Buffer.concat([this.cache, ZEROES], 16)) + } + + this.ghash(fromArray([0, abl, 0, bl])) + return this.state } -function xor (a, b) { - return [ - a[0] ^ b[0], - a[1] ^ b[1], - a[2] ^ b[2], - a[3] ^ b[3] - ] + +module.exports = GHASH + +},{"161":161}],31:[function(require,module,exports){ +function incr32 (iv) { + var len = iv.length + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } } +module.exports = incr32 -}).call(this,require(47).Buffer) -},{"47":47}],27:[function(require,module,exports){ -exports['aes-128-ecb'] = { - cipher: 'AES', - key: 128, - iv: 0, - mode: 'ECB', - type: 'block' -} -exports['aes-192-ecb'] = { - cipher: 'AES', - key: 192, - iv: 0, - mode: 'ECB', - type: 'block' -} -exports['aes-256-ecb'] = { - cipher: 'AES', - key: 256, - iv: 0, - mode: 'ECB', - type: 'block' -} -exports['aes-128-cbc'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CBC', - type: 'block' -} -exports['aes-192-cbc'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CBC', - type: 'block' -} -exports['aes-256-cbc'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CBC', - type: 'block' -} -exports['aes128'] = exports['aes-128-cbc'] -exports['aes192'] = exports['aes-192-cbc'] -exports['aes256'] = exports['aes-256-cbc'] -exports['aes-128-cfb'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CFB', - type: 'stream' -} -exports['aes-192-cfb'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CFB', - type: 'stream' -} -exports['aes-256-cfb'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CFB', - type: 'stream' -} -exports['aes-128-cfb8'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CFB8', - type: 'stream' -} -exports['aes-192-cfb8'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CFB8', - type: 'stream' -} -exports['aes-256-cfb8'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CFB8', - type: 'stream' -} -exports['aes-128-cfb1'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CFB1', - type: 'stream' -} -exports['aes-192-cfb1'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CFB1', - type: 'stream' -} -exports['aes-256-cfb1'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CFB1', - type: 'stream' -} -exports['aes-128-ofb'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'OFB', - type: 'stream' -} -exports['aes-192-ofb'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'OFB', - type: 'stream' -} -exports['aes-256-ofb'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'OFB', - type: 'stream' -} -exports['aes-128-ctr'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CTR', - type: 'stream' -} -exports['aes-192-ctr'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CTR', - type: 'stream' -} -exports['aes-256-ctr'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CTR', - type: 'stream' -} -exports['aes-128-gcm'] = { - cipher: 'AES', - key: 128, - iv: 12, - mode: 'GCM', - type: 'auth' -} -exports['aes-192-gcm'] = { - cipher: 'AES', - key: 192, - iv: 12, - mode: 'GCM', - type: 'auth' -} -exports['aes-256-gcm'] = { - cipher: 'AES', - key: 256, - iv: 12, - mode: 'GCM', - type: 'auth' -} - -},{}],28:[function(require,module,exports){ -var xor = require(46) +},{}],32:[function(require,module,exports){ +var xor = require(53) exports.encrypt = function (self, block) { var data = xor(block, self._prev) @@ -6316,18 +7620,26 @@ exports.decrypt = function (self, block) { return xor(out, pad) } -},{"46":46}],29:[function(require,module,exports){ -(function (Buffer){ -var xor = require(46) +},{"53":53}],33:[function(require,module,exports){ +var Buffer = require(161).Buffer +var xor = require(53) + +function encryptStart (self, data, decrypt) { + var len = data.length + var out = xor(data, self._cache) + self._cache = self._cache.slice(len) + self._prev = Buffer.concat([self._prev, decrypt ? data : out]) + return out +} exports.encrypt = function (self, data, decrypt) { - var out = new Buffer('') + var out = Buffer.allocUnsafe(0) var len while (data.length) { if (self._cache.length === 0) { self._cache = self._cipher.encryptBlock(self._prev) - self._prev = new Buffer('') + self._prev = Buffer.allocUnsafe(0) } if (self._cache.length <= data.length) { @@ -6342,17 +7654,10 @@ exports.encrypt = function (self, data, decrypt) { return out } -function encryptStart (self, data, decrypt) { - var len = data.length - var out = xor(data, self._cache) - self._cache = self._cache.slice(len) - self._prev = Buffer.concat([self._prev, decrypt ? data : out]) - return out -} -}).call(this,require(47).Buffer) -},{"46":46,"47":47}],30:[function(require,module,exports){ -(function (Buffer){ +},{"161":161,"53":53}],34:[function(require,module,exports){ +var Buffer = require(161).Buffer + function encryptByte (self, byteParam, decrypt) { var pad var i = -1 @@ -6368,92 +7673,316 @@ function encryptByte (self, byteParam, decrypt) { } return out } -exports.encrypt = function (self, chunk, decrypt) { - var len = chunk.length - var out = new Buffer(len) + +function shiftIn (buffer, value) { + var len = buffer.length var i = -1 + var out = Buffer.allocUnsafe(buffer.length) + buffer = Buffer.concat([buffer, Buffer.from([value])]) + while (++i < len) { - out[i] = encryptByte(self, chunk[i], decrypt) + out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) } + return out } -function shiftIn (buffer, value) { - var len = buffer.length + +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = Buffer.allocUnsafe(len) var i = -1 - var out = new Buffer(buffer.length) - buffer = Buffer.concat([buffer, new Buffer([value])]) + while (++i < len) { - out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) + out[i] = encryptByte(self, chunk[i], decrypt) } + return out } -}).call(this,require(47).Buffer) -},{"47":47}],31:[function(require,module,exports){ -(function (Buffer){ +},{"161":161}],35:[function(require,module,exports){ +var Buffer = require(161).Buffer + function encryptByte (self, byteParam, decrypt) { var pad = self._cipher.encryptBlock(self._prev) var out = pad[0] ^ byteParam - self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])]) + + self._prev = Buffer.concat([ + self._prev.slice(1), + Buffer.from([decrypt ? byteParam : out]) + ]) + return out } + exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length - var out = new Buffer(len) + var out = Buffer.allocUnsafe(len) var i = -1 + while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt) } + return out } -}).call(this,require(47).Buffer) -},{"47":47}],32:[function(require,module,exports){ -(function (Buffer){ -var xor = require(46) - -function incr32 (iv) { - var len = iv.length - var item - while (len--) { - item = iv.readUInt8(len) - if (item === 255) { - iv.writeUInt8(0, len) - } else { - item++ - iv.writeUInt8(item, len) - break - } - } -} +},{"161":161}],36:[function(require,module,exports){ +var xor = require(53) +var Buffer = require(161).Buffer +var incr32 = require(31) function getBlock (self) { - var out = self._cipher.encryptBlock(self._prev) + var out = self._cipher.encryptBlockRaw(self._prev) incr32(self._prev) return out } +var blockSize = 16 exports.encrypt = function (self, chunk) { - while (self._cache.length < chunk.length) { - self._cache = Buffer.concat([self._cache, getBlock(self)]) + var chunkNum = Math.ceil(chunk.length / blockSize) + var start = self._cache.length + self._cache = Buffer.concat([ + self._cache, + Buffer.allocUnsafe(chunkNum * blockSize) + ]) + for (var i = 0; i < chunkNum; i++) { + var out = getBlock(self) + var offset = start + i * blockSize + self._cache.writeUInt32BE(out[0], offset + 0) + self._cache.writeUInt32BE(out[1], offset + 4) + self._cache.writeUInt32BE(out[2], offset + 8) + self._cache.writeUInt32BE(out[3], offset + 12) } var pad = self._cache.slice(0, chunk.length) self._cache = self._cache.slice(chunk.length) return xor(chunk, pad) } -}).call(this,require(47).Buffer) -},{"46":46,"47":47}],33:[function(require,module,exports){ +},{"161":161,"31":31,"53":53}],37:[function(require,module,exports){ exports.encrypt = function (self, block) { return self._cipher.encryptBlock(block) } + exports.decrypt = function (self, block) { return self._cipher.decryptBlock(block) } -},{}],34:[function(require,module,exports){ +},{}],38:[function(require,module,exports){ +var modeModules = { + ECB: require(37), + CBC: require(32), + CFB: require(33), + CFB8: require(35), + CFB1: require(34), + OFB: require(40), + CTR: require(36), + GCM: require(36) +} + +var modes = require(39) + +for (var key in modes) { + modes[key].module = modeModules[modes[key].mode] +} + +module.exports = modes + +},{"32":32,"33":33,"34":34,"35":35,"36":36,"37":37,"39":39,"40":40}],39:[function(require,module,exports){ +module.exports={ + "aes-128-ecb": { + "cipher": "AES", + "key": 128, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-192-ecb": { + "cipher": "AES", + "key": 192, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-256-ecb": { + "cipher": "AES", + "key": 256, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-128-cbc": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-192-cbc": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-256-cbc": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes128": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes192": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes256": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-128-cfb": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-192-cfb": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-256-cfb": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-128-cfb8": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-192-cfb8": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-256-cfb8": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-128-cfb1": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-192-cfb1": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-256-cfb1": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-128-ofb": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-192-ofb": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-256-ofb": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-128-ctr": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-192-ctr": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-256-ctr": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-128-gcm": { + "cipher": "AES", + "key": 128, + "iv": 12, + "mode": "GCM", + "type": "auth" + }, + "aes-192-gcm": { + "cipher": "AES", + "key": 192, + "iv": 12, + "mode": "GCM", + "type": "auth" + }, + "aes-256-gcm": { + "cipher": "AES", + "key": 256, + "iv": 12, + "mode": "GCM", + "type": "auth" + } +} + +},{}],40:[function(require,module,exports){ (function (Buffer){ -var xor = require(46) +var xor = require(53) function getBlock (self) { self._prev = self._cipher.encryptBlock(self._prev) @@ -6470,45 +7999,47 @@ exports.encrypt = function (self, chunk) { return xor(chunk, pad) } -}).call(this,require(47).Buffer) -},{"46":46,"47":47}],35:[function(require,module,exports){ -(function (Buffer){ -var aes = require(21) -var Transform = require(49) -var inherits = require(97) +}).call(this,require(54).Buffer) +},{"53":53,"54":54}],41:[function(require,module,exports){ +var aes = require(25) +var Buffer = require(161).Buffer +var Transform = require(57) +var inherits = require(111) -inherits(StreamCipher, Transform) -module.exports = StreamCipher function StreamCipher (mode, key, iv, decrypt) { - if (!(this instanceof StreamCipher)) { - return new StreamCipher(mode, key, iv) - } Transform.call(this) + this._cipher = new aes.AES(key) - this._prev = new Buffer(iv.length) - this._cache = new Buffer('') - this._secCache = new Buffer('') + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) this._decrypt = decrypt - iv.copy(this._prev) this._mode = mode } + +inherits(StreamCipher, Transform) + StreamCipher.prototype._update = function (chunk) { return this._mode.encrypt(this, chunk, this._decrypt) } + StreamCipher.prototype._final = function () { this._cipher.scrub() } -}).call(this,require(47).Buffer) -},{"21":21,"47":47,"49":49,"97":97}],36:[function(require,module,exports){ -var ebtk = require(87) -var aes = require(23) -var DES = require(37) -var desModes = require(38) -var aesModes = require(27) +module.exports = StreamCipher + +},{"111":111,"161":161,"25":25,"57":57}],42:[function(require,module,exports){ +var DES = require(43) +var aes = require(27) +var aesModes = require(38) +var desModes = require(44) +var ebtk = require(93) + function createCipher (suite, password) { - var keyLen, ivLen suite = suite.toLowerCase() + + var keyLen, ivLen if (aesModes[suite]) { keyLen = aesModes[suite].key ivLen = aesModes[suite].iv @@ -6518,12 +8049,15 @@ function createCipher (suite, password) { } else { throw new TypeError('invalid suite type') } + var keys = ebtk(password, false, keyLen, ivLen) return createCipheriv(suite, keys.key, keys.iv) } + function createDecipher (suite, password) { - var keyLen, ivLen suite = suite.toLowerCase() + + var keyLen, ivLen if (aesModes[suite]) { keyLen = aesModes[suite].key ivLen = aesModes[suite].iv @@ -6533,53 +8067,42 @@ function createDecipher (suite, password) { } else { throw new TypeError('invalid suite type') } + var keys = ebtk(password, false, keyLen, ivLen) return createDecipheriv(suite, keys.key, keys.iv) } function createCipheriv (suite, key, iv) { suite = suite.toLowerCase() - if (aesModes[suite]) { - return aes.createCipheriv(suite, key, iv) - } else if (desModes[suite]) { - return new DES({ - key: key, - iv: iv, - mode: suite - }) - } else { - throw new TypeError('invalid suite type') - } + if (aesModes[suite]) return aes.createCipheriv(suite, key, iv) + if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite }) + + throw new TypeError('invalid suite type') } + function createDecipheriv (suite, key, iv) { suite = suite.toLowerCase() - if (aesModes[suite]) { - return aes.createDecipheriv(suite, key, iv) - } else if (desModes[suite]) { - return new DES({ - key: key, - iv: iv, - mode: suite, - decrypt: true - }) - } else { - throw new TypeError('invalid suite type') - } + if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv) + if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true }) + + throw new TypeError('invalid suite type') +} + +function getCiphers () { + return Object.keys(desModes).concat(aes.getCiphers()) } + exports.createCipher = exports.Cipher = createCipher exports.createCipheriv = exports.Cipheriv = createCipheriv exports.createDecipher = exports.Decipher = createDecipher exports.createDecipheriv = exports.Decipheriv = createDecipheriv -function getCiphers () { - return Object.keys(desModes).concat(aes.getCiphers()) -} exports.listCiphers = exports.getCiphers = getCiphers -},{"23":23,"27":27,"37":37,"38":38,"87":87}],37:[function(require,module,exports){ -(function (Buffer){ -var CipherBase = require(49) -var des = require(59) -var inherits = require(97) +},{"27":27,"38":38,"43":43,"44":44,"93":93}],43:[function(require,module,exports){ +var CipherBase = require(57) +var des = require(66) +var inherits = require(111) +var Buffer = require(161).Buffer var modes = { 'des-ede3-cbc': des.CBC.instantiate(des.EDE), @@ -6604,10 +8127,16 @@ function DES (opts) { type = 'encrypt' } var key = opts.key + if (!Buffer.isBuffer(key)) { + key = Buffer.from(key) + } if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { key = Buffer.concat([key, key.slice(0, 8)]) } var iv = opts.iv + if (!Buffer.isBuffer(iv)) { + iv = Buffer.from(iv) + } this._des = mode.create({ key: key, iv: iv, @@ -6615,14 +8144,13 @@ function DES (opts) { }) } DES.prototype._update = function (data) { - return new Buffer(this._des.update(data)) + return Buffer.from(this._des.update(data)) } DES.prototype._final = function () { - return new Buffer(this._des.final()) + return Buffer.from(this._des.final()) } -}).call(this,require(47).Buffer) -},{"47":47,"49":49,"59":59,"97":97}],38:[function(require,module,exports){ +},{"111":111,"161":161,"57":57,"66":66}],44:[function(require,module,exports){ exports['des-ecb'] = { key: 8, iv: 0 @@ -6648,10 +8176,10 @@ exports['des-ede'] = { iv: 0 } -},{}],39:[function(require,module,exports){ +},{}],45:[function(require,module,exports){ (function (Buffer){ -var bn = require(18); -var randomBytes = require(136); +var bn = require(22); +var randomBytes = require(158); module.exports = crt; function blind(priv) { var r = getr(priv); @@ -6691,104 +8219,193 @@ function getr(priv) { return r; } -}).call(this,require(47).Buffer) -},{"136":136,"18":18,"47":47}],40:[function(require,module,exports){ -(function (Buffer){ -'use strict' -exports['RSA-SHA224'] = exports.sha224WithRSAEncryption = { - sign: 'rsa', - hash: 'sha224', - id: new Buffer('302d300d06096086480165030402040500041c', 'hex') -} -exports['RSA-SHA256'] = exports.sha256WithRSAEncryption = { - sign: 'rsa', - hash: 'sha256', - id: new Buffer('3031300d060960864801650304020105000420', 'hex') -} -exports['RSA-SHA384'] = exports.sha384WithRSAEncryption = { - sign: 'rsa', - hash: 'sha384', - id: new Buffer('3041300d060960864801650304020205000430', 'hex') -} -exports['RSA-SHA512'] = exports.sha512WithRSAEncryption = { - sign: 'rsa', - hash: 'sha512', - id: new Buffer('3051300d060960864801650304020305000440', 'hex') -} -exports['RSA-SHA1'] = { - sign: 'rsa', - hash: 'sha1', - id: new Buffer('3021300906052b0e03021a05000414', 'hex') -} -exports['ecdsa-with-SHA1'] = { - sign: 'ecdsa', - hash: 'sha1', - id: new Buffer('', 'hex') -} - -exports.DSA = exports['DSA-SHA1'] = exports['DSA-SHA'] = { - sign: 'dsa', - hash: 'sha1', - id: new Buffer('', 'hex') -} -exports['DSA-SHA224'] = exports['DSA-WITH-SHA224'] = { - sign: 'dsa', - hash: 'sha224', - id: new Buffer('', 'hex') -} -exports['DSA-SHA256'] = exports['DSA-WITH-SHA256'] = { - sign: 'dsa', - hash: 'sha256', - id: new Buffer('', 'hex') -} -exports['DSA-SHA384'] = exports['DSA-WITH-SHA384'] = { - sign: 'dsa', - hash: 'sha384', - id: new Buffer('', 'hex') -} -exports['DSA-SHA512'] = exports['DSA-WITH-SHA512'] = { - sign: 'dsa', - hash: 'sha512', - id: new Buffer('', 'hex') -} -exports['DSA-RIPEMD160'] = { - sign: 'dsa', - hash: 'rmd160', - id: new Buffer('', 'hex') -} -exports['RSA-RIPEMD160'] = exports.ripemd160WithRSA = { - sign: 'rsa', - hash: 'rmd160', - id: new Buffer('3021300906052b2403020105000414', 'hex') -} -exports['RSA-MD5'] = exports.md5WithRSAEncryption = { - sign: 'rsa', - hash: 'md5', - id: new Buffer('3020300c06082a864886f70d020505000410', 'hex') -} - -}).call(this,require(47).Buffer) -},{"47":47}],41:[function(require,module,exports){ +}).call(this,require(54).Buffer) +},{"158":158,"22":22,"54":54}],46:[function(require,module,exports){ +module.exports = require(47) + +},{"47":47}],47:[function(require,module,exports){ +module.exports={ + "sha224WithRSAEncryption": { + "sign": "rsa", + "hash": "sha224", + "id": "302d300d06096086480165030402040500041c" + }, + "RSA-SHA224": { + "sign": "ecdsa/rsa", + "hash": "sha224", + "id": "302d300d06096086480165030402040500041c" + }, + "sha256WithRSAEncryption": { + "sign": "rsa", + "hash": "sha256", + "id": "3031300d060960864801650304020105000420" + }, + "RSA-SHA256": { + "sign": "ecdsa/rsa", + "hash": "sha256", + "id": "3031300d060960864801650304020105000420" + }, + "sha384WithRSAEncryption": { + "sign": "rsa", + "hash": "sha384", + "id": "3041300d060960864801650304020205000430" + }, + "RSA-SHA384": { + "sign": "ecdsa/rsa", + "hash": "sha384", + "id": "3041300d060960864801650304020205000430" + }, + "sha512WithRSAEncryption": { + "sign": "rsa", + "hash": "sha512", + "id": "3051300d060960864801650304020305000440" + }, + "RSA-SHA512": { + "sign": "ecdsa/rsa", + "hash": "sha512", + "id": "3051300d060960864801650304020305000440" + }, + "RSA-SHA1": { + "sign": "rsa", + "hash": "sha1", + "id": "3021300906052b0e03021a05000414" + }, + "ecdsa-with-SHA1": { + "sign": "ecdsa", + "hash": "sha1", + "id": "" + }, + "sha256": { + "sign": "ecdsa", + "hash": "sha256", + "id": "" + }, + "sha224": { + "sign": "ecdsa", + "hash": "sha224", + "id": "" + }, + "sha384": { + "sign": "ecdsa", + "hash": "sha384", + "id": "" + }, + "sha512": { + "sign": "ecdsa", + "hash": "sha512", + "id": "" + }, + "DSA-SHA": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA-SHA1": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA-WITH-SHA224": { + "sign": "dsa", + "hash": "sha224", + "id": "" + }, + "DSA-SHA224": { + "sign": "dsa", + "hash": "sha224", + "id": "" + }, + "DSA-WITH-SHA256": { + "sign": "dsa", + "hash": "sha256", + "id": "" + }, + "DSA-SHA256": { + "sign": "dsa", + "hash": "sha256", + "id": "" + }, + "DSA-WITH-SHA384": { + "sign": "dsa", + "hash": "sha384", + "id": "" + }, + "DSA-SHA384": { + "sign": "dsa", + "hash": "sha384", + "id": "" + }, + "DSA-WITH-SHA512": { + "sign": "dsa", + "hash": "sha512", + "id": "" + }, + "DSA-SHA512": { + "sign": "dsa", + "hash": "sha512", + "id": "" + }, + "DSA-RIPEMD160": { + "sign": "dsa", + "hash": "rmd160", + "id": "" + }, + "ripemd160WithRSA": { + "sign": "rsa", + "hash": "rmd160", + "id": "3021300906052b2403020105000414" + }, + "RSA-RIPEMD160": { + "sign": "rsa", + "hash": "rmd160", + "id": "3021300906052b2403020105000414" + }, + "md5WithRSAEncryption": { + "sign": "rsa", + "hash": "md5", + "id": "3020300c06082a864886f70d020505000410" + }, + "RSA-MD5": { + "sign": "rsa", + "hash": "md5", + "id": "3020300c06082a864886f70d020505000410" + } +} + +},{}],48:[function(require,module,exports){ +module.exports={ + "1.3.132.0.10": "secp256k1", + "1.3.132.0.33": "p224", + "1.2.840.10045.3.1.1": "p192", + "1.2.840.10045.3.1.7": "p256", + "1.3.132.0.34": "p384", + "1.3.132.0.35": "p521" +} + +},{}],49:[function(require,module,exports){ (function (Buffer){ -var _algos = require(40) -var createHash = require(52) -var inherits = require(97) -var sign = require(43) -var stream = require(148) -var verify = require(44) - -var algos = {} -Object.keys(_algos).forEach(function (key) { - algos[key] = algos[key.toLowerCase()] = _algos[key] +var createHash = require(60) +var stream = require(171) +var inherits = require(111) +var sign = require(50) +var verify = require(51) + +var algorithms = require(47) +Object.keys(algorithms).forEach(function (key) { + algorithms[key].id = new Buffer(algorithms[key].id, 'hex') + algorithms[key.toLowerCase()] = algorithms[key] }) function Sign (algorithm) { stream.Writable.call(this) - var data = algos[algorithm] - if (!data) { - throw new Error('Unknown message digest') - } + var data = algorithms[algorithm] + if (!data) throw new Error('Unknown message digest') this._hashType = data.hash this._hash = createHash(data.hash) @@ -6803,9 +8420,7 @@ Sign.prototype._write = function _write (data, _, done) { } Sign.prototype.update = function update (data, enc) { - if (typeof data === 'string') { - data = new Buffer(data, enc) - } + if (typeof data === 'string') data = new Buffer(data, enc) this._hash.update(data) return this @@ -6814,7 +8429,7 @@ Sign.prototype.update = function update (data, enc) { Sign.prototype.sign = function signMethod (key, enc) { this.end() var hash = this._hash.digest() - var sig = sign(Buffer.concat([this._tag, hash]), key, this._hashType, this._signType) + var sig = sign(hash, key, this._hashType, this._signType, this._tag) return enc ? sig.toString(enc) : sig } @@ -6822,10 +8437,8 @@ Sign.prototype.sign = function signMethod (key, enc) { function Verify (algorithm) { stream.Writable.call(this) - var data = algos[algorithm] - if (!data) { - throw new Error('Unknown message digest') - } + var data = algorithms[algorithm] + if (!data) throw new Error('Unknown message digest') this._hash = createHash(data.hash) this._tag = data.id @@ -6835,28 +8448,22 @@ inherits(Verify, stream.Writable) Verify.prototype._write = function _write (data, _, done) { this._hash.update(data) - done() } Verify.prototype.update = function update (data, enc) { - if (typeof data === 'string') { - data = new Buffer(data, enc) - } + if (typeof data === 'string') data = new Buffer(data, enc) this._hash.update(data) return this } Verify.prototype.verify = function verifyMethod (key, sig, enc) { - if (typeof sig === 'string') { - sig = new Buffer(sig, enc) - } + if (typeof sig === 'string') sig = new Buffer(sig, enc) this.end() var hash = this._hash.digest() - - return verify(sig, Buffer.concat([this._tag, hash]), key, this._signType) + return verify(sig, hash, key, this._signType, this._tag) } function createSign (algorithm) { @@ -6874,58 +8481,36 @@ module.exports = { createVerify: createVerify } -}).call(this,require(47).Buffer) -},{"148":148,"40":40,"43":43,"44":44,"47":47,"52":52,"97":97}],42:[function(require,module,exports){ -'use strict' -exports['1.3.132.0.10'] = 'secp256k1' - -exports['1.3.132.0.33'] = 'p224' - -exports['1.2.840.10045.3.1.1'] = 'p192' - -exports['1.2.840.10045.3.1.7'] = 'p256' - -exports['1.3.132.0.34'] = 'p384' - -exports['1.3.132.0.35'] = 'p521' - -},{}],43:[function(require,module,exports){ +}).call(this,require(54).Buffer) +},{"111":111,"171":171,"47":47,"50":50,"51":51,"54":54,"60":60}],50:[function(require,module,exports){ (function (Buffer){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js -var createHmac = require(55) -var crt = require(39) -var curves = require(42) -var elliptic = require(69) -var parseKeys = require(111) - -var BN = require(18) -var EC = elliptic.ec - -function sign (hash, key, hashType, signType) { +var createHmac = require(62) +var crt = require(45) +var EC = require(76).ec +var BN = require(22) +var parseKeys = require(127) +var curves = require(48) + +function sign (hash, key, hashType, signType, tag) { var priv = parseKeys(key) if (priv.curve) { - if (signType !== 'ecdsa') throw new Error('wrong private key type') - + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') return ecSign(hash, priv) } else if (priv.type === 'dsa') { - if (signType !== 'dsa') { - throw new Error('wrong private key type') - } + if (signType !== 'dsa') throw new Error('wrong private key type') return dsaSign(hash, priv, hashType) } else { - if (signType !== 'rsa') throw new Error('wrong private key type') + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') } - + hash = Buffer.concat([tag, hash]) var len = priv.modulus.byteLength() var pad = [ 0, 1 ] - while (hash.length + pad.length + 1 < len) { - pad.push(0xff) - } + while (hash.length + pad.length + 1 < len) pad.push(0xff) pad.push(0x00) var i = -1 - while (++i < hash.length) { - pad.push(hash[i]) - } + while (++i < hash.length) pad.push(hash[i]) var out = crt(pad, priv) return out @@ -6936,9 +8521,7 @@ function ecSign (hash, priv) { if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')) var curve = new EC(curveId) - var key = curve.genKeyPair() - - key._importPrivate(priv.privateKey) + var key = curve.keyFromPrivate(priv.privateKey) var out = key.sign(hash) return new Buffer(out.toDER()) @@ -6958,7 +8541,7 @@ function dsaSign (hash, priv, algo) { k = makeKey(q, kv, algo) r = makeR(g, k, p, q) s = k.invm(q).imul(H.add(x.mul(r))).mod(q) - if (!s.cmpn(0)) { + if (s.cmpn(0) === 0) { s = false r = new BN(0) } @@ -6971,13 +8554,8 @@ function toDER (r, s) { s = s.toArray() // Pad values - if (r[0] & 0x80) { - r = [ 0 ].concat(r) - } - // Pad values - if (s[0] & 0x80) { - s = [0].concat(s) - } + if (r[0] & 0x80) r = [ 0 ].concat(r) + if (s[0] & 0x80) s = [ 0 ].concat(s) var total = r.length + s.length + 4 var res = [ 0x30, total, 0x02, r.length ] @@ -6990,7 +8568,7 @@ function getKey (x, q, hash, algo) { if (x.length < q.byteLength()) { var zeros = new Buffer(q.byteLength() - x.length) zeros.fill(0) - x = Buffer.concat([zeros, x]) + x = Buffer.concat([ zeros, x ]) } var hlen = hash.length var hbits = bits2octets(hash, q) @@ -6998,36 +8576,17 @@ function getKey (x, q, hash, algo) { v.fill(1) var k = new Buffer(hlen) k.fill(0) - k = createHmac(algo, k) - .update(v) - .update(new Buffer([0])) - .update(x) - .update(hbits) - .digest() - v = createHmac(algo, k) - .update(v) - .digest() - k = createHmac(algo, k) - .update(v) - .update(new Buffer([1])) - .update(x) - .update(hbits) - .digest() - v = createHmac(algo, k) - .update(v) - .digest() - return { - k: k, - v: v - } + k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest() + v = createHmac(algo, k).update(v).digest() + k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest() + v = createHmac(algo, k).update(v).digest() + return { k: k, v: v } } function bits2int (obits, q) { var bits = new BN(obits) var shift = (obits.length << 3) - q.bitLength() - if (shift > 0) { - bits.ishrn(shift) - } + if (shift > 0) bits.ishrn(shift) return bits } @@ -7038,32 +8597,26 @@ function bits2octets (bits, q) { if (out.length < q.byteLength()) { var zeros = new Buffer(q.byteLength() - out.length) zeros.fill(0) - out = Buffer.concat([zeros, out]) + out = Buffer.concat([ zeros, out ]) } return out } function makeKey (q, kv, algo) { - var t, k + var t + var k do { - t = new Buffer('') + t = new Buffer(0) while (t.length * 8 < q.bitLength()) { - kv.v = createHmac(algo, kv.k) - .update(kv.v) - .digest() - t = Buffer.concat([t, kv.v]) + kv.v = createHmac(algo, kv.k).update(kv.v).digest() + t = Buffer.concat([ t, kv.v ]) } k = bits2int(t, q) - kv.k = createHmac(algo, kv.k) - .update(kv.v) - .update(new Buffer([0])) - .digest() - kv.v = createHmac(algo, kv.k) - .update(kv.v) - .digest() + kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest() + kv.v = createHmac(algo, kv.k).update(kv.v).digest() } while (k.cmp(q) !== -1) return k @@ -7077,34 +8630,28 @@ module.exports = sign module.exports.getKey = getKey module.exports.makeKey = makeKey -}).call(this,require(47).Buffer) -},{"111":111,"18":18,"39":39,"42":42,"47":47,"55":55,"69":69}],44:[function(require,module,exports){ +}).call(this,require(54).Buffer) +},{"127":127,"22":22,"45":45,"48":48,"54":54,"62":62,"76":76}],51:[function(require,module,exports){ (function (Buffer){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js -var curves = require(42) -var elliptic = require(69) -var parseKeys = require(111) - -var BN = require(18) -var EC = elliptic.ec +var BN = require(22) +var EC = require(76).ec +var parseKeys = require(127) +var curves = require(48) -function verify (sig, hash, key, signType) { +function verify (sig, hash, key, signType, tag) { var pub = parseKeys(key) if (pub.type === 'ec') { - if (signType !== 'ecdsa') { - throw new Error('wrong public key type') - } + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') return ecVerify(sig, hash, pub) } else if (pub.type === 'dsa') { - if (signType !== 'dsa') { - throw new Error('wrong public key type') - } + if (signType !== 'dsa') throw new Error('wrong public key type') return dsaVerify(sig, hash, pub) } else { - if (signType !== 'rsa') { - throw new Error('wrong public key type') - } + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') } + hash = Buffer.concat([tag, hash]) var len = pub.modulus.byteLength() var pad = [ 1 ] var padNum = 0 @@ -7122,21 +8669,13 @@ function verify (sig, hash, key, signType) { sig = new BN(sig).toRed(red) sig = sig.redPow(new BN(pub.publicExponent)) - sig = new Buffer(sig.fromRed().toArray()) - var out = 0 - if (padNum < 8) { - out = 1 - } + var out = padNum < 8 ? 1 : 0 len = Math.min(sig.length, pad.length) - if (sig.length !== pad.length) { - out = 1 - } + if (sig.length !== pad.length) out = 1 i = -1 - while (++i < len) { - out |= (sig[i] ^ pad[i]) - } + while (++i < len) out |= sig[i] ^ pad[i] return out === 0 } @@ -7165,139 +8704,244 @@ function dsaVerify (sig, hash, pub) { var v = g.toRed(montp) .redPow(new BN(hash).mul(w).mod(q)) .fromRed() - .mul( - y.toRed(montp) - .redPow(r.mul(w).mod(q)) - .fromRed() - ).mod(p).mod(q) - return !v.cmp(r) + .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) + .mod(p) + .mod(q) + return v.cmp(r) === 0 } function checkValue (b, q) { - if (b.cmpn(0) <= 0) { - throw new Error('invalid sig') - } - if (b.cmp(q) >= q) { - throw new Error('invalid sig') - } + if (b.cmpn(0) <= 0) throw new Error('invalid sig') + if (b.cmp(q) >= q) throw new Error('invalid sig') } module.exports = verify -}).call(this,require(47).Buffer) -},{"111":111,"18":18,"42":42,"47":47,"69":69}],45:[function(require,module,exports){ -(function (global){ -'use strict'; +}).call(this,require(54).Buffer) +},{"127":127,"22":22,"48":48,"54":54,"76":76}],52:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -var buffer = require(47); -var Buffer = buffer.Buffer; -var SlowBuffer = buffer.SlowBuffer; -var MAX_LEN = buffer.kMaxLength || 2147483647; -exports.alloc = function alloc(size, fill, encoding) { - if (typeof Buffer.alloc === 'function') { - return Buffer.alloc(size, fill, encoding); - } - if (typeof encoding === 'number') { - throw new TypeError('encoding must not be number'); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - var enc = encoding; - var _fill = fill; - if (_fill === undefined) { - enc = undefined; - _fill = 0; - } - var buf = new Buffer(size); - if (typeof _fill === 'string') { - var fillBuf = new Buffer(_fill, enc); - var flen = fillBuf.length; - var i = -1; - while (++i < size) { - buf[i] = fillBuf[i % flen]; - } - } else { - buf.fill(_fill); - } - return buf; -} -exports.allocUnsafe = function allocUnsafe(size) { - if (typeof Buffer.allocUnsafe === 'function') { - return Buffer.allocUnsafe(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); +var Buffer = require(54).Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); } - return new Buffer(size); } -exports.from = function from(value, encodingOrOffset, length) { - if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { - return Buffer.from(value, encodingOrOffset, length); - } - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); - } - if (typeof value === 'string') { - return new Buffer(value, encodingOrOffset); + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - var offset = encodingOrOffset; - if (arguments.length === 1) { - return new Buffer(value); - } - if (typeof offset === 'undefined') { - offset = 0; - } - var len = length; - if (typeof len === 'undefined') { - len = value.byteLength - offset; + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; } - if (offset >= value.byteLength) { - throw new RangeError('\'offset\' is out of bounds'); + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; } - if (len > value.byteLength - offset) { - throw new RangeError('\'length\' is out of bounds'); + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; } - return new Buffer(value.slice(offset, offset + len)); + break; } - if (Buffer.isBuffer(value)) { - var out = new Buffer(value.length); - value.copy(out, 0, 0, value.length); - return out; + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; } - if (value) { - if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { - return new Buffer(value); + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; } - if (value.type === 'Buffer' && Array.isArray(value.data)) { - return new Buffer(value.data); + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; } - } - throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); -} -exports.allocUnsafeSlow = function allocUnsafeSlow(size) { - if (typeof Buffer.allocUnsafeSlow === 'function') { - return Buffer.allocUnsafeSlow(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } } - if (size >= MAX_LEN) { - throw new RangeError('size is too large'); + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); } - return new SlowBuffer(size); + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"47":47}],46:[function(require,module,exports){ +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +},{"54":54}],53:[function(require,module,exports){ (function (Buffer){ module.exports = function xor (a, b) { var length = Math.min(a.length, b.length) @@ -7310,9 +8954,9 @@ module.exports = function xor (a, b) { return buffer } -}).call(this,require(47).Buffer) -},{"47":47}],47:[function(require,module,exports){ -(function (global){ +}).call(this,require(54).Buffer) +},{"54":54}],54:[function(require,module,exports){ +(function (global,Buffer){ /*! * The buffer module from node.js, for the browser. * @@ -7323,9 +8967,9 @@ module.exports = function xor (a, b) { 'use strict' -var base64 = require(17) -var ieee754 = require(94) -var isArray = require(48) +var base64 = require(21) +var ieee754 = require(108) +var isArray = require(55) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer @@ -8862,21 +10506,55 @@ function blitBuffer (src, dst, offset, length) { return i } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"17":17,"48":48,"94":94}],48:[function(require,module,exports){ +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require(54).Buffer) +},{"108":108,"21":21,"54":54,"55":55}],55:[function(require,module,exports){ var toString = {}.toString; -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],56:[function(require,module,exports){ +var charenc = { + // UTF-8 encoding + utf8: { + // Convert a string to a byte array + stringToBytes: function(str) { + return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))); + }, + + // Convert a byte array to a string + bytesToString: function(bytes) { + return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))); + } + }, + + // Binary encoding + bin: { + // Convert a string to a byte array + stringToBytes: function(str) { + for (var bytes = [], i = 0; i < str.length; i++) + bytes.push(str.charCodeAt(i) & 0xFF); + return bytes; + }, + + // Convert a byte array to a string + bytesToString: function(bytes) { + for (var str = [], i = 0; i < bytes.length; i++) + str.push(String.fromCharCode(bytes[i])); + return str.join(''); + } + } }; -},{}],49:[function(require,module,exports){ -(function (Buffer){ -var Transform = require(148).Transform -var inherits = require(97) -var StringDecoder = require(161).StringDecoder -module.exports = CipherBase -inherits(CipherBase, Transform) +module.exports = charenc; + +},{}],57:[function(require,module,exports){ +var Buffer = require(161).Buffer +var Transform = require(171).Transform +var StringDecoder = require(52).StringDecoder +var inherits = require(111) + function CipherBase (hashMode) { Transform.call(this) this.hashMode = typeof hashMode === 'string' @@ -8885,25 +10563,31 @@ function CipherBase (hashMode) { } else { this.final = this._finalOrDigest } + if (this._final) { + this.__final = this._final + this._final = null + } this._decoder = null this._encoding = null } +inherits(CipherBase, Transform) + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { if (typeof data === 'string') { - data = new Buffer(data, inputEnc) + data = Buffer.from(data, inputEnc) } + var outData = this._update(data) - if (this.hashMode) { - return this - } + if (this.hashMode) return this + if (outputEnc) { outData = this._toString(outData, outputEnc) } + return outData } CipherBase.prototype.setAutoPadding = function () {} - CipherBase.prototype.getAuthTag = function () { throw new Error('trying to get auth tag in unsupported state') } @@ -8933,15 +10617,15 @@ CipherBase.prototype._transform = function (data, _, next) { CipherBase.prototype._flush = function (done) { var err try { - this.push(this._final()) + this.push(this.__final()) } catch (e) { err = e - } finally { - done(err) } + + done(err) } CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this._final() || new Buffer('') + var outData = this.__final() || Buffer.alloc(0) if (outputEnc) { outData = this._toString(outData, outputEnc, true) } @@ -8953,18 +10637,20 @@ CipherBase.prototype._toString = function (value, enc, fin) { this._decoder = new StringDecoder(enc) this._encoding = enc } - if (this._encoding !== enc) { - throw new Error('can\'t switch encodings') - } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + var out = this._decoder.write(value) if (fin) { out += this._decoder.end() } + return out } -}).call(this,require(47).Buffer) -},{"148":148,"161":161,"47":47,"97":97}],50:[function(require,module,exports){ +module.exports = CipherBase + +},{"111":111,"161":161,"171":171,"52":52}],58:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -9074,165 +10760,144 @@ function objectToString(o) { return Object.prototype.toString.call(o); } -}).call(this,{"isBuffer":require(98)}) -},{"98":98}],51:[function(require,module,exports){ +}).call(this,{"isBuffer":require(112)}) +},{"112":112}],59:[function(require,module,exports){ (function (Buffer){ -var elliptic = require(69); -var BN = require(18); +var elliptic = require(76) +var BN = require(22) -module.exports = function createECDH(curve) { - return new ECDH(curve); -}; +module.exports = function createECDH (curve) { + return new ECDH(curve) +} var aliases = { - secp256k1: { - name: 'secp256k1', - byteLength: 32 - }, - secp224r1: { - name: 'p224', - byteLength: 28 - }, - prime256v1: { - name: 'p256', - byteLength: 32 - }, - prime192v1: { - name: 'p192', - byteLength: 24 - }, - ed25519: { - name: 'ed25519', - byteLength: 32 - }, - secp384r1: { - name: 'p384', - byteLength: 48 - }, - secp521r1: { - name: 'p521', - byteLength: 66 - } -}; + secp256k1: { + name: 'secp256k1', + byteLength: 32 + }, + secp224r1: { + name: 'p224', + byteLength: 28 + }, + prime256v1: { + name: 'p256', + byteLength: 32 + }, + prime192v1: { + name: 'p192', + byteLength: 24 + }, + ed25519: { + name: 'ed25519', + byteLength: 32 + }, + secp384r1: { + name: 'p384', + byteLength: 48 + }, + secp521r1: { + name: 'p521', + byteLength: 66 + } +} -aliases.p224 = aliases.secp224r1; -aliases.p256 = aliases.secp256r1 = aliases.prime256v1; -aliases.p192 = aliases.secp192r1 = aliases.prime192v1; -aliases.p384 = aliases.secp384r1; -aliases.p521 = aliases.secp521r1; +aliases.p224 = aliases.secp224r1 +aliases.p256 = aliases.secp256r1 = aliases.prime256v1 +aliases.p192 = aliases.secp192r1 = aliases.prime192v1 +aliases.p384 = aliases.secp384r1 +aliases.p521 = aliases.secp521r1 -function ECDH(curve) { - this.curveType = aliases[curve]; - if (!this.curveType ) { - this.curveType = { - name: curve - }; - } - this.curve = new elliptic.ec(this.curveType.name); - this.keys = void 0; +function ECDH (curve) { + this.curveType = aliases[curve] + if (!this.curveType) { + this.curveType = { + name: curve + } + } + this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap + this.keys = void 0 } ECDH.prototype.generateKeys = function (enc, format) { - this.keys = this.curve.genKeyPair(); - return this.getPublicKey(enc, format); -}; + this.keys = this.curve.genKeyPair() + return this.getPublicKey(enc, format) +} ECDH.prototype.computeSecret = function (other, inenc, enc) { - inenc = inenc || 'utf8'; - if (!Buffer.isBuffer(other)) { - other = new Buffer(other, inenc); - } - var otherPub = this.curve.keyFromPublic(other).getPublic(); - var out = otherPub.mul(this.keys.getPrivate()).getX(); - return formatReturnValue(out, enc, this.curveType.byteLength); -}; + inenc = inenc || 'utf8' + if (!Buffer.isBuffer(other)) { + other = new Buffer(other, inenc) + } + var otherPub = this.curve.keyFromPublic(other).getPublic() + var out = otherPub.mul(this.keys.getPrivate()).getX() + return formatReturnValue(out, enc, this.curveType.byteLength) +} ECDH.prototype.getPublicKey = function (enc, format) { - var key = this.keys.getPublic(format === 'compressed', true); - if (format === 'hybrid') { - if (key[key.length - 1] % 2) { - key[0] = 7; - } else { - key [0] = 6; - } - } - return formatReturnValue(key, enc); -}; + var key = this.keys.getPublic(format === 'compressed', true) + if (format === 'hybrid') { + if (key[key.length - 1] % 2) { + key[0] = 7 + } else { + key[0] = 6 + } + } + return formatReturnValue(key, enc) +} ECDH.prototype.getPrivateKey = function (enc) { - return formatReturnValue(this.keys.getPrivate(), enc); -}; + return formatReturnValue(this.keys.getPrivate(), enc) +} ECDH.prototype.setPublicKey = function (pub, enc) { - enc = enc || 'utf8'; - if (!Buffer.isBuffer(pub)) { - pub = new Buffer(pub, enc); - } - this.keys._importPublic(pub); - return this; -}; - -ECDH.prototype.setPrivateKey = function (priv, enc) { - enc = enc || 'utf8'; - if (!Buffer.isBuffer(priv)) { - priv = new Buffer(priv, enc); - } - var _priv = new BN(priv); - _priv = _priv.toString(16); - this.keys._importPrivate(_priv); - return this; -}; - -function formatReturnValue(bn, enc, len) { - if (!Array.isArray(bn)) { - bn = bn.toArray(); - } - var buf = new Buffer(bn); - if (len && buf.length < len) { - var zeros = new Buffer(len - buf.length); - zeros.fill(0); - buf = Buffer.concat([zeros, buf]); - } - if (!enc) { - return buf; - } else { - return buf.toString(enc); - } + enc = enc || 'utf8' + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc) + } + this.keys._importPublic(pub) + return this } -}).call(this,require(47).Buffer) -},{"18":18,"47":47,"69":69}],52:[function(require,module,exports){ -(function (Buffer){ -'use strict'; -var inherits = require(97) -var md5 = require(54) -var rmd160 = require(137) -var sha = require(140) - -var Base = require(49) - -function HashNoConstructor(hash) { - Base.call(this, 'digest') +ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc) + } - this._hash = hash - this.buffers = [] + var _priv = new BN(priv) + _priv = _priv.toString(16) + this.keys = this.curve.genKeyPair() + this.keys._importPrivate(_priv) + return this } -inherits(HashNoConstructor, Base) - -HashNoConstructor.prototype._update = function (data) { - this.buffers.push(data) +function formatReturnValue (bn, enc, len) { + if (!Array.isArray(bn)) { + bn = bn.toArray() + } + var buf = new Buffer(bn) + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length) + zeros.fill(0) + buf = Buffer.concat([zeros, buf]) + } + if (!enc) { + return buf + } else { + return buf.toString(enc) + } } -HashNoConstructor.prototype._final = function () { - var buf = Buffer.concat(this.buffers) - var r = this._hash(buf) - this.buffers = null - - return r -} +}).call(this,require(54).Buffer) +},{"22":22,"54":54,"76":76}],60:[function(require,module,exports){ +'use strict' +var inherits = require(111) +var MD5 = require(118) +var RIPEMD160 = require(160) +var sha = require(164) +var Base = require(57) -function Hash(hash) { +function Hash (hash) { Base.call(this, 'digest') this._hash = hash @@ -9250,741 +10915,342 @@ Hash.prototype._final = function () { module.exports = function createHash (alg) { alg = alg.toLowerCase() - if ('md5' === alg) return new HashNoConstructor(md5) - if ('rmd160' === alg || 'ripemd160' === alg) return new HashNoConstructor(rmd160) + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() return new Hash(sha(alg)) } -}).call(this,require(47).Buffer) -},{"137":137,"140":140,"47":47,"49":49,"54":54,"97":97}],53:[function(require,module,exports){ -(function (Buffer){ -'use strict'; -var intSize = 4; -var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); -var chrsz = 8; - -function toArray(buf, bigEndian) { - if ((buf.length % intSize) !== 0) { - var len = buf.length + (intSize - (buf.length % intSize)); - buf = Buffer.concat([buf, zeroBuffer], len); - } - - var arr = []; - var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; - for (var i = 0; i < buf.length; i += intSize) { - arr.push(fn.call(buf, i)); - } - return arr; -} - -function toBuffer(arr, size, bigEndian) { - var buf = new Buffer(size); - var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; - for (var i = 0; i < arr.length; i++) { - fn.call(buf, arr[i], i * 4, true); - } - return buf; -} - -function hash(buf, fn, hashSize, bigEndian) { - if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); - var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); - return toBuffer(arr, hashSize, bigEndian); -} -exports.hash = hash; -}).call(this,require(47).Buffer) -},{"47":47}],54:[function(require,module,exports){ -'use strict'; -/* - * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - * Digest Algorithm, as defined in RFC 1321. - * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for more info. - */ - -var helpers = require(53); - -/* - * Calculate the MD5 of an array of little-endian words, and a bit length - */ -function core_md5(x, len) -{ - /* append padding */ - x[len >> 5] |= 0x80 << ((len) % 32); - x[(((len + 64) >>> 9) << 4) + 14] = len; - - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for(var i = 0; i < x.length; i += 16) - { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - - a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); - d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); - c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); - b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); - a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); - d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); - c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); - b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); - a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); - d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); - c = md5_ff(c, d, a, b, x[i+10], 17, -42063); - b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); - a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); - d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); - c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); - b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); - - a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); - d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); - c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); - b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); - a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); - d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); - c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); - b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); - a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); - d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); - c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); - b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); - a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); - d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); - c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); - b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); - - a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); - d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); - c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); - b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); - a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); - d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); - c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); - b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); - a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); - d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); - c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); - b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); - a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); - d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); - c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); - b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); - - a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); - d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); - c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); - b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); - a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); - d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); - c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); - b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); - a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); - d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); - c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); - b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); - a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); - d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); - c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); - b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); - - a = safe_add(a, olda); - b = safe_add(b, oldb); - c = safe_add(c, oldc); - d = safe_add(d, oldd); - } - return Array(a, b, c, d); - -} - -/* - * These functions implement the four basic operations the algorithm uses. - */ -function md5_cmn(q, a, b, x, s, t) -{ - return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); -} -function md5_ff(a, b, c, d, x, s, t) -{ - return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); -} -function md5_gg(a, b, c, d, x, s, t) -{ - return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); -} -function md5_hh(a, b, c, d, x, s, t) -{ - return md5_cmn(b ^ c ^ d, a, b, x, s, t); -} -function md5_ii(a, b, c, d, x, s, t) -{ - return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ -function safe_add(x, y) -{ - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); -} +},{"111":111,"118":118,"160":160,"164":164,"57":57}],61:[function(require,module,exports){ +var MD5 = require(118) -/* - * Bitwise rotate a 32-bit number to the left. - */ -function bit_rol(num, cnt) -{ - return (num << cnt) | (num >>> (32 - cnt)); +module.exports = function (buffer) { + return new MD5().update(buffer).digest() } -module.exports = function md5(buf) { - return helpers.hash(buf, core_md5, 16); -}; -},{"53":53}],55:[function(require,module,exports){ -(function (Buffer){ -'use strict'; -var createHash = require(52); -var inherits = require(97) +},{"118":118}],62:[function(require,module,exports){ +'use strict' +var inherits = require(111) +var Legacy = require(63) +var Base = require(57) +var Buffer = require(161).Buffer +var md5 = require(61) +var RIPEMD160 = require(160) -var Transform = require(148).Transform +var sha = require(164) -var ZEROS = new Buffer(128) -ZEROS.fill(0) +var ZEROS = Buffer.alloc(128) -function Hmac(alg, key) { - Transform.call(this) - alg = alg.toLowerCase() +function Hmac (alg, key) { + Base.call(this, 'digest') if (typeof key === 'string') { - key = new Buffer(key) + key = Buffer.from(key) } var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 this._alg = alg this._key = key - if (key.length > blocksize) { - key = createHash(alg).update(key).digest() - + var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + key = hash.update(key).digest() } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } - var ipad = this._ipad = new Buffer(blocksize) - var opad = this._opad = new Buffer(blocksize) + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } - - this._hash = createHash(alg).update(ipad) + this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + this._hash.update(ipad) } -inherits(Hmac, Transform) - -Hmac.prototype.update = function (data, enc) { - this._hash.update(data, enc) - - return this -} +inherits(Hmac, Base) -Hmac.prototype._transform = function (data, _, next) { +Hmac.prototype._update = function (data) { this._hash.update(data) - - next() -} - -Hmac.prototype._flush = function (next) { - this.push(this.digest()) - - next() } -Hmac.prototype.digest = function (enc) { +Hmac.prototype._final = function () { var h = this._hash.digest() - - return createHash(this._alg).update(this._opad).update(h).digest(enc) -} - -module.exports = function createHmac(alg, key) { - return new Hmac(alg, key) -} - -}).call(this,require(47).Buffer) -},{"148":148,"47":47,"52":52,"97":97}],56:[function(require,module,exports){ -'use strict' - -exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require(136) -exports.createHash = exports.Hash = require(52) -exports.createHmac = exports.Hmac = require(55) - -var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(Object.keys(require(40))) -exports.getHashes = function () { - return hashes -} - -var p = require(112) -exports.pbkdf2 = p.pbkdf2 -exports.pbkdf2Sync = p.pbkdf2Sync - -var aes = require(36) -;[ - 'Cipher', - 'createCipher', - 'Cipheriv', - 'createCipheriv', - 'Decipher', - 'createDecipher', - 'Decipheriv', - 'createDecipheriv', - 'getCiphers', - 'listCiphers' -].forEach(function (key) { - exports[key] = aes[key] -}) - -var dh = require(65) -;[ - 'DiffieHellmanGroup', - 'createDiffieHellmanGroup', - 'getDiffieHellman', - 'createDiffieHellman', - 'DiffieHellman' -].forEach(function (key) { - exports[key] = dh[key] -}) - -var sign = require(41) -;[ - 'createSign', - 'Sign', - 'createVerify', - 'Verify' -].forEach(function (key) { - exports[key] = sign[key] -}) - -exports.createECDH = require(51) - -var publicEncrypt = require(130) - -;[ - 'publicEncrypt', - 'privateEncrypt', - 'publicDecrypt', - 'privateDecrypt' -].forEach(function (key) { - exports[key] = publicEncrypt[key] -}) - -// the least I can do is make error messages for the rest of the node.js/crypto api. -;[ - 'createCredentials' -].forEach(function (name) { - exports[name] = function () { - throw new Error([ - 'sorry, ' + name + ' is not implemented yet', - 'we accept pull requests', - 'https://github.com/crypto-browserify/crypto-browserify' - ].join('\n')) - } -}) - -},{"112":112,"130":130,"136":136,"36":36,"40":40,"41":41,"51":51,"52":52,"55":55,"65":65}],57:[function(require,module,exports){ - -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require(58); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // is webkit? http://stackoverflow.com/a/16459606/376773 - return ('WebkitAppearance' in document.documentElement.style) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (window.console && (console.firebug || (console.exception && console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - return JSON.stringify(v); -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs() { - var args = arguments; - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return args; - - var c = 'color: ' + this.color; - args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); - return args; -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage(){ - try { - return window.localStorage; - } catch (e) {} + var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) + return hash.update(this._opad).update(h).digest() } -},{"58":58}],58:[function(require,module,exports){ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ +module.exports = function createHmac (alg, key) { + alg = alg.toLowerCase() + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac(alg, key) +} -exports = module.exports = debug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require(107); +},{"111":111,"160":160,"161":161,"164":164,"57":57,"61":61,"63":63}],63:[function(require,module,exports){ +'use strict' +var inherits = require(111) +var Buffer = require(161).Buffer -/** - * The currently active debug mode names, and names to skip. - */ +var Base = require(57) -exports.names = []; -exports.skips = []; +var ZEROS = Buffer.alloc(128) +var blocksize = 64 -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lowercased letter, i.e. "n". - */ +function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } -exports.formatters = {}; + this._alg = alg + this._key = key -/** - * Previously assigned color. - */ + if (key.length > blocksize) { + key = alg(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } -var prevColor = 0; + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) -/** - * Previous log timestamp. - */ + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } -var prevTime; + this._hash = [ipad] +} -/** - * Select a color. - * - * @return {Number} - * @api private - */ +inherits(Hmac, Base) -function selectColor() { - return exports.colors[prevColor++ % exports.colors.length]; +Hmac.prototype._update = function (data) { + this._hash.push(data) } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ +Hmac.prototype._final = function () { + var h = this._alg(Buffer.concat(this._hash)) + return this._alg(Buffer.concat([this._opad, h])) +} +module.exports = Hmac -function debug(namespace) { +},{"111":111,"161":161,"57":57}],64:[function(require,module,exports){ +(function() { + var base64map + = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', - // define the `disabled` version - function disabled() { - } - disabled.enabled = false; + crypt = { + // Bit-wise rotation left + rotl: function(n, b) { + return (n << b) | (n >>> (32 - b)); + }, - // define the `enabled` version - function enabled() { + // Bit-wise rotation right + rotr: function(n, b) { + return (n << (32 - b)) | (n >>> b); + }, - var self = enabled; + // Swap big-endian to little-endian and vice versa + endian: function(n) { + // If number given, swap endian + if (n.constructor == Number) { + return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; + } - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + // Else, assume array and swap all items + for (var i = 0; i < n.length; i++) + n[i] = crypt.endian(n[i]); + return n; + }, - // add the `color` if not set - if (null == self.useColors) self.useColors = exports.useColors(); - if (null == self.color && self.useColors) self.color = selectColor(); + // Generate an array of any length of random bytes + randomBytes: function(n) { + for (var bytes = []; n > 0; n--) + bytes.push(Math.floor(Math.random() * 256)); + return bytes; + }, - var args = Array.prototype.slice.call(arguments); + // Convert a byte array to big-endian 32-bit words + bytesToWords: function(bytes) { + for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) + words[b >>> 5] |= bytes[i] << (24 - b % 32); + return words; + }, - args[0] = exports.coerce(args[0]); + // Convert big-endian 32-bit words to a byte array + wordsToBytes: function(words) { + for (var bytes = [], b = 0; b < words.length * 32; b += 8) + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); + return bytes; + }, - if ('string' !== typeof args[0]) { - // anything else let's inspect with %o - args = ['%o'].concat(args); - } + // Convert a byte array to a hex string + bytesToHex: function(bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + } + return hex.join(''); + }, - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + // Convert a hex string to a byte array + hexToBytes: function(hex) { + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.substr(c, 2), 16)); + return bytes; + }, - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; + // Convert a byte array to a base-64 string + bytesToBase64: function(bytes) { + for (var base64 = [], i = 0; i < bytes.length; i += 3) { + var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + for (var j = 0; j < 4; j++) + if (i * 8 + j * 6 <= bytes.length * 8) + base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); + else + base64.push('='); } - return match; - }); + return base64.join(''); + }, - if ('function' === typeof exports.formatArgs) { - args = exports.formatArgs.apply(self, args); + // Convert a base-64 string to a byte array + base64ToBytes: function(base64) { + // Remove non-base-64 characters + base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); + + for (var bytes = [], i = 0, imod4 = 0; i < base64.length; + imod4 = ++i % 4) { + if (imod4 == 0) continue; + bytes.push(((base64map.indexOf(base64.charAt(i - 1)) + & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) + | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); + } + return bytes; } - var logFn = enabled.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - enabled.enabled = true; + }; + + module.exports = crypt; +})(); - var fn = exports.enabled(namespace) ? enabled : disabled; +},{}],65:[function(require,module,exports){ +'use strict' - fn.namespace = namespace; +exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require(158) +exports.createHash = exports.Hash = require(60) +exports.createHmac = exports.Hmac = require(62) - return fn; +var algos = require(46) +var algoKeys = Object.keys(algos) +var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) +exports.getHashes = function () { + return hashes } -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ +var p = require(128) +exports.pbkdf2 = p.pbkdf2 +exports.pbkdf2Sync = p.pbkdf2Sync -function enable(namespaces) { - exports.save(namespaces); +var aes = require(42) - var split = (namespaces || '').split(/[\s,]+/); - var len = split.length; +exports.Cipher = aes.Cipher +exports.createCipher = aes.createCipher +exports.Cipheriv = aes.Cipheriv +exports.createCipheriv = aes.createCipheriv +exports.Decipher = aes.Decipher +exports.createDecipher = aes.createDecipher +exports.Decipheriv = aes.Decipheriv +exports.createDecipheriv = aes.createDecipheriv +exports.getCiphers = aes.getCiphers +exports.listCiphers = aes.listCiphers - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} +var dh = require(72) -/** - * Disable debug output. - * - * @api public - */ +exports.DiffieHellmanGroup = dh.DiffieHellmanGroup +exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup +exports.getDiffieHellman = dh.getDiffieHellman +exports.createDiffieHellman = dh.createDiffieHellman +exports.DiffieHellman = dh.DiffieHellman -function disable() { - exports.enable(''); -} +var sign = require(49) -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +exports.createSign = sign.createSign +exports.Sign = sign.Sign +exports.createVerify = sign.createVerify +exports.Verify = sign.Verify -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} +exports.createECDH = require(59) -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ +var publicEncrypt = require(152) -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} +exports.publicEncrypt = publicEncrypt.publicEncrypt +exports.privateEncrypt = publicEncrypt.privateEncrypt +exports.publicDecrypt = publicEncrypt.publicDecrypt +exports.privateDecrypt = publicEncrypt.privateDecrypt -},{"107":107}],59:[function(require,module,exports){ +// the least I can do is make error messages for the rest of the node.js/crypto api. +// ;[ +// 'createCredentials' +// ].forEach(function (name) { +// exports[name] = function () { +// throw new Error([ +// 'sorry, ' + name + ' is not implemented yet', +// 'we accept pull requests', +// 'https://github.com/crypto-browserify/crypto-browserify' +// ].join('\n')) +// } +// }) + +var rf = require(159) + +exports.randomFill = rf.randomFill +exports.randomFillSync = rf.randomFillSync + +exports.createCredentials = function () { + throw new Error([ + 'sorry, createCredentials is not implemented yet', + 'we accept pull requests', + 'https://github.com/crypto-browserify/crypto-browserify' + ].join('\n')) +} + +exports.constants = { + 'DH_CHECK_P_NOT_SAFE_PRIME': 2, + 'DH_CHECK_P_NOT_PRIME': 1, + 'DH_UNABLE_TO_CHECK_GENERATOR': 4, + 'DH_NOT_SUITABLE_GENERATOR': 8, + 'NPN_ENABLED': 1, + 'ALPN_ENABLED': 1, + 'RSA_PKCS1_PADDING': 1, + 'RSA_SSLV23_PADDING': 2, + 'RSA_NO_PADDING': 3, + 'RSA_PKCS1_OAEP_PADDING': 4, + 'RSA_X931_PADDING': 5, + 'RSA_PKCS1_PSS_PADDING': 6, + 'POINT_CONVERSION_COMPRESSED': 2, + 'POINT_CONVERSION_UNCOMPRESSED': 4, + 'POINT_CONVERSION_HYBRID': 6 +} + +},{"128":128,"152":152,"158":158,"159":159,"42":42,"46":46,"49":49,"59":59,"60":60,"62":62,"72":72}],66:[function(require,module,exports){ 'use strict'; -exports.utils = require(64); -exports.Cipher = require(61); -exports.DES = require(62); -exports.CBC = require(60); -exports.EDE = require(63); +exports.utils = require(71); +exports.Cipher = require(68); +exports.DES = require(69); +exports.CBC = require(67); +exports.EDE = require(70); -},{"60":60,"61":61,"62":62,"63":63,"64":64}],60:[function(require,module,exports){ +},{"67":67,"68":68,"69":69,"70":70,"71":71}],67:[function(require,module,exports){ 'use strict'; -var assert = require(106); -var inherits = require(97); +var assert = require(121); +var inherits = require(111); var proto = {}; @@ -10047,10 +11313,10 @@ proto._update = function _update(inp, inOff, out, outOff) { } }; -},{"106":106,"97":97}],61:[function(require,module,exports){ +},{"111":111,"121":121}],68:[function(require,module,exports){ 'use strict'; -var assert = require(106); +var assert = require(121); function Cipher(options) { this.options = options; @@ -10190,13 +11456,13 @@ Cipher.prototype._finalDecrypt = function _finalDecrypt() { return this._unpad(out); }; -},{"106":106}],62:[function(require,module,exports){ +},{"121":121}],69:[function(require,module,exports){ 'use strict'; -var assert = require(106); -var inherits = require(97); +var assert = require(121); +var inherits = require(111); -var des = require(59); +var des = require(66); var utils = des.utils; var Cipher = des.Cipher; @@ -10335,13 +11601,13 @@ DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { utils.rip(l, r, out, off); }; -},{"106":106,"59":59,"97":97}],63:[function(require,module,exports){ +},{"111":111,"121":121,"66":66}],70:[function(require,module,exports){ 'use strict'; -var assert = require(106); -var inherits = require(97); +var assert = require(121); +var inherits = require(111); -var des = require(59); +var des = require(66); var Cipher = des.Cipher; var DES = des.DES; @@ -10392,7 +11658,7 @@ EDE.prototype._update = function _update(inp, inOff, out, outOff) { EDE.prototype._pad = DES.prototype._pad; EDE.prototype._unpad = DES.prototype._unpad; -},{"106":106,"59":59,"97":97}],64:[function(require,module,exports){ +},{"111":111,"121":121,"66":66}],71:[function(require,module,exports){ 'use strict'; exports.readUInt32BE = function readUInt32BE(bytes, off) { @@ -10650,12 +11916,12 @@ exports.padSplit = function padSplit(num, size, group) { return out.join(' '); }; -},{}],65:[function(require,module,exports){ +},{}],72:[function(require,module,exports){ (function (Buffer){ -var generatePrime = require(67) -var primes = require(68) +var generatePrime = require(74) +var primes = require(75) -var DH = require(66) +var DH = require(73) function getDiffieHellman (mod) { var prime = new Buffer(primes[mod].prime, 'hex') @@ -10695,19 +11961,19 @@ function createDiffieHellman (prime, enc, generator, genc) { exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman -}).call(this,require(47).Buffer) -},{"47":47,"66":66,"67":67,"68":68}],66:[function(require,module,exports){ +}).call(this,require(54).Buffer) +},{"54":54,"73":73,"74":74,"75":75}],73:[function(require,module,exports){ (function (Buffer){ -var BN = require(18); -var MillerRabin = require(105); +var BN = require(22); +var MillerRabin = require(120); var millerRabin = new MillerRabin(); var TWENTYFOUR = new BN(24); var ELEVEN = new BN(11); var TEN = new BN(10); var THREE = new BN(3); var SEVEN = new BN(7); -var primes = require(67); -var randomBytes = require(136); +var primes = require(74); +var randomBytes = require(158); module.exports = DH; function setPublicKey(pub, enc) { @@ -10863,15 +12129,15 @@ function formatReturnValue(bn, enc) { } } -}).call(this,require(47).Buffer) -},{"105":105,"136":136,"18":18,"47":47,"67":67}],67:[function(require,module,exports){ -var randomBytes = require(136); +}).call(this,require(54).Buffer) +},{"120":120,"158":158,"22":22,"54":54,"74":74}],74:[function(require,module,exports){ +var randomBytes = require(158); module.exports = findPrime; findPrime.simpleSieve = simpleSieve; findPrime.fermatTest = fermatTest; -var BN = require(18); +var BN = require(22); var TWENTYFOUR = new BN(24); -var MillerRabin = require(105); +var MillerRabin = require(120); var millerRabin = new MillerRabin(); var ONE = new BN(1); var TWO = new BN(2); @@ -10971,7 +12237,7 @@ function findPrime(bits, gen) { } -},{"105":105,"136":136,"18":18}],68:[function(require,module,exports){ +},{"120":120,"158":158,"22":22}],75:[function(require,module,exports){ module.exports={ "modp1": { "gen": "02", @@ -11006,28 +12272,26 @@ module.exports={ "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" } } -},{}],69:[function(require,module,exports){ +},{}],76:[function(require,module,exports){ 'use strict'; var elliptic = exports; -elliptic.version = require(85).version; -elliptic.utils = require(84); -elliptic.rand = require(19); -elliptic.hmacDRBG = require(82); -elliptic.curve = require(72); -elliptic.curves = require(75); +elliptic.version = require(91).version; +elliptic.utils = require(90); +elliptic.rand = require(23); +elliptic.curve = require(79); +elliptic.curves = require(82); // Protocols -elliptic.ec = require(76); -elliptic.eddsa = require(79); +elliptic.ec = require(83); +elliptic.eddsa = require(86); -},{"19":19,"72":72,"75":75,"76":76,"79":79,"82":82,"84":84,"85":85}],70:[function(require,module,exports){ +},{"23":23,"79":79,"82":82,"83":83,"86":86,"90":90,"91":91}],77:[function(require,module,exports){ 'use strict'; -var BN = require(18); -var elliptic = require(69); -var utils = elliptic.utils; +var BN = require(22); +var utils = require(90); var getNAF = utils.getNAF; var getJSF = utils.getJSF; var assert = utils.assert; @@ -11399,16 +12663,15 @@ BasePoint.prototype.dblp = function dblp(k) { return r; }; -},{"18":18,"69":69}],71:[function(require,module,exports){ +},{"22":22,"90":90}],78:[function(require,module,exports){ 'use strict'; -var curve = require(72); -var elliptic = require(69); -var BN = require(18); -var inherits = require(97); -var Base = curve.base; +var utils = require(90); +var BN = require(22); +var inherits = require(111); +var Base = require(77); -var assert = elliptic.utils.assert; +var assert = utils.assert; function EdwardsCurve(conf) { // NOTE: Important as we are creating point in Base.call() @@ -11476,10 +12739,10 @@ EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { if (!y.red) y = y.toRed(this.red); - // x^2 = (y^2 - 1) / (d y^2 + 1) + // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) var y2 = y.redSqr(); - var lhs = y2.redSub(this.one); - var rhs = y2.redMul(this.d).redAdd(this.one); + var lhs = y2.redSub(this.c2); + var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); var x2 = lhs.redMul(rhs.redInvm()); if (x2.cmp(this.zero) === 0) { @@ -11493,7 +12756,7 @@ EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) throw new Error('invalid point'); - if (x.isOdd() !== odd) + if (x.fromRed().isOdd() !== odd) x = x.redNeg(); return this.point(x, y); @@ -11570,7 +12833,8 @@ Point.prototype.inspect = function inspect() { Point.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.x.cmpn(0) === 0 && - this.y.cmp(this.z) === 0; + (this.y.cmp(this.z) === 0 || + (this.zOne && this.y.cmp(this.curve.c) === 0)); }; Point.prototype._extDbl = function _extDbl() { @@ -11651,7 +12915,7 @@ Point.prototype._projDbl = function _projDbl() { // E = C + D var e = c.redAdd(d); // H = (c * Z1)^2 - var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); + var h = this.curve._mulC(this.z).redSqr(); // J = E - 2 * H var j = e.redSub(h).redSub(h); // X3 = c * (B - E) * J @@ -11827,33 +13091,30 @@ Point.prototype.eqXToP = function eqXToP(x) { if (this.x.cmp(rx) === 0) return true; } - return false; }; // Compatibility with BaseCurve Point.prototype.toP = Point.prototype.normalize; Point.prototype.mixedAdd = Point.prototype.add; -},{"18":18,"69":69,"72":72,"97":97}],72:[function(require,module,exports){ +},{"111":111,"22":22,"77":77,"90":90}],79:[function(require,module,exports){ 'use strict'; var curve = exports; -curve.base = require(70); -curve.short = require(74); -curve.mont = require(73); -curve.edwards = require(71); +curve.base = require(77); +curve.short = require(81); +curve.mont = require(80); +curve.edwards = require(78); -},{"70":70,"71":71,"73":73,"74":74}],73:[function(require,module,exports){ +},{"77":77,"78":78,"80":80,"81":81}],80:[function(require,module,exports){ 'use strict'; -var curve = require(72); -var BN = require(18); -var inherits = require(97); -var Base = curve.base; +var BN = require(22); +var inherits = require(111); +var Base = require(77); -var elliptic = require(69); -var utils = elliptic.utils; +var utils = require(90); function MontCurve(conf) { Base.call(this, 'mont', conf); @@ -12026,16 +13287,15 @@ Point.prototype.getX = function getX() { return this.x.fromRed(); }; -},{"18":18,"69":69,"72":72,"97":97}],74:[function(require,module,exports){ +},{"111":111,"22":22,"77":77,"90":90}],81:[function(require,module,exports){ 'use strict'; -var curve = require(72); -var elliptic = require(69); -var BN = require(18); -var inherits = require(97); -var Base = curve.base; +var utils = require(90); +var BN = require(22); +var inherits = require(111); +var Base = require(77); -var assert = elliptic.utils.assert; +var assert = utils.assert; function ShortCurve(conf) { Base.call(this, 'short', conf); @@ -12451,8 +13711,9 @@ Point.prototype.getY = function getY() { Point.prototype.mul = function mul(k) { k = new BN(k, 16); - - if (this._hasDoubles(k)) + if (this.isInfinity()) + return this; + else if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k); else if (this.curve.endo) return this.curve._endoWnafMulAdd([ this ], [ k ]); @@ -12950,7 +14211,6 @@ JPoint.prototype.eqXToP = function eqXToP(x) { if (this.x.cmp(rx) === 0) return true; } - return false; }; JPoint.prototype.inspect = function inspect() { @@ -12966,23 +14226,24 @@ JPoint.prototype.isInfinity = function isInfinity() { return this.z.cmpn(0) === 0; }; -},{"18":18,"69":69,"72":72,"97":97}],75:[function(require,module,exports){ +},{"111":111,"22":22,"77":77,"90":90}],82:[function(require,module,exports){ 'use strict'; var curves = exports; -var hash = require(88); -var elliptic = require(69); +var hash = require(95); +var curve = require(79); +var utils = require(90); -var assert = elliptic.utils.assert; +var assert = utils.assert; function PresetCurve(options) { if (options.type === 'short') - this.curve = new elliptic.curve.short(options); + this.curve = new curve.short(options); else if (options.type === 'edwards') - this.curve = new elliptic.curve.edwards(options); + this.curve = new curve.edwards(options); else - this.curve = new elliptic.curve.mont(options); + this.curve = new curve.mont(options); this.g = this.curve.g; this.n = this.curve.n; this.hash = options.hash; @@ -13136,7 +14397,7 @@ defineCurve('ed25519', { var pre; try { - pre = require(83); + pre = require(89); } catch (e) { pre = undefined; } @@ -13173,16 +14434,18 @@ defineCurve('secp256k1', { ] }); -},{"69":69,"83":83,"88":88}],76:[function(require,module,exports){ +},{"79":79,"89":89,"90":90,"95":95}],83:[function(require,module,exports){ 'use strict'; -var BN = require(18); -var elliptic = require(69); -var utils = elliptic.utils; +var BN = require(22); +var HmacDRBG = require(107); +var utils = require(90); +var curves = require(82); +var rand = require(23); var assert = utils.assert; -var KeyPair = require(77); -var Signature = require(78); +var KeyPair = require(84); +var Signature = require(85); function EC(options) { if (!(this instanceof EC)) @@ -13190,13 +14453,13 @@ function EC(options) { // Shortcut `elliptic.ec(curve-name)` if (typeof options === 'string') { - assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); + assert(curves.hasOwnProperty(options), 'Unknown curve ' + options); - options = elliptic.curves[options]; + options = curves[options]; } // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof elliptic.curves.PresetCurve) + if (options instanceof curves.PresetCurve) options = { curve: options }; this.curve = options.curve.curve; @@ -13230,10 +14493,12 @@ EC.prototype.genKeyPair = function genKeyPair(options) { options = {}; // Instantiate Hmac_DRBG - var drbg = new elliptic.hmacDRBG({ + var drbg = new HmacDRBG({ hash: this.hash, pers: options.pers, - entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', nonce: this.n.toArray() }); @@ -13278,12 +14543,12 @@ EC.prototype.sign = function sign(msg, key, enc, options) { var nonce = msg.toArray('be', bytes); // Instantiate Hmac_DRBG - var drbg = new elliptic.hmacDRBG({ + var drbg = new HmacDRBG({ hash: this.hash, entropy: bkey, nonce: nonce, pers: options.pers, - persEnc: options.persEnc + persEnc: options.persEnc || 'utf8' }); // Number of bytes to generate @@ -13412,12 +14677,11 @@ EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { throw new Error('Unable to find valid recovery factor'); }; -},{"18":18,"69":69,"77":77,"78":78}],77:[function(require,module,exports){ +},{"107":107,"22":22,"23":23,"82":82,"84":84,"85":85,"90":90}],84:[function(require,module,exports){ 'use strict'; -var BN = require(18); -var elliptic = require(69); -var utils = elliptic.utils; +var BN = require(22); +var utils = require(90); var assert = utils.assert; function KeyPair(ec, options) { @@ -13533,13 +14797,12 @@ KeyPair.prototype.inspect = function inspect() { ' pub: ' + (this.pub && this.pub.inspect()) + ' >'; }; -},{"18":18,"69":69}],78:[function(require,module,exports){ +},{"22":22,"90":90}],85:[function(require,module,exports){ 'use strict'; -var BN = require(18); +var BN = require(22); -var elliptic = require(69); -var utils = elliptic.utils; +var utils = require(90); var assert = utils.assert; function Signature(options, enc) { @@ -13670,16 +14933,16 @@ Signature.prototype.toDER = function toDER(enc) { return utils.encode(res, enc); }; -},{"18":18,"69":69}],79:[function(require,module,exports){ +},{"22":22,"90":90}],86:[function(require,module,exports){ 'use strict'; -var hash = require(88); -var elliptic = require(69); -var utils = elliptic.utils; +var hash = require(95); +var curves = require(82); +var utils = require(90); var assert = utils.assert; var parseBytes = utils.parseBytes; -var KeyPair = require(80); -var Signature = require(81); +var KeyPair = require(87); +var Signature = require(88); function EDDSA(curve) { assert(curve === 'ed25519', 'only tested with ed25519 so far'); @@ -13687,7 +14950,7 @@ function EDDSA(curve) { if (!(this instanceof EDDSA)) return new EDDSA(curve); - var curve = elliptic.curves[curve].curve; + var curve = curves[curve].curve; this.curve = curve; this.g = curve.g; this.g.precompute(curve.n.bitLength() + 1); @@ -13790,11 +15053,10 @@ EDDSA.prototype.isPoint = function isPoint(val) { return val instanceof this.pointClass; }; -},{"69":69,"80":80,"81":81,"88":88}],80:[function(require,module,exports){ +},{"82":82,"87":87,"88":88,"90":90,"95":95}],87:[function(require,module,exports){ 'use strict'; -var elliptic = require(69); -var utils = elliptic.utils; +var utils = require(90); var assert = utils.assert; var parseBytes = utils.parseBytes; var cachedProperty = utils.cachedProperty; @@ -13888,12 +15150,11 @@ KeyPair.prototype.getPublic = function getPublic(enc) { module.exports = KeyPair; -},{"69":69}],81:[function(require,module,exports){ +},{"90":90}],88:[function(require,module,exports){ 'use strict'; -var BN = require(18); -var elliptic = require(69); -var utils = elliptic.utils; +var BN = require(22); +var utils = require(90); var assert = utils.assert; var cachedProperty = utils.cachedProperty; var parseBytes = utils.parseBytes; @@ -13956,123 +15217,7 @@ Signature.prototype.toHex = function toHex() { module.exports = Signature; -},{"18":18,"69":69}],82:[function(require,module,exports){ -'use strict'; - -var hash = require(88); -var elliptic = require(69); -var utils = elliptic.utils; -var assert = utils.assert; - -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; - - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; - - this.reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; - - var entropy = utils.toArray(options.entropy, options.entropyEnc); - var nonce = utils.toArray(options.nonce, options.nonceEnc); - var pers = utils.toArray(options.pers, options.persEnc); - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -module.exports = HmacDRBG; - -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; - } - - this._update(seed); - this.reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; - -HmacDRBG.prototype._hmac = function hmac() { - return new hash.hmac(this.hash, this.K); -}; - -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; - - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; - -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils.toBuffer(entropy, entropyEnc); - add = utils.toBuffer(add, addEnc); - - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this.reseed = 1; -}; - -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this.reseed > this.reseedInterval) - throw new Error('Reseed is required'); - - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } - - // Optional additional data - if (add) { - add = utils.toArray(add, addEnc); - this._update(add); - } - - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } - - var res = temp.slice(0, len); - this._update(add); - this.reseed++; - return utils.encode(res, enc); -}; - -},{"69":69,"88":88}],83:[function(require,module,exports){ +},{"22":22,"90":90}],89:[function(require,module,exports){ module.exports = { doubles: { step: 4, @@ -14847,78 +15992,26 @@ module.exports = { '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' ], [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] - } -}; - -},{}],84:[function(require,module,exports){ -'use strict'; - -var utils = exports; -var BN = require(18); - -utils.assert = function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -}; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - return res; - } - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] } - return res; -} -utils.toArray = toArray; +}; -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; +},{}],90:[function(require,module,exports){ +'use strict'; -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; +var utils = exports; +var BN = require(22); +var minAssert = require(121); +var minUtils = require(122); -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; +utils.assert = minAssert; +utils.toArray = minUtils.toArray; +utils.zero2 = minUtils.zero2; +utils.toHex = minUtils.toHex; +utils.encode = minUtils.encode; // Represent num in a w-NAF form function getNAF(num, w) { @@ -15028,55 +16121,32 @@ function intFromLE(bytes) { utils.intFromLE = intFromLE; -},{"18":18}],85:[function(require,module,exports){ +},{"121":121,"122":122,"22":22}],91:[function(require,module,exports){ module.exports={ - "_args": [ - [ - { - "raw": "elliptic@^6.0.0", - "scope": null, - "escapedName": "elliptic", - "name": "elliptic", - "rawSpec": "^6.0.0", - "spec": ">=6.0.0 <7.0.0", - "type": "range" - }, - "/Users/nolan/workspace/pouchdb-quick-search/node_modules/browserify-sign" - ] - ], - "_from": "elliptic@>=6.0.0 <7.0.0", - "_id": "elliptic@6.3.3", - "_inCache": true, + "_from": "elliptic@^6.0.0", + "_id": "elliptic@6.5.1", + "_inBundle": false, + "_integrity": "sha512-xvJINNLbTeWQjrl6X+7eQCrIy/YPv5XCpKW6kB5mKvtnGILoLDcySuwomfdzt0BMdLNVnuRNTuzKNHj0bva1Cg==", "_location": "/elliptic", - "_nodeVersion": "7.0.0", - "_npmOperationalInternal": { - "host": "packages-18-east.internal.npmjs.com", - "tmp": "tmp/elliptic-6.3.3.tgz_1486422837740_0.10658654430881143" - }, - "_npmUser": { - "name": "indutny", - "email": "fedor@indutny.com" - }, - "_npmVersion": "3.10.8", "_phantomChildren": {}, "_requested": { + "type": "range", + "registry": true, "raw": "elliptic@^6.0.0", - "scope": null, - "escapedName": "elliptic", "name": "elliptic", + "escapedName": "elliptic", "rawSpec": "^6.0.0", - "spec": ">=6.0.0 <7.0.0", - "type": "range" + "saveSpec": null, + "fetchSpec": "^6.0.0" }, "_requiredBy": [ "/browserify-sign", "/create-ecdh" ], - "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.3.3.tgz", - "_shasum": "5482d9646d54bcb89fd7d994fc9e2e9568876e3f", - "_shrinkwrap": null, + "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.1.tgz", + "_shasum": "c380f5f909bf1b9b4428d028cd18d3b0efd6b52b", "_spec": "elliptic@^6.0.0", - "_where": "/Users/nolan/workspace/pouchdb-quick-search/node_modules/browserify-sign", + "_where": "/home/pawel/workspace/pouchdb-quick-search/node_modules/browserify-sign", "author": { "name": "Fedor Indutny", "email": "fedor@indutny.com" @@ -15084,38 +16154,37 @@ module.exports={ "bugs": { "url": "https://github.com/indutny/elliptic/issues" }, + "bundleDependencies": false, "dependencies": { "bn.js": "^4.4.0", "brorand": "^1.0.1", "hash.js": "^1.0.0", - "inherits": "^2.0.1" + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" }, + "deprecated": false, "description": "EC cryptography", "devDependencies": { "brfs": "^1.4.3", - "coveralls": "^2.11.3", - "grunt": "^0.4.5", + "coveralls": "^3.0.4", + "grunt": "^1.0.4", "grunt-browserify": "^5.0.0", "grunt-cli": "^1.2.0", "grunt-contrib-connect": "^1.0.0", "grunt-contrib-copy": "^1.0.0", "grunt-contrib-uglify": "^1.0.1", "grunt-mocha-istanbul": "^3.0.1", - "grunt-saucelabs": "^8.6.2", + "grunt-saucelabs": "^9.0.1", "istanbul": "^0.4.2", - "jscs": "^2.9.0", + "jscs": "^3.0.7", "jshint": "^2.6.0", - "mocha": "^2.1.0" - }, - "directories": {}, - "dist": { - "shasum": "5482d9646d54bcb89fd7d994fc9e2e9568876e3f", - "tarball": "https://registry.npmjs.org/elliptic/-/elliptic-6.3.3.tgz" + "mocha": "^6.1.4" }, "files": [ "lib" ], - "gitHead": "63aee8d697e9b7fac37ece24222029117a890a7e", "homepage": "https://github.com/indutny/elliptic", "keywords": [ "EC", @@ -15125,15 +16194,7 @@ module.exports={ ], "license": "MIT", "main": "lib/elliptic.js", - "maintainers": [ - { - "name": "indutny", - "email": "fedor@indutny.com" - } - ], "name": "elliptic", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+ssh://git@github.com/indutny/elliptic.git" @@ -15146,10 +16207,10 @@ module.exports={ "unit": "istanbul test _mocha --reporter=spec test/index.js", "version": "grunt dist && git add dist/" }, - "version": "6.3.3" + "version": "6.5.1" } -},{}],86:[function(require,module,exports){ +},{}],92:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -15396,6824 +16457,6470 @@ EventEmitter.prototype.removeAllListeners = function(type) { return this; } - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - -},{}],87:[function(require,module,exports){ -(function (Buffer){ -var md5 = require(54) -module.exports = EVP_BytesToKey -function EVP_BytesToKey (password, salt, keyLen, ivLen) { - if (!Buffer.isBuffer(password)) { - password = new Buffer(password, 'binary') - } - if (salt && !Buffer.isBuffer(salt)) { - salt = new Buffer(salt, 'binary') - } - keyLen = keyLen / 8 - ivLen = ivLen || 0 - var ki = 0 - var ii = 0 - var key = new Buffer(keyLen) - var iv = new Buffer(ivLen) - var addmd = 0 - var md_buf - var i - var bufs = [] - while (true) { - if (addmd++ > 0) { - bufs.push(md_buf) - } - bufs.push(password) - if (salt) { - bufs.push(salt) - } - md_buf = md5(Buffer.concat(bufs)) - bufs = [] - i = 0 - if (keyLen > 0) { - while (true) { - if (keyLen === 0) { - break - } - if (i === md_buf.length) { - break - } - key[ki++] = md_buf[i] - keyLen-- - i++ - } - } - if (ivLen > 0 && i !== md_buf.length) { - while (true) { - if (ivLen === 0) { - break - } - if (i === md_buf.length) { - break - } - iv[ii++] = md_buf[i] - ivLen-- - i++ - } - } - if (keyLen === 0 && ivLen === 0) { - break - } - } - for (i = 0; i < md_buf.length; i++) { - md_buf[i] = 0 - } - return { - key: key, - iv: iv - } -} - -}).call(this,require(47).Buffer) -},{"47":47,"54":54}],88:[function(require,module,exports){ -var hash = exports; - -hash.utils = require(93); -hash.common = require(89); -hash.sha = require(92); -hash.ripemd = require(91); -hash.hmac = require(90); - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.sha384 = hash.sha.sha384; -hash.sha512 = hash.sha.sha512; -hash.ripemd160 = hash.ripemd.ripemd160; - -},{"89":89,"90":90,"91":91,"92":92,"93":93}],89:[function(require,module,exports){ -var hash = require(88); -var utils = hash.utils; -var assert = utils.assert; - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -exports.BlockHash = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; -}; - -},{"88":88}],90:[function(require,module,exports){ -var hmac = exports; - -var hash = require(88); -var utils = hash.utils; -var assert = utils.assert; - -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -module.exports = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (var i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); + listeners = this._events[type]; - // 0x36 ^ 0x5c = 0x6a - for (var i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); return this; }; -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; }; -},{"88":88}],91:[function(require,module,exports){ -var hash = require(88); -var utils = hash.utils; - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_3 = utils.sum32_3; -var sum32_4 = utils.sum32_4; -var BlockHash = hash.common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash); -exports.ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; -RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32( - rotl32( - sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32(C, 10); - C = B; - B = T; - T = sum32( - rotl32( - sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32(Ch, 10); - Ch = Bh; - Bh = T; + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; } - T = sum32_3(this.h[1], C, Dh); - this.h[1] = sum32_3(this.h[2], D, Eh); - this.h[2] = sum32_3(this.h[3], E, Ah); - this.h[3] = sum32_3(this.h[4], A, Bh); - this.h[4] = sum32_3(this.h[0], B, Ch); - this.h[0] = T; + return 0; }; -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); }; -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); +function isFunction(arg) { + return typeof arg === 'function'; } -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; +function isNumber(arg) { + return typeof arg === 'number'; } -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; } -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -]; +function isUndefined(arg) { + return arg === void 0; +} -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; +},{}],93:[function(require,module,exports){ +var Buffer = require(161).Buffer +var MD5 = require(118) -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -]; +/* eslint-disable camelcase */ +function EVP_BytesToKey (password, salt, keyBits, ivLen) { + if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') + if (salt) { + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') + if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') + } -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; + var keyLen = keyBits / 8 + var key = Buffer.alloc(keyLen) + var iv = Buffer.alloc(ivLen || 0) + var tmp = Buffer.alloc(0) -},{"88":88}],92:[function(require,module,exports){ -var hash = require(88); -var utils = hash.utils; -var assert = utils.assert; + while (keyLen > 0 || ivLen > 0) { + var hash = new MD5() + hash.update(tmp) + hash.update(password) + if (salt) hash.update(salt) + tmp = hash.digest() -var rotr32 = utils.rotr32; -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_4 = utils.sum32_4; -var sum32_5 = utils.sum32_5; -var rotr64_hi = utils.rotr64_hi; -var rotr64_lo = utils.rotr64_lo; -var shr64_hi = utils.shr64_hi; -var shr64_lo = utils.shr64_lo; -var sum64 = utils.sum64; -var sum64_hi = utils.sum64_hi; -var sum64_lo = utils.sum64_lo; -var sum64_4_hi = utils.sum64_4_hi; -var sum64_4_lo = utils.sum64_4_lo; -var sum64_5_hi = utils.sum64_5_hi; -var sum64_5_lo = utils.sum64_5_lo; -var BlockHash = hash.common.BlockHash; + var used = 0 -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; + if (keyLen > 0) { + var keyStart = key.length - keyLen + used = Math.min(keyLen, tmp.length) + tmp.copy(key, keyStart, 0, used) + keyLen -= used + } -var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; + if (used < tmp.length && ivLen > 0) { + var ivStart = iv.length - ivLen + var length = Math.min(ivLen, tmp.length - used) + tmp.copy(iv, ivStart, used, used + length) + ivLen -= length + } + } + + tmp.fill(0) + return { key: key, iv: iv } +} -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; +module.exports = EVP_BytesToKey -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); +},{"118":118,"161":161}],94:[function(require,module,exports){ +'use strict' +var Buffer = require(161).Buffer +var Transform = require(171).Transform +var inherits = require(111) - BlockHash.call(this); - this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; - this.k = sha256_K; - this.W = new Array(64); +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } } -utils.inherits(SHA256, BlockHash); -exports.sha256 = SHA256; -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; +function HashBase (blockSize) { + Transform.call(this) -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + this._finalized = false +} - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; +inherits(HashBase, Transform) - assert(this.k.length === W.length); - for (var i = 0; i < W.length; i++) { - var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); - var T2 = sum32(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32(d, T1); - d = c; - c = b; - b = a; - a = sum32(T1, T2); +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err } - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); - this.h[5] = sum32(this.h[5], f); - this.h[6] = sum32(this.h[6], g); - this.h[7] = sum32(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; + callback(error) +} -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } - SHA256.call(this); - this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + callback(error) } -utils.inherits(SHA224, SHA256); -exports.sha224 = SHA224; -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } - BlockHash.call(this); - this.h = [ 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); + return this } -utils.inherits(SHA512, BlockHash); -exports.sha512 = SHA512; -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) - W[i] = sum64_4_hi(c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo(c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } -}; + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 -SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); + return digest +} - var W = this.W; +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; +module.exports = HashBase - assert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; +},{"111":111,"161":161,"171":171}],95:[function(require,module,exports){ +var hash = exports; - var T1_hi = sum64_5_hi(c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo(c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - var c0_hi = s0_512_hi(ah, al); - var c0_lo = s0_512_lo(ah, al); - var c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); - var c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); +hash.utils = require(106); +hash.common = require(96); +hash.sha = require(99); +hash.ripemd = require(98); +hash.hmac = require(97); - var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.sha384 = hash.sha.sha384; +hash.sha512 = hash.sha.sha512; +hash.ripemd160 = hash.ripemd.ripemd160; - hh = gh; - hl = gl; +},{"106":106,"96":96,"97":97,"98":98,"99":99}],96:[function(require,module,exports){ +'use strict'; - gh = fh; - gl = fl; +var utils = require(106); +var assert = require(121); - fh = eh; - fl = el; +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; - eh = sum64_hi(dh, dl, T1_hi, T1_lo); - el = sum64_lo(dl, dl, T1_hi, T1_lo); + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; - dh = ch; - dl = cl; +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; - ch = bh; - cl = bl; + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; - bh = ah; - bl = al; + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; - ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); } - sum64(this.h, 0, ah, al); - sum64(this.h, 2, bh, bl); - sum64(this.h, 4, ch, cl); - sum64(this.h, 6, dh, dl); - sum64(this.h, 8, eh, el); - sum64(this.h, 10, fh, fl); - sum64(this.h, 12, gh, gl); - sum64(this.h, 14, hh, hl); + return this; }; -SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); }; -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; - SHA512.call(this); - this.h = [ 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, SHA512); -exports.sha384 = SHA384; + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); + return res; }; -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash.call(this); - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); -} - -utils.inherits(SHA1, BlockHash); -exports.sha1 = SHA1; +},{"106":106,"121":121}],97:[function(require,module,exports){ +'use strict'; -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; +var utils = require(106); +var assert = require(121); -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; - for(; i < W.length; i++) - W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); - for (var i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32(b, 30); - b = a; - a = t; - } + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); }; -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; }; -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} +},{"106":106,"121":121}],98:[function(require,module,exports){ +'use strict'; -function p32(x, y, z) { - return x ^ y ^ z; -} +var utils = require(106); +var common = require(96); -function s0_256(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); -} +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = common.BlockHash; -function s1_256(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); -} +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); -function g0_256(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); -} + BlockHash.call(this); -function g1_256(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; } +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; -function ch64_hi(xh, xl, yh, yl, zh, zl) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; -} +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; -function maj64_hi(xh, xl, yh, yl, zh, zl) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); } -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; } -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 28); - var c1_hi = rotr64_hi(xl, xh, 2); // 34 - var c2_hi = rotr64_hi(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; } -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 28); - var c1_lo = rotr64_lo(xl, xh, 2); // 34 - var c2_lo = rotr64_lo(xl, xh, 7); // 39 +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +]; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 14); - var c1_hi = rotr64_hi(xh, xl, 18); - var c2_hi = rotr64_hi(xl, xh, 9); // 41 +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +]; - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 14); - var c1_lo = rotr64_lo(xh, xl, 18); - var c2_lo = rotr64_lo(xl, xh, 9); // 41 +},{"106":106,"96":96}],99:[function(require,module,exports){ +'use strict'; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} +exports.sha1 = require(100); +exports.sha224 = require(101); +exports.sha256 = require(102); +exports.sha384 = require(103); +exports.sha512 = require(104); -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 1); - var c1_hi = rotr64_hi(xh, xl, 8); - var c2_hi = shr64_hi(xh, xl, 7); +},{"100":100,"101":101,"102":102,"103":103,"104":104}],100:[function(require,module,exports){ +'use strict'; - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} +var utils = require(106); +var common = require(96); +var shaCommon = require(105); -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 1); - var c1_lo = rotr64_lo(xh, xl, 8); - var c2_lo = shr64_lo(xh, xl, 7); +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_5 = utils.sum32_5; +var ft_1 = shaCommon.ft_1; +var BlockHash = common.BlockHash; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 19); - var c1_hi = rotr64_hi(xl, xh, 29); // 61 - var c2_hi = shr64_hi(xh, xl, 6); +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; + BlockHash.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); } -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 19); - var c1_lo = rotr64_lo(xl, xh, 29); // 61 - var c2_lo = shr64_lo(xh, xl, 6); +utils.inherits(SHA1, BlockHash); +module.exports = SHA1; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; -},{"88":88}],93:[function(require,module,exports){ -var utils = exports; -var inherits = require(97); +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -utils.toArray = toArray; + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -utils.htonl = htonl; + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; } - return res; -} -utils.toHex32 = toHex32; -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); else - return word; -} -utils.zero8 = zero8; + return utils.split32(this.h, 'big'); +}; -function join32(msg, start, end, endian) { - var len = end - start; - assert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -utils.join32 = join32; +},{"105":105,"106":106,"96":96}],101:[function(require,module,exports){ +'use strict'; -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -utils.split32 = split32; +var utils = require(106); +var SHA256 = require(102); -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -utils.rotr32 = rotr32; +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; } -utils.rotl32 = rotl32; +utils.inherits(SHA224, SHA256); +module.exports = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; -function sum32(a, b) { - return (a + b) >>> 0; -} -utils.sum32 = sum32; -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -utils.sum32_3 = sum32_3; +},{"102":102,"106":106}],102:[function(require,module,exports){ +'use strict'; -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -utils.sum32_4 = sum32_4; +var utils = require(106); +var common = require(96); +var shaCommon = require(105); +var assert = require(121); -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -utils.sum32_5 = sum32_5; +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var ch32 = shaCommon.ch32; +var maj32 = shaCommon.maj32; +var s0_256 = shaCommon.s0_256; +var s1_256 = shaCommon.s1_256; +var g0_256 = shaCommon.g0_256; +var g1_256 = shaCommon.g1_256; -function assert(cond, msg) { - if (!cond) - throw new Error(msg || 'Assertion failed'); -} -utils.assert = assert; +var BlockHash = common.BlockHash; -utils.inherits = inherits; +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); } -exports.sum64 = sum64; +utils.inherits(SHA256, BlockHash); +module.exports = SHA256; -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -}; -exports.sum64_hi = sum64_hi; +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -}; -exports.sum64_lo = sum64_lo; +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -}; -exports.sum64_4_hi = sum64_4_hi; + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -}; -exports.sum64_4_lo = sum64_4_lo; + assert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); }; -exports.sum64_5_hi = sum64_5_hi; -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; +},{"105":105,"106":106,"121":121,"96":96}],103:[function(require,module,exports){ +'use strict'; - return lo >>> 0; -}; -exports.sum64_5_lo = sum64_5_lo; +var utils = require(106); -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -}; -exports.rotr64_hi = rotr64_hi; +var SHA512 = require(104); -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -}; -exports.rotr64_lo = rotr64_lo; +function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); -function shr64_hi(ah, al, num) { - return ah >>> num; -}; -exports.shr64_hi = shr64_hi; + SHA512.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; +} +utils.inherits(SHA384, SHA512); +module.exports = SHA384; -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; + +SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); }; -exports.shr64_lo = shr64_lo; -},{"97":97}],94:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] +},{"104":104,"106":106}],104:[function(require,module,exports){ +'use strict'; - i += d +var utils = require(106); +var common = require(96); +var assert = require(121); - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} +var rotr64_hi = utils.rotr64_hi; +var rotr64_lo = utils.rotr64_lo; +var shr64_hi = utils.shr64_hi; +var shr64_lo = utils.shr64_lo; +var sum64 = utils.sum64; +var sum64_hi = utils.sum64_hi; +var sum64_lo = utils.sum64_lo; +var sum64_4_hi = utils.sum64_4_hi; +var sum64_4_lo = utils.sum64_4_lo; +var sum64_5_hi = utils.sum64_5_hi; +var sum64_5_lo = utils.sum64_5_lo; - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} +var BlockHash = common.BlockHash; - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); } +utils.inherits(SHA512, BlockHash); +module.exports = SHA512; -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; - value = Math.abs(value) +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } + W[i] = sum64_4_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); } +}; - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} +SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + var W = this.W; - buffer[offset + i - d] |= s * 128 -} + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; -},{}],95:[function(require,module,exports){ -(function (global){ -'use strict'; -var Mutation = global.MutationObserver || global.WebKitMutationObserver; + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; -var scheduleDrain; + var T1_hi = sum64_5_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); -{ - if (Mutation) { - var called = 0; - var observer = new Mutation(nextTick); - var element = global.document.createTextNode(''); - observer.observe(element, { - characterData: true - }); - scheduleDrain = function () { - element.data = (called = ++called % 2); - }; - } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') { - var channel = new global.MessageChannel(); - channel.port1.onmessage = nextTick; - scheduleDrain = function () { - channel.port2.postMessage(0); - }; - } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) { - scheduleDrain = function () { + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); - // Create a