github.com/emmansun/gmsm@v0.29.1/sm2/sm2ec/elliptic.go (about)

     1  package sm2ec
     2  
     3  import (
     4  	"crypto/elliptic"
     5  	"math/big"
     6  	"sync"
     7  )
     8  
     9  var initonce sync.Once
    10  
    11  var sm2Params = &elliptic.CurveParams{
    12  	Name:    "sm2p256v1",
    13  	BitSize: 256,
    14  	P:       bigFromHex("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF"),
    15  	N:       bigFromHex("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123"),
    16  	B:       bigFromHex("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93"),
    17  	Gx:      bigFromHex("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7"),
    18  	Gy:      bigFromHex("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"),
    19  }
    20  
    21  func bigFromHex(s string) *big.Int {
    22  	b, ok := new(big.Int).SetString(s, 16)
    23  	if !ok {
    24  		panic("sm2/elliptic: internal error: invalid encoding")
    25  	}
    26  	return b
    27  }
    28  
    29  func initAll() {
    30  	initSM2P256()
    31  }
    32  
    33  func P256() elliptic.Curve {
    34  	initonce.Do(initAll)
    35  	return sm2p256
    36  }
    37  
    38  // Since golang 1.19
    39  // unmarshaler is implemented by curves with their own constant-time Unmarshal.
    40  // There isn't an equivalent interface for Marshal/MarshalCompressed because
    41  // that doesn't involve any mathematical operations, only FillBytes and Bit.
    42  type unmarshaler interface {
    43  	Unmarshal([]byte) (x, y *big.Int)
    44  	UnmarshalCompressed([]byte) (x, y *big.Int)
    45  }
    46  
    47  func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) {
    48  	if c, ok := curve.(unmarshaler); ok {
    49  		return c.Unmarshal(data)
    50  	}
    51  	return elliptic.Unmarshal(curve, data)
    52  }
    53  
    54  // UnmarshalCompressed converts a point, serialized by MarshalCompressed, into
    55  // an x, y pair. It is an error if the point is not in compressed form, is not
    56  // on the curve, or is the point at infinity. On error, x = nil.
    57  func UnmarshalCompressed(curve elliptic.Curve, data []byte) (x, y *big.Int) {
    58  	if c, ok := curve.(unmarshaler); ok {
    59  		return c.UnmarshalCompressed(data)
    60  	}
    61  	return elliptic.UnmarshalCompressed(curve, data)
    62  }