Skip to content

Commit 1565260

Browse files
committed
ecdsa: Apply nonce bit-length mitigation to stop timing leakage.
Ported from elliptic-js: indutny/elliptic#203
1 parent 03a8dbc commit 1565260

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

lib/EC.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,17 @@ public function sign($msg, $key, $enc = null, $options = null)
136136
if( $k->cmpn(1) <= 0 || $k->cmp($ns1) >= 0 )
137137
continue;
138138

139-
$kp = $this->g->mul($k);
139+
// Fix the bit-length of the random nonce,
140+
// so that it doesn't leak via timing.
141+
// This does not change that ks = k mod k
142+
$ks = $k->add($this->n);
143+
$kt = $ks->add($this->n);
144+
if ($ks->bitLength() === $this->n->bitLength()) {
145+
$kp = $this->g->mul($kt);
146+
} else {
147+
$kp = $this->g->mul($ks);
148+
}
149+
140150
if( $kp->isInfinity() )
141151
continue;
142152

0 commit comments

Comments
 (0)