Created
November 19, 2014 04:59
-
-
Save codyromano/4407868f5fb12c582be1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (exports) { | |
/** | |
* Dependencies | |
* - jsbn.js | |
* - jsbn2.js | |
* - prng4.js | |
* - ec.js | |
* - sec.js | |
* - rng.js | |
*/ | |
'use strict'; | |
function EllipticCurve () { | |
// Get a curve using Stanford ec / sec library | |
var c = getSECCurveByName('secp160k1'); | |
// The user's private point (key) | |
this.privatePoint = null; | |
// Use the Web Cryptography API to generate a random number | |
this.rng = new SecureRandom(); | |
// Define the various points of the EC | |
this.q = c.getCurve().getQ().toString(); | |
this.a = c.getCurve().getA().toBigInteger().toString(); | |
this.b = c.getCurve().getB().toBigInteger().toString(); | |
this.gx = c.getG().getX().toBigInteger().toString(); | |
this.gy = c.getG().getY().toBigInteger().toString(); | |
this.n = c.getN().toString(); | |
} | |
EllipticCurve.prototype.getCurve = function () { | |
return new ECCurveFp( | |
new BigInteger(this.q), | |
new BigInteger(this.a), | |
new BigInteger(this.b) | |
); | |
}; | |
/** | |
* @return {BigInteger} | |
*/ | |
EllipticCurve.prototype.pickRandom = function () { | |
var n = new BigInteger(this.n), | |
n1 = n.subtract(BigInteger.ONE), | |
r = new BigInteger(n.bitLength(), this.rng); | |
return r.mod(n1).add(BigInteger.ONE); | |
}; | |
EllipticCurve.prototype.getPrivatePoint = function () { | |
return (this.privatePoint = this.pickRandom().toString()); | |
}; | |
/** | |
* @param {Object} curve | |
* @return {Object} | |
*/ | |
EllipticCurve.prototype.getG = function (curve) { | |
return new ECPointFp( | |
curve, | |
curve.fromBigInteger(new BigInteger(this.gx)), | |
curve.fromBigInteger(new BigInteger(this.gy)) | |
); | |
}; | |
/** | |
* @return {Object} | |
*/ | |
EllipticCurve.prototype.getPublicPoint = function () { | |
var curve, G, a, P, after; | |
if (!this.privatePoint) { | |
throw new Error('No can do, Chief...You need to make a private key first.'); | |
} | |
curve = this.getCurve(); | |
G = this.getG(curve); | |
a = new BigInteger(this.privatePoint); | |
P = G.multiply(a); | |
return { | |
x: P.getX().toBigInteger().toString(), | |
y: P.getY().toBigInteger().toString() | |
}; | |
}; | |
// Exports | |
exports.EllipticCurve = EllipticCurve; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment