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