index.js 1.7 KB

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