|
var crypto = require("crypto"); |
|
var BigInteger = require("jsbn").BigInteger; |
|
var ECPointFp = require("./lib/ec.js").ECPointFp; |
|
var Buffer = require("safer-buffer").Buffer; |
|
exports.ECCurves = require("./lib/sec.js"); |
|
|
|
|
|
function unstupid(hex,len) |
|
{ |
|
return (hex.length >= len) ? hex : unstupid("0"+hex,len); |
|
} |
|
|
|
exports.ECKey = function(curve, key, isPublic) |
|
{ |
|
var priv; |
|
var c = curve(); |
|
var n = c.getN(); |
|
var bytes = Math.floor(n.bitLength()/8); |
|
|
|
if(key) |
|
{ |
|
if(isPublic) |
|
{ |
|
var curve = c.getCurve(); |
|
|
|
|
|
|
|
|
|
|
|
this.P = curve.decodePointHex(key.toString("hex")); |
|
}else{ |
|
if(key.length != bytes) return false; |
|
priv = new BigInteger(key.toString("hex"), 16); |
|
} |
|
}else{ |
|
var n1 = n.subtract(BigInteger.ONE); |
|
var r = new BigInteger(crypto.randomBytes(n.bitLength())); |
|
priv = r.mod(n1).add(BigInteger.ONE); |
|
this.P = c.getG().multiply(priv); |
|
} |
|
if(this.P) |
|
{ |
|
|
|
|
|
this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); |
|
} |
|
if(priv) |
|
{ |
|
this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); |
|
this.deriveSharedSecret = function(key) |
|
{ |
|
if(!key || !key.P) return false; |
|
var S = key.P.multiply(priv); |
|
return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); |
|
} |
|
} |
|
} |
|
|
|
|