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

     1  //go:build purego || !(amd64 || arm64 || s390x || ppc64le)
     2  
     3  package sm2ec
     4  
     5  import (
     6  	"errors"
     7  
     8  	"github.com/emmansun/gmsm/internal/sm2ec/fiat"
     9  )
    10  
    11  // P256OrdInverse, sets out to in⁻¹ mod org(G). If in is zero, out will be zero.
    12  // n-2 =
    13  // 1111111111111111111111111111111011111111111111111111111111111111
    14  // 1111111111111111111111111111111111111111111111111111111111111111
    15  // 0111001000000011110111110110101100100001110001100000010100101011
    16  // 0101001110111011111101000000100100111001110101010100000100100001
    17  //
    18  func P256OrdInverse(k []byte) ([]byte, error) {
    19  	if len(k) != 32 {
    20  		return nil, errors.New("invalid scalar length")
    21  	}
    22  	x := new(fiat.SM2P256OrderElement)
    23  	_, err := x.SetBytes(k)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	xinv := new(fiat.SM2P256OrderElement).Invert(x)
    28  	return xinv.Bytes(), nil
    29  }
    30  
    31  // P256OrdMul multiplication modulo org(G).
    32  func P256OrdMul(in1, in2 []byte) ([]byte, error) {
    33  	if len(in1) != 32 || len(in2) != 32 {
    34  		return nil, errors.New("invalid scalar length")
    35  	}
    36  	ax := new(fiat.SM2P256OrderElement)
    37  	ay := new(fiat.SM2P256OrderElement)
    38  	res := new(fiat.SM2P256OrderElement)
    39  
    40  	_, err := ax.SetBytes(in1)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	_, err = ay.SetBytes(in2)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	res = res.Mul(ax, ay)
    51  	return res.Bytes(), nil
    52  }