Skip to content

Commit

Permalink
determanistic k
Browse files Browse the repository at this point in the history
  • Loading branch information
calvinmetcalf authored and Calvin Metcalf committed Jan 12, 2015
1 parent ef5d2b8 commit 2e1bf48
Showing 1 changed file with 60 additions and 6 deletions.
66 changes: 60 additions & 6 deletions sign.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ function dsaSign(hash, priv, crypto) {
var k;
var H = new bn(hash);
var s = false;
var kv = getKay(x, hash, crypto);
while (s === false) {
while (!r.cmpn(0)) {
k = getKay(q, crypto);
k = makeKey(q, kv, crypto);
r = makeR(g, k, p, q);
}
s = k.invm(q).imul(H.add(x.imul(r).mod(q)).mod(q)).mod(q);
Expand All @@ -75,12 +76,65 @@ function toDER(r, s) {
res = res.concat(r, [ 0x02, s.length ], s);
return new Buffer(res);
}
function getKay(q, crypto) {
var k = new bn(crypto.randomBytes(q.byteLength()));
while (k.cmp(q) >= 0) {
k = new bn(crypto.randomBytes(q.byteLength()));
function getKay(x, hash, crypto) {
x = new Buffer(x.toArray());
var algo = 'sha1';//I know!
var hlen = hash.length;
var v = new Buffer(hlen);
v.fill(1);
var k = new Buffer(hlen);
k.fill(0);
k = crypto.createHmac('sha1', k)
.update(v)
.update(new Buffer([0]))
.update(x)
.update(hash)
.digest();
v = crypto.createHmac(algo, k)
.update(v)
.digest();
k = crypto.createHmac(algo, k)
.update(v)
.update(new Buffer([1]))
.update(x)
.update(hash)
.digest();
return {
k:k,
v:v
};
}
function bits2int(bits, q) {
bits = new bn(bits);
var shift = bits.bitLength() - q.bitLength();
if (shift > 0) {
bits.ishrn(shift);
}
return bits;
}
function makeKey(q, kv, crypto) {
var t;
var k;
while (true) {
t = new Buffer('');
while (t.length * 8 < q.bitLength()) {
kv.v = crypto.createHmac('sha1', kv.k)
.update(kv.v)
.digest();
t = Buffer.concat([t, kv.v]);
}
k = bits2int(t, q);
kv.k = crypto.createHmac('sha1', kv.k)
.update(kv.v)
.update(new Buffer([0]))
.digest();
kv.v = crypto.createHmac('sha1', kv.k)
.update(kv.v)
.digest();
if (k.cmp(q) === -1) {
return k;
}
}
return k;
}
function makeR(g, k, p, q) {
return g.toRed(bn.mont(p)).redPow(k).fromRed().mod(q);
Expand Down

0 comments on commit 2e1bf48

Please sign in to comment.