[6a3a178] | 1 | var crypto = require("crypto");
|
---|
| 2 | var BigInteger = require("jsbn").BigInteger;
|
---|
| 3 | var ECPointFp = require("./lib/ec.js").ECPointFp;
|
---|
| 4 | var Buffer = require("safer-buffer").Buffer;
|
---|
| 5 | exports.ECCurves = require("./lib/sec.js");
|
---|
| 6 |
|
---|
| 7 | // zero prepad
|
---|
| 8 | function unstupid(hex,len)
|
---|
| 9 | {
|
---|
| 10 | return (hex.length >= len) ? hex : unstupid("0"+hex,len);
|
---|
| 11 | }
|
---|
| 12 |
|
---|
| 13 | exports.ECKey = function(curve, key, isPublic)
|
---|
| 14 | {
|
---|
| 15 | var priv;
|
---|
| 16 | var c = curve();
|
---|
| 17 | var n = c.getN();
|
---|
| 18 | var bytes = Math.floor(n.bitLength()/8);
|
---|
| 19 |
|
---|
| 20 | if(key)
|
---|
| 21 | {
|
---|
| 22 | if(isPublic)
|
---|
| 23 | {
|
---|
| 24 | var curve = c.getCurve();
|
---|
| 25 | // var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format
|
---|
| 26 | // var y = key.slice(bytes+1);
|
---|
| 27 | // this.P = new ECPointFp(curve,
|
---|
| 28 | // curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)),
|
---|
| 29 | // curve.fromBigInteger(new BigInteger(y.toString("hex"), 16)));
|
---|
| 30 | this.P = curve.decodePointHex(key.toString("hex"));
|
---|
| 31 | }else{
|
---|
| 32 | if(key.length != bytes) return false;
|
---|
| 33 | priv = new BigInteger(key.toString("hex"), 16);
|
---|
| 34 | }
|
---|
| 35 | }else{
|
---|
| 36 | var n1 = n.subtract(BigInteger.ONE);
|
---|
| 37 | var r = new BigInteger(crypto.randomBytes(n.bitLength()));
|
---|
| 38 | priv = r.mod(n1).add(BigInteger.ONE);
|
---|
| 39 | this.P = c.getG().multiply(priv);
|
---|
| 40 | }
|
---|
| 41 | if(this.P)
|
---|
| 42 | {
|
---|
| 43 | // var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2);
|
---|
| 44 | // this.PublicKey = Buffer.from("04"+pubhex,"hex");
|
---|
| 45 | this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex");
|
---|
| 46 | }
|
---|
| 47 | if(priv)
|
---|
| 48 | {
|
---|
| 49 | this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex");
|
---|
| 50 | this.deriveSharedSecret = function(key)
|
---|
| 51 | {
|
---|
| 52 | if(!key || !key.P) return false;
|
---|
| 53 | var S = key.P.multiply(priv);
|
---|
| 54 | return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex");
|
---|
| 55 | }
|
---|
| 56 | }
|
---|
| 57 | }
|
---|
| 58 |
|
---|