github.com/emmansun/gmsm@v0.29.1/internal/sm2ec/sm2p256_mqv_test.go (about)

     1  package sm2ec_test
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/rand"
     6  	"encoding/hex"
     7  	"io"
     8  	"math/big"
     9  	"testing"
    10  
    11  	"github.com/emmansun/gmsm/internal/sm2ec"
    12  )
    13  
    14  func randomK(r io.Reader, ord *big.Int) (k *big.Int, err error) {
    15  	for {
    16  		k, err = rand.Int(r, ord)
    17  		if err != nil || (k.Sign() > 0 && len(k.Bytes()) == 32) {
    18  			return
    19  		}
    20  	}
    21  }
    22  
    23  func TestImplicitSig(t *testing.T) {
    24  	n, _ := new(big.Int).SetString("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16)
    25  	sPriv, err := randomK(rand.Reader, n)
    26  	if err != nil {
    27  		t.Fatal(err)
    28  	}
    29  	ePriv, err := randomK(rand.Reader, n)
    30  	if err != nil {
    31  		t.Fatal(err)
    32  	}
    33  	k, err := randomK(rand.Reader, n)
    34  	if err != nil {
    35  		t.Fatal(err)
    36  	}
    37  	res1, err := sm2ec.ImplicitSig(sPriv.Bytes(), ePriv.Bytes(), k.Bytes())
    38  	if err != nil {
    39  		t.Fatal(err)
    40  	}
    41  	res2 := new(big.Int)
    42  	res2.Mul(ePriv, k)
    43  	res2.Add(res2, sPriv)
    44  	res2.Mod(res2, n)
    45  	if !bytes.Equal(new(big.Int).SetBytes(res1).Bytes(), res2.Bytes()) {
    46  		t.Errorf("expected %s, got %s", hex.EncodeToString(res1), hex.EncodeToString(res2.Bytes()))
    47  	}
    48  }