// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mlkem import ( "bytes" "crypto/rand" "math/big" mathrand "math/rand/v2" "strconv" "testing" ) func TestFieldReduce(t *testing.T) { for a := uint32(0); a < 2*q*q; a++ { got := fieldReduce(a) exp := fieldElement(a % q) if got != exp { t.Fatalf("reduce(%d) = %d, expected %d", a, got, exp) } } } func TestFieldAdd(t *testing.T) { for a := fieldElement(0); a < q; a++ { for b := fieldElement(0); b < q; b++ { got := fieldAdd(a, b) exp := (a + b) % q if got != exp { t.Fatalf("%d + %d = %d, expected %d", a, b, got, exp) } } } } func TestFieldSub(t *testing.T) { for a := fieldElement(0); a < q; a++ { for b := fieldElement(0); b < q; b++ { got := fieldSub(a, b) exp := (a - b + q) % q if got != exp { t.Fatalf("%d - %d = %d, expected %d", a, b, got, exp) } } } } func TestFieldMul(t *testing.T) { for a := fieldElement(0); a < q; a++ { for b := fieldElement(0); b < q; b++ { got := fieldMul(a, b) exp := fieldElement((uint32(a) * uint32(b)) % q) if got != exp { t.Fatalf("%d * %d = %d, expected %d", a, b, got, exp) } } } } func TestDecompressCompress(t *testing.T) { for _, bits := range []uint8{1, 4, 10} { for a := uint16(0); a < 1<= q { t.Fatalf("decompress(%d, %d) = %d >= q", a, bits, f) } got := compress(f, bits) if got != a { t.Fatalf("compress(decompress(%d, %d), %d) = %d", a, bits, bits, got) } } for a := fieldElement(0); a < q; a++ { c := compress(a, bits) if c >= 1<= 2^bits", a, bits, c) } got := decompress(c, bits) diff := min(a-got, got-a, a-got+q, got-a+q) ceil := q / (1 << bits) if diff > fieldElement(ceil) { t.Fatalf("decompress(compress(%d, %d), %d) = %d (diff %d, max diff %d)", a, bits, bits, got, diff, ceil) } } } } func CompressRat(x fieldElement, d uint8) uint16 { if x >= q { panic("x out of range") } if d <= 0 || d >= 12 { panic("d out of range") } precise := big.NewRat((1<= 1<= 12 { panic("d out of range") } precise := big.NewRat(q*int64(y), 1<>7 != 0 { panic("not 7 bits") } var r uint8 r |= n >> 6 & 0b0000_0001 r |= n >> 4 & 0b0000_0010 r |= n >> 2 & 0b0000_0100 r |= n /**/ & 0b0000_1000 r |= n << 2 & 0b0001_0000 r |= n << 4 & 0b0010_0000 r |= n << 6 & 0b0100_0000 return r } func TestZetas(t *testing.T) { ζ := big.NewInt(17) q := big.NewInt(q) for k, zeta := range zetas { // ζ^BitRev7(k) mod q exp := new(big.Int).Exp(ζ, big.NewInt(int64(BitRev7(uint8(k)))), q) if big.NewInt(int64(zeta)).Cmp(exp) != 0 { t.Errorf("zetas[%d] = %v, expected %v", k, zeta, exp) } } } func TestGammas(t *testing.T) { ζ := big.NewInt(17) q := big.NewInt(q) for k, gamma := range gammas { // ζ^2BitRev7(i)+1 exp := new(big.Int).Exp(ζ, big.NewInt(int64(BitRev7(uint8(k)))*2+1), q) if big.NewInt(int64(gamma)).Cmp(exp) != 0 { t.Errorf("gammas[%d] = %v, expected %v", k, gamma, exp) } } }