Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

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