Skip to content

Commit ac61588

Browse files
bfordagl
authored andcommitted
math/big: add modular square-root and Jacobi functions
This change adds Int.ModSqrt to compute modular square-roots via the standard Tonelli-Shanks algorithm, and the Jacobi function that this and many other modular-arithmetic algorithms depend on. This is needed by change 1883 (https://golang.org/cl/1883), to add support for ANSI-standard compressed encoding of elliptic curve points. Change-Id: Icc4805001bba0b3cb7200e0b0a7f87b14a9e9439 Reviewed-on: https://go-review.googlesource.com/1886 Reviewed-by: Adam Langley <[email protected]>
1 parent 1ddb8c2 commit ac61588

File tree

2 files changed

+255
-0
lines changed

2 files changed

+255
-0
lines changed

src/math/big/int.go

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,124 @@ func (z *Int) ModInverse(g, n *Int) *Int {
583583
return z
584584
}
585585

586+
// Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
587+
// The y argument must be an odd integer.
588+
func Jacobi(x, y *Int) int {
589+
if len(y.abs) == 0 || y.abs[0]&1 == 0 {
590+
panic(fmt.Sprintf("big: invalid 2nd argument to Int.Jacobi: need odd integer but got %s", y))
591+
}
592+
593+
// We use the formulation described in chapter 2, section 2.4,
594+
// "The Yacas Book of Algorithms":
595+
// http://yacas.sourceforge.net/Algo.book.pdf
596+
597+
var a, b, c Int
598+
a.Set(x)
599+
b.Set(y)
600+
j := 1
601+
602+
if b.neg {
603+
if a.neg {
604+
j = -1
605+
}
606+
b.neg = false
607+
}
608+
609+
for {
610+
if b.Cmp(intOne) == 0 {
611+
return j
612+
}
613+
if len(a.abs) == 0 {
614+
return 0
615+
}
616+
a.Mod(&a, &b)
617+
if len(a.abs) == 0 {
618+
return 0
619+
}
620+
// a > 0
621+
622+
// handle factors of 2 in 'a'
623+
s := a.abs.trailingZeroBits()
624+
if s&1 != 0 {
625+
bmod8 := b.abs[0] & 7
626+
if bmod8 == 3 || bmod8 == 5 {
627+
j = -j
628+
}
629+
}
630+
c.Rsh(&a, s) // a = 2^s*c
631+
632+
// swap numerator and denominator
633+
if b.abs[0]&3 == 3 && c.abs[0]&3 == 3 {
634+
j = -j
635+
}
636+
a.Set(&b)
637+
b.Set(&c)
638+
}
639+
}
640+
641+
// ModSqrt sets z to a square root of x mod p if such a square root exists, and
642+
// returns z. The modulus p must be an odd prime. If x is not a square mod p,
643+
// ModSqrt leaves z unchanged and returns nil. This function panics if p is
644+
// not an odd integer.
645+
func (z *Int) ModSqrt(x, p *Int) *Int {
646+
switch Jacobi(x, p) {
647+
case -1:
648+
return nil // x is not a square mod p
649+
case 0:
650+
return z.SetInt64(0) // sqrt(0) mod p = 0
651+
case 1:
652+
break
653+
}
654+
if x.neg || x.Cmp(p) >= 0 { // ensure 0 <= x < p
655+
x = new(Int).Mod(x, p)
656+
}
657+
658+
// Break p-1 into s*2^e such that s is odd.
659+
var s Int
660+
s.Sub(p, intOne)
661+
e := s.abs.trailingZeroBits()
662+
s.Rsh(&s, e)
663+
664+
// find some non-square n
665+
var n Int
666+
n.SetInt64(2)
667+
for Jacobi(&n, p) != -1 {
668+
n.Add(&n, intOne)
669+
}
670+
671+
// Core of the Tonelli-Shanks algorithm. Follows the description in
672+
// section 6 of "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra
673+
// Brown:
674+
// https://www.maa.org/sites/default/files/pdf/upload_library/22/Polya/07468342.di020786.02p0470a.pdf
675+
var y, b, g, t Int
676+
y.Add(&s, intOne)
677+
y.Rsh(&y, 1)
678+
y.Exp(x, &y, p) // y = x^((s+1)/2)
679+
b.Exp(x, &s, p) // b = x^s
680+
g.Exp(&n, &s, p) // g = n^s
681+
r := e
682+
for {
683+
// find the least m such that ord_p(b) = 2^m
684+
var m uint
685+
t.Set(&b)
686+
for t.Cmp(intOne) != 0 {
687+
t.Mul(&t, &t).Mod(&t, p)
688+
m++
689+
}
690+
691+
if m == 0 {
692+
return z.Set(&y)
693+
}
694+
695+
t.SetInt64(0).SetBit(&t, int(r-m-1), 1).Exp(&g, &t, p)
696+
// t = g^(2^(r-m-1)) mod p
697+
g.Mul(&t, &t).Mod(&g, p) // g = g^(2^(r-m)) mod p
698+
y.Mul(&y, &t).Mod(&y, p)
699+
b.Mul(&b, &g).Mod(&b, p)
700+
r = m
701+
}
702+
}
703+
586704
// Lsh sets z = x << n and returns z.
587705
func (z *Int) Lsh(x *Int, n uint) *Int {
588706
z.abs = z.abs.shl(x.abs, n)

src/math/big/int_test.go

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,13 @@ var primes = []string{
704704
"230975859993204150666423538988557839555560243929065415434980904258310530753006723857139742334640122533598517597674807096648905501653461687601339782814316124971547968912893214002992086353183070342498989426570593",
705705
"5521712099665906221540423207019333379125265462121169655563495403888449493493629943498064604536961775110765377745550377067893607246020694972959780839151452457728855382113555867743022746090187341871655890805971735385789993",
706706
"203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123",
707+
708+
// ECC primes: http://tools.ietf.org/html/draft-ladd-safecurves-02
709+
"3618502788666131106986593281521497120414687020801267626233049500247285301239", // Curve1174: 2^251-9
710+
"57896044618658097711785492504343953926634992332820282019728792003956564819949", // Curve25519: 2^255-19
711+
"9850501549098619803069760025035903451269934817616361666987073351061430442874302652853566563721228910201656997576599", // E-382: 2^382-105
712+
"42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494931472367", // Curve41417: 2^414-17
713+
"6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", // E-521: 2^521-1
707714
}
708715

709716
var composites = []string{
@@ -1249,6 +1256,136 @@ func TestModInverse(t *testing.T) {
12491256
}
12501257
}
12511258

1259+
// testModSqrt is a helper for TestModSqrt,
1260+
// which checks that ModSqrt can compute a square-root of elt^2.
1261+
func testModSqrt(t *testing.T, elt, mod, sq, sqrt *Int) bool {
1262+
var sqChk, sqrtChk, sqrtsq Int
1263+
sq.Mul(elt, elt)
1264+
sq.Mod(sq, mod)
1265+
z := sqrt.ModSqrt(sq, mod)
1266+
if z != sqrt {
1267+
t.Errorf("ModSqrt returned wrong value %s", z)
1268+
}
1269+
1270+
// test ModSqrt arguments outside the range [0,mod)
1271+
sqChk.Add(sq, mod)
1272+
z = sqrtChk.ModSqrt(&sqChk, mod)
1273+
if z != &sqrtChk || z.Cmp(sqrt) != 0 {
1274+
t.Errorf("ModSqrt returned inconsistent value %s", z)
1275+
}
1276+
sqChk.Sub(sq, mod)
1277+
z = sqrtChk.ModSqrt(&sqChk, mod)
1278+
if z != &sqrtChk || z.Cmp(sqrt) != 0 {
1279+
t.Errorf("ModSqrt returned inconsistent value %s", z)
1280+
}
1281+
1282+
// make sure we actually got a square root
1283+
if sqrt.Cmp(elt) == 0 {
1284+
return true // we found the "desired" square root
1285+
}
1286+
sqrtsq.Mul(sqrt, sqrt) // make sure we found the "other" one
1287+
sqrtsq.Mod(&sqrtsq, mod)
1288+
return sq.Cmp(&sqrtsq) == 0
1289+
}
1290+
1291+
func TestModSqrt(t *testing.T) {
1292+
var elt, mod, modx4, sq, sqrt Int
1293+
r := rand.New(rand.NewSource(9))
1294+
for i, s := range primes[1:] { // skip 2, use only odd primes
1295+
mod.SetString(s, 10)
1296+
modx4.Lsh(&mod, 2)
1297+
1298+
// test a few random elements per prime
1299+
for x := 1; x < 5; x++ {
1300+
elt.Rand(r, &modx4)
1301+
elt.Sub(&elt, &mod) // test range [-mod, 3*mod)
1302+
if !testModSqrt(t, &elt, &mod, &sq, &sqrt) {
1303+
t.Errorf("#%d: failed (sqrt(e) = %s)", i, &sqrt)
1304+
}
1305+
}
1306+
}
1307+
1308+
// exhaustive test for small values
1309+
for n := 3; n < 100; n++ {
1310+
mod.SetInt64(int64(n))
1311+
if !mod.ProbablyPrime(10) {
1312+
continue
1313+
}
1314+
isSquare := make([]bool, n)
1315+
1316+
// test all the squares
1317+
for x := 1; x < n; x++ {
1318+
elt.SetInt64(int64(x))
1319+
if !testModSqrt(t, &elt, &mod, &sq, &sqrt) {
1320+
t.Errorf("#%d: failed (sqrt(%d,%d) = %s)", x, &elt, &mod, &sqrt)
1321+
}
1322+
isSquare[sq.Uint64()] = true
1323+
}
1324+
1325+
// test all non-squares
1326+
for x := 1; x < n; x++ {
1327+
sq.SetInt64(int64(x))
1328+
z := sqrt.ModSqrt(&sq, &mod)
1329+
if !isSquare[x] && z != nil {
1330+
t.Errorf("#%d: failed (sqrt(%d,%d) = nil)", x, &sqrt, &mod)
1331+
}
1332+
}
1333+
}
1334+
}
1335+
1336+
func TestJacobi(t *testing.T) {
1337+
testCases := []struct {
1338+
x, y int64
1339+
result int
1340+
}{
1341+
{0, 1, 1},
1342+
{0, -1, 1},
1343+
{1, 1, 1},
1344+
{1, -1, 1},
1345+
{0, 5, 0},
1346+
{1, 5, 1},
1347+
{2, 5, -1},
1348+
{-2, 5, -1},
1349+
{2, -5, -1},
1350+
{-2, -5, 1},
1351+
{3, 5, -1},
1352+
{5, 5, 0},
1353+
{-5, 5, 0},
1354+
{6, 5, 1},
1355+
{6, -5, 1},
1356+
{-6, 5, 1},
1357+
{-6, -5, -1},
1358+
}
1359+
1360+
var x, y Int
1361+
1362+
for i, test := range testCases {
1363+
x.SetInt64(test.x)
1364+
y.SetInt64(test.y)
1365+
expected := test.result
1366+
actual := Jacobi(&x, &y)
1367+
if actual != expected {
1368+
t.Errorf("#%d: Jacobi(%d, %d) = %d, but expected %d", i, test.x, test.y, actual, expected)
1369+
}
1370+
}
1371+
}
1372+
1373+
func TestJacobiPanic(t *testing.T) {
1374+
const failureMsg = "test failure"
1375+
defer func() {
1376+
msg := recover()
1377+
if msg == nil || msg == failureMsg {
1378+
panic(msg)
1379+
}
1380+
t.Log(msg)
1381+
}()
1382+
x := NewInt(1)
1383+
y := NewInt(2)
1384+
// Jacobi should panic when the second argument is even.
1385+
Jacobi(x, y)
1386+
panic(failureMsg)
1387+
}
1388+
12521389
var encodingTests = []string{
12531390
"-539345864568634858364538753846587364875430589374589",
12541391
"-678645873",

0 commit comments

Comments
 (0)