react / wstein / node_modules / browserify / node_modules / crypto-browserify / node_modules / create-ecdh / browser.js
80542 viewsvar elliptic = require('elliptic');1var BN = require('bn.js');23module.exports = function createECDH(curve) {4return new ECDH(curve);5};67var aliases = {8secp256k1: {9name: 'secp256k1',10byteLength: 3211},12secp224r1: {13name: 'p224',14byteLength: 2815},16prime256v1: {17name: 'p256',18byteLength: 3219},20prime192v1: {21name: 'p192',22byteLength: 2423},24ed25519: {25name: 'ed25519',26byteLength: 3227}28};2930aliases.p224 = aliases.secp224r1;31aliases.p256 = aliases.secp256r1 = aliases.prime256v1;32aliases.p192 = aliases.secp192r1 = aliases.prime192v1;3334function ECDH(curve) {35this.curveType = aliases[curve];36if (!this.curveType ) {37this.curveType = {38name: curve39};40}41this.curve = new elliptic.ec(this.curveType.name);42this.keys = void 0;43}4445ECDH.prototype.generateKeys = function (enc, format) {46this.keys = this.curve.genKeyPair();47return this.getPublicKey(enc, format);48};4950ECDH.prototype.computeSecret = function (other, inenc, enc) {51inenc = inenc || 'utf8';52if (!Buffer.isBuffer(other)) {53other = new Buffer(other, inenc);54}55var otherPub = this.curve.keyFromPublic(other).getPublic();56var out = otherPub.mul(this.keys.getPrivate()).getX();57return formatReturnValue(out, enc, this.curveType.byteLength);58};5960ECDH.prototype.getPublicKey = function (enc, format) {61var key = this.keys.getPublic(format === 'compressed', true);62if (format === 'hybrid') {63if (key[key.length - 1] % 2) {64key[0] = 7;65} else {66key [0] = 6;67}68}69return formatReturnValue(key, enc);70};7172ECDH.prototype.getPrivateKey = function (enc) {73return formatReturnValue(this.keys.getPrivate(), enc);74};7576ECDH.prototype.setPublicKey = function (pub, enc) {77enc = enc || 'utf8';78if (!Buffer.isBuffer(pub)) {79pub = new Buffer(pub, enc);80}81this.keys._importPublic(pub);82return this;83};8485ECDH.prototype.setPrivateKey = function (priv, enc) {86enc = enc || 'utf8';87if (!Buffer.isBuffer(priv)) {88priv = new Buffer(priv, enc);89}90var _priv = new BN(priv);91_priv = _priv.toString(16);92this.keys._importPrivate(_priv);93return this;94};9596function formatReturnValue(bn, enc, len) {97if (!Array.isArray(bn)) {98bn = bn.toArray();99}100var buf = new Buffer(bn);101if (len && buf.length < len) {102var zeros = new Buffer(len - buf.length);103zeros.fill(0);104buf = Buffer.concat([zeros, buf]);105}106if (!enc) {107return buf;108} else {109return buf.toString(enc);110}111}112113114