github.com/emmansun/gmsm@v0.29.1/internal/sm2ec/p256_ord_test.go (about) 1 package sm2ec_test 2 3 import ( 4 "bytes" 5 "math/big" 6 "testing" 7 8 "github.com/emmansun/gmsm/internal/sm2ec" 9 elliptic "github.com/emmansun/gmsm/sm2/sm2ec" 10 ) 11 12 func TestP256OrdInverse(t *testing.T) { 13 N := elliptic.P256().Params().N 14 15 // inv(0) is expected to be 0. 16 zero := make([]byte, 32) 17 out, err := sm2ec.P256OrdInverse(zero) 18 if err != nil { 19 t.Fatal(err) 20 } 21 if !bytes.Equal(out, zero) { 22 t.Error("unexpected output for inv(0)") 23 } 24 25 // inv(N) is also 0 mod N. 26 input := make([]byte, 32) 27 N.FillBytes(input) 28 out, err = sm2ec.P256OrdInverse(input) 29 if err != nil { 30 t.Fatal(err) 31 } 32 if !bytes.Equal(out, zero) { 33 t.Error("unexpected output for inv(N)") 34 } 35 if !bytes.Equal(input, N.Bytes()) { 36 t.Error("input was modified") 37 } 38 39 // Check inv(1) and inv(N+1) against math/big 40 exp := new(big.Int).ModInverse(big.NewInt(1), N).FillBytes(make([]byte, 32)) 41 big.NewInt(1).FillBytes(input) 42 out, err = sm2ec.P256OrdInverse(input) 43 if err != nil { 44 t.Fatal(err) 45 } 46 if !bytes.Equal(out, exp) { 47 t.Error("unexpected output for inv(1)") 48 } 49 new(big.Int).Add(N, big.NewInt(1)).FillBytes(input) 50 out, err = sm2ec.P256OrdInverse(input) 51 if err != nil { 52 t.Fatal(err) 53 } 54 if !bytes.Equal(out, exp) { 55 t.Error("unexpected output for inv(N+1)") 56 } 57 58 // Check inv(20) and inv(N+20) against math/big 59 exp = new(big.Int).ModInverse(big.NewInt(20), N).FillBytes(make([]byte, 32)) 60 big.NewInt(20).FillBytes(input) 61 out, err = sm2ec.P256OrdInverse(input) 62 if err != nil { 63 t.Fatal(err) 64 } 65 if !bytes.Equal(out, exp) { 66 t.Error("unexpected output for inv(20)") 67 } 68 new(big.Int).Add(N, big.NewInt(20)).FillBytes(input) 69 out, err = sm2ec.P256OrdInverse(input) 70 if err != nil { 71 t.Fatal(err) 72 } 73 if !bytes.Equal(out, exp) { 74 t.Error("unexpected output for inv(N+20)") 75 } 76 77 // Check inv(2^256-1) against math/big 78 bigInput := new(big.Int).Lsh(big.NewInt(1), 256) 79 bigInput.Sub(bigInput, big.NewInt(1)) 80 exp = new(big.Int).ModInverse(bigInput, N).FillBytes(make([]byte, 32)) 81 bigInput.FillBytes(input) 82 out, err = sm2ec.P256OrdInverse(input) 83 if err != nil { 84 t.Fatal(err) 85 } 86 if !bytes.Equal(out, exp) { 87 t.Error("unexpected output for inv(2^256-1)") 88 } 89 }