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

     1  // Package sm2 implements ShangMi(SM) sm2 digital signature, public key encryption and key exchange algorithms.
     2  package sm2
     3  
     4  // Further references:
     5  //   [NSA]: Suite B implementer's guide to FIPS 186-3
     6  //     http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.182.4503&rep=rep1&type=pdf
     7  //   [SECG]: SECG, SEC1
     8  //     http://www.secg.org/sec1-v2.pdf
     9  //   [GM/T]: SM2 GB/T 32918.2-2016, GB/T 32918.4-2016
    10  //
    11  
    12  import (
    13  	"crypto"
    14  	"crypto/ecdsa"
    15  	"crypto/elliptic"
    16  	_subtle "crypto/subtle"
    17  	"errors"
    18  	"fmt"
    19  	"io"
    20  	"math/big"
    21  	"sync"
    22  
    23  	"github.com/emmansun/gmsm/ecdh"
    24  	"github.com/emmansun/gmsm/internal/bigmod"
    25  	"github.com/emmansun/gmsm/internal/randutil"
    26  	_sm2ec "github.com/emmansun/gmsm/internal/sm2ec"
    27  	"github.com/emmansun/gmsm/internal/subtle"
    28  	"github.com/emmansun/gmsm/sm2/sm2ec"
    29  	"github.com/emmansun/gmsm/sm3"
    30  	"golang.org/x/crypto/cryptobyte"
    31  	"golang.org/x/crypto/cryptobyte/asn1"
    32  )
    33  
    34  const (
    35  	uncompressed byte = 0x04
    36  	compressed02 byte = 0x02
    37  	compressed03 byte = compressed02 | 0x01
    38  	hybrid06     byte = 0x06
    39  	hybrid07     byte = hybrid06 | 0x01
    40  )
    41  
    42  // PrivateKey represents an ECDSA SM2 private key.
    43  // It implemented both crypto.Decrypter and crypto.Signer interfaces.
    44  type PrivateKey struct {
    45  	ecdsa.PrivateKey
    46  	// inverseOfKeyPlus1 is set under inverseOfKeyPlus1Once
    47  	inverseOfKeyPlus1     *bigmod.Nat
    48  	inverseOfKeyPlus1Once sync.Once
    49  }
    50  
    51  type pointMarshalMode byte
    52  
    53  const (
    54  	//MarshalUncompressed uncompressed mashal mode
    55  	MarshalUncompressed pointMarshalMode = iota
    56  	//MarshalCompressed compressed mashal mode
    57  	MarshalCompressed
    58  	//MarshalHybrid hybrid mashal mode
    59  	MarshalHybrid
    60  )
    61  
    62  type ciphertextSplicingOrder byte
    63  
    64  const (
    65  	C1C3C2 ciphertextSplicingOrder = iota
    66  	C1C2C3
    67  )
    68  
    69  type ciphertextEncoding byte
    70  
    71  const (
    72  	ENCODING_PLAIN ciphertextEncoding = iota
    73  	ENCODING_ASN1
    74  )
    75  
    76  // EncrypterOpts encryption options
    77  type EncrypterOpts struct {
    78  	ciphertextEncoding      ciphertextEncoding
    79  	pointMarshalMode        pointMarshalMode
    80  	ciphertextSplicingOrder ciphertextSplicingOrder
    81  }
    82  
    83  // DecrypterOpts decryption options
    84  type DecrypterOpts struct {
    85  	ciphertextEncoding      ciphertextEncoding
    86  	cipherTextSplicingOrder ciphertextSplicingOrder
    87  }
    88  
    89  // NewPlainEncrypterOpts creates a SM2 non-ASN1 encrypter options.
    90  func NewPlainEncrypterOpts(marhsalMode pointMarshalMode, splicingOrder ciphertextSplicingOrder) *EncrypterOpts {
    91  	return &EncrypterOpts{ENCODING_PLAIN, marhsalMode, splicingOrder}
    92  }
    93  
    94  // NewPlainDecrypterOpts creates a SM2 non-ASN1 decrypter options.
    95  func NewPlainDecrypterOpts(splicingOrder ciphertextSplicingOrder) *DecrypterOpts {
    96  	return &DecrypterOpts{ENCODING_PLAIN, splicingOrder}
    97  }
    98  
    99  func toBytes(curve elliptic.Curve, value *big.Int) []byte {
   100  	byteLen := (curve.Params().BitSize + 7) >> 3
   101  	result := make([]byte, byteLen)
   102  	value.FillBytes(result)
   103  	return result
   104  }
   105  
   106  var defaultEncrypterOpts = &EncrypterOpts{ENCODING_PLAIN, MarshalUncompressed, C1C3C2}
   107  
   108  var ASN1EncrypterOpts = &EncrypterOpts{ENCODING_ASN1, MarshalUncompressed, C1C3C2}
   109  
   110  var ASN1DecrypterOpts = &DecrypterOpts{ENCODING_ASN1, C1C3C2}
   111  
   112  // directSigning is a standard Hash value that signals that no pre-hashing
   113  // should be performed.
   114  var directSigning crypto.Hash = 0
   115  
   116  // Signer SM2 special signer
   117  type Signer interface {
   118  	SignWithSM2(rand io.Reader, uid, msg []byte) ([]byte, error)
   119  }
   120  
   121  // SM2SignerOption implements crypto.SignerOpts interface.
   122  // It is specific for SM2, used in private key's Sign method.
   123  type SM2SignerOption struct {
   124  	uid         []byte
   125  	forceGMSign bool
   126  }
   127  
   128  // NewSM2SignerOption creates a SM2 specific signer option.
   129  // forceGMSign - if use GM specific sign logic, if yes, should pass raw message to sign.
   130  // uid - if forceGMSign is true, then you can pass uid, if no uid is provided, system will use default one.
   131  func NewSM2SignerOption(forceGMSign bool, uid []byte) *SM2SignerOption {
   132  	opt := &SM2SignerOption{
   133  		uid:         uid,
   134  		forceGMSign: forceGMSign,
   135  	}
   136  	if forceGMSign && len(uid) == 0 {
   137  		opt.uid = defaultUID
   138  	}
   139  	return opt
   140  }
   141  
   142  // DefaultSM2SignerOpts uses default UID and forceGMSign is true.
   143  var DefaultSM2SignerOpts = NewSM2SignerOption(true, nil)
   144  
   145  func (*SM2SignerOption) HashFunc() crypto.Hash {
   146  	return directSigning
   147  }
   148  
   149  // FromECPrivateKey convert an ecdsa private key to SM2 private key.
   150  func (priv *PrivateKey) FromECPrivateKey(key *ecdsa.PrivateKey) (*PrivateKey, error) {
   151  	if key.Curve != sm2ec.P256() {
   152  		return nil, errors.New("sm2: it's NOT a sm2 curve private key")
   153  	}
   154  	priv.PrivateKey = *key
   155  	return priv, nil
   156  }
   157  
   158  func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {
   159  	xx, ok := x.(*PrivateKey)
   160  	if !ok {
   161  		return false
   162  	}
   163  	return priv.PublicKey.Equal(&xx.PublicKey) && bigIntEqual(priv.D, xx.D)
   164  }
   165  
   166  // bigIntEqual reports whether a and b are equal leaking only their bit length
   167  // through timing side-channels.
   168  func bigIntEqual(a, b *big.Int) bool {
   169  	return _subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1
   170  }
   171  
   172  // Sign signs digest with priv, reading randomness from rand. Compliance with GB/T 32918.2-2016.
   173  // The opts argument is currently used for SM2SignerOption checking only.
   174  // If the opts argument is SM2SignerOption and its ForceGMSign is true,
   175  // digest argument will be treated as raw data and UID will be taken from opts.
   176  //
   177  // This method implements crypto.Signer, which is an interface to support keys
   178  // where the private part is kept in, for example, a hardware module.
   179  func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
   180  	return SignASN1(rand, priv, digest, opts)
   181  }
   182  
   183  // SignWithSM2 signs uid, msg with priv, reading randomness from rand. Compliance with GB/T 32918.2-2016.
   184  // Deprecated: please use Sign method directly.
   185  func (priv *PrivateKey) SignWithSM2(rand io.Reader, uid, msg []byte) ([]byte, error) {
   186  	return priv.Sign(rand, msg, NewSM2SignerOption(true, uid))
   187  }
   188  
   189  // Decrypt decrypts ciphertext msg to plaintext.
   190  // The opts argument should be appropriate for the primitive used.
   191  // Compliance with GB/T 32918.4-2016 chapter 7.
   192  func (priv *PrivateKey) Decrypt(rand io.Reader, msg []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
   193  	var sm2Opts *DecrypterOpts
   194  	sm2Opts, _ = opts.(*DecrypterOpts)
   195  	return decrypt(priv, msg, sm2Opts)
   196  }
   197  
   198  const maxRetryLimit = 100
   199  
   200  var (
   201  	errCiphertextTooShort = errors.New("sm2: ciphertext too short")
   202  )
   203  
   204  // EncryptASN1 sm2 encrypt and output ASN.1 result, compliance with GB/T 32918.4-2016.
   205  //
   206  // The random parameter is used as a source of entropy to ensure that
   207  // encrypting the same message twice doesn't result in the same ciphertext.
   208  // Most applications should use [crypto/rand.Reader] as random.
   209  func EncryptASN1(random io.Reader, pub *ecdsa.PublicKey, msg []byte) ([]byte, error) {
   210  	return Encrypt(random, pub, msg, ASN1EncrypterOpts)
   211  }
   212  
   213  // Encrypt sm2 encrypt implementation, compliance with GB/T 32918.4-2016.
   214  //
   215  // The random parameter is used as a source of entropy to ensure that
   216  // encrypting the same message twice doesn't result in the same ciphertext.
   217  // Most applications should use [crypto/rand.Reader] as random.
   218  func Encrypt(random io.Reader, pub *ecdsa.PublicKey, msg []byte, opts *EncrypterOpts) ([]byte, error) {
   219  	//A3, requirement is to check if h*P is infinite point, h is 1
   220  	if pub.X.Sign() == 0 && pub.Y.Sign() == 0 {
   221  		return nil, errors.New("sm2: public key point is the infinity")
   222  	}
   223  	if len(msg) == 0 {
   224  		return nil, nil
   225  	}
   226  	if opts == nil {
   227  		opts = defaultEncrypterOpts
   228  	}
   229  	switch pub.Curve.Params() {
   230  	case P256().Params():
   231  		return encryptSM2EC(p256(), pub, random, msg, opts)
   232  	default:
   233  		return encryptLegacy(random, pub, msg, opts)
   234  	}
   235  }
   236  
   237  func encryptSM2EC(c *sm2Curve, pub *ecdsa.PublicKey, random io.Reader, msg []byte, opts *EncrypterOpts) ([]byte, error) {
   238  	Q, err := c.pointFromAffine(pub.X, pub.Y)
   239  	if err != nil {
   240  		return nil, err
   241  	}
   242  	var retryCount int = 0
   243  	for {
   244  		k, C1, err := randomPoint(c, random, false)
   245  		if err != nil {
   246  			return nil, err
   247  		}
   248  		C2, err := Q.ScalarMult(Q, k.Bytes(c.N))
   249  		if err != nil {
   250  			return nil, err
   251  		}
   252  		C2Bytes := C2.Bytes()[1:]
   253  		c2 := sm3.Kdf(C2Bytes, len(msg))
   254  		if subtle.ConstantTimeAllZero(c2) == 1 {
   255  			retryCount++
   256  			if retryCount > maxRetryLimit {
   257  				return nil, fmt.Errorf("sm2: A5, failed to calculate valid t, tried %v times", retryCount)
   258  			}
   259  			continue
   260  		}
   261  		//A6, C2 = M + t;
   262  		subtle.XORBytes(c2, msg, c2)
   263  
   264  		//A7, C3 = hash(x2||M||y2)
   265  		md := sm3.New()
   266  		md.Write(C2Bytes[:len(C2Bytes)/2])
   267  		md.Write(msg)
   268  		md.Write(C2Bytes[len(C2Bytes)/2:])
   269  		c3 := md.Sum(nil)
   270  
   271  		if opts.ciphertextEncoding == ENCODING_PLAIN {
   272  			return encodingCiphertext(opts, C1, c2, c3)
   273  		}
   274  		return encodingCiphertextASN1(C1, c2, c3)
   275  	}
   276  }
   277  
   278  func encodingCiphertext(opts *EncrypterOpts, C1 *_sm2ec.SM2P256Point, c2, c3 []byte) ([]byte, error) {
   279  	var c1 []byte
   280  	switch opts.pointMarshalMode {
   281  	case MarshalCompressed:
   282  		c1 = C1.BytesCompressed()
   283  	default:
   284  		c1 = C1.Bytes()
   285  	}
   286  
   287  	if opts.ciphertextSplicingOrder == C1C3C2 {
   288  		// c1 || c3 || c2
   289  		return append(append(c1, c3...), c2...), nil
   290  	}
   291  	// c1 || c2 || c3
   292  	return append(append(c1, c2...), c3...), nil
   293  }
   294  
   295  func encodingCiphertextASN1(C1 *_sm2ec.SM2P256Point, c2, c3 []byte) ([]byte, error) {
   296  	c1 := C1.Bytes()
   297  	var b cryptobyte.Builder
   298  	b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
   299  		addASN1IntBytes(b, c1[1:len(c1)/2+1])
   300  		addASN1IntBytes(b, c1[len(c1)/2+1:])
   301  		b.AddASN1OctetString(c3)
   302  		b.AddASN1OctetString(c2)
   303  	})
   304  	return b.Bytes()
   305  }
   306  
   307  // GenerateKey generates a new SM2 private key.
   308  //
   309  // Most applications should use [crypto/rand.Reader] as rand. Note that the
   310  // returned key does not depend deterministically on the bytes read from rand,
   311  // and may change between calls and/or between versions.
   312  func GenerateKey(rand io.Reader) (*PrivateKey, error) {
   313  	randutil.MaybeReadByte(rand)
   314  
   315  	c := p256()
   316  	k, Q, err := randomPoint(c, rand, true)
   317  	if err != nil {
   318  		return nil, err
   319  	}
   320  
   321  	priv := new(PrivateKey)
   322  	priv.PublicKey.Curve = c.curve
   323  	priv.D = new(big.Int).SetBytes(k.Bytes(c.N))
   324  	priv.PublicKey.X, priv.PublicKey.Y, err = c.pointToAffine(Q)
   325  	if err != nil {
   326  		return nil, err
   327  	}
   328  	return priv, nil
   329  }
   330  
   331  // NewPrivateKey checks that key is valid and returns a SM2 PrivateKey.
   332  //
   333  // key - the private key byte slice, the length must be 32 for SM2.
   334  func NewPrivateKey(key []byte) (*PrivateKey, error) {
   335  	c := p256()
   336  	if len(key) != c.N.Size() {
   337  		return nil, errors.New("sm2: invalid private key size")
   338  	}
   339  	k, err := bigmod.NewNat().SetBytes(key, c.N)
   340  	if err != nil || k.IsZero() == 1 || k.Equal(c.nMinus1) == 1 {
   341  		return nil, errInvalidPrivateKey
   342  	}
   343  	p, err := c.newPoint().ScalarBaseMult(k.Bytes(c.N))
   344  	if err != nil {
   345  		return nil, err
   346  	}
   347  	priv := new(PrivateKey)
   348  	priv.PublicKey.Curve = c.curve
   349  	priv.D = new(big.Int).SetBytes(k.Bytes(c.N))
   350  	priv.PublicKey.X, priv.PublicKey.Y, err = c.pointToAffine(p)
   351  	if err != nil {
   352  		return nil, err
   353  	}
   354  	return priv, nil
   355  }
   356  
   357  // NewPrivateKeyFromInt checks that key is valid and returns a SM2 PrivateKey.
   358  func NewPrivateKeyFromInt(key *big.Int) (*PrivateKey, error) {
   359  	if key == nil {
   360  		return nil, errors.New("sm2: invalid private key size")
   361  	}
   362  	keyBytes := make([]byte, p256().N.Size())
   363  	return NewPrivateKey(key.FillBytes(keyBytes))
   364  }
   365  
   366  // NewPublicKey checks that key is valid and returns a PublicKey.
   367  func NewPublicKey(key []byte) (*ecdsa.PublicKey, error) {
   368  	c := p256()
   369  	// Reject the point at infinity and compressed encodings.
   370  	if len(key) == 0 || key[0] != 4 {
   371  		return nil, errors.New("sm2: invalid public key")
   372  	}
   373  	// SetBytes also checks that the point is on the curve.
   374  	p, err := c.newPoint().SetBytes(key)
   375  	if err != nil {
   376  		return nil, err
   377  	}
   378  	k := new(ecdsa.PublicKey)
   379  	k.Curve = c.curve
   380  	k.X, k.Y, err = c.pointToAffine(p)
   381  	if err != nil {
   382  		return nil, err
   383  	}
   384  	return k, nil
   385  }
   386  
   387  // Decrypt sm2 decrypt implementation by default DecrypterOpts{C1C3C2}.
   388  // Compliance with GB/T 32918.4-2016.
   389  func Decrypt(priv *PrivateKey, ciphertext []byte) ([]byte, error) {
   390  	return decrypt(priv, ciphertext, nil)
   391  }
   392  
   393  // ErrDecryption represents a failure to decrypt a message.
   394  // It is deliberately vague to avoid adaptive attacks.
   395  var ErrDecryption = errors.New("sm2: decryption error")
   396  
   397  func decrypt(priv *PrivateKey, ciphertext []byte, opts *DecrypterOpts) ([]byte, error) {
   398  	ciphertextLen := len(ciphertext)
   399  	if ciphertextLen <= 1+(priv.Params().BitSize/8)+sm3.Size {
   400  		return nil, errCiphertextTooShort
   401  	}
   402  	switch priv.Curve.Params() {
   403  	case P256().Params():
   404  		return decryptSM2EC(p256(), priv, ciphertext, opts)
   405  	default:
   406  		return decryptLegacy(priv, ciphertext, opts)
   407  	}
   408  }
   409  
   410  func decryptSM2EC(c *sm2Curve, priv *PrivateKey, ciphertext []byte, opts *DecrypterOpts) ([]byte, error) {
   411  	C1, c2, c3, err := parseCiphertext(c, ciphertext, opts)
   412  	if err != nil {
   413  		return nil, ErrDecryption
   414  	}
   415  	d, err := bigmod.NewNat().SetBytes(priv.D.Bytes(), c.N)
   416  	if err != nil {
   417  		return nil, ErrDecryption
   418  	}
   419  
   420  	C2, err := C1.ScalarMult(C1, d.Bytes(c.N))
   421  	if err != nil {
   422  		return nil, ErrDecryption
   423  	}
   424  	C2Bytes := C2.Bytes()[1:]
   425  	msgLen := len(c2)
   426  	msg := sm3.Kdf(C2Bytes, msgLen)
   427  	if subtle.ConstantTimeAllZero(c2) == 1 {
   428  		return nil, ErrDecryption
   429  	}
   430  
   431  	//B5, calculate msg = c2 ^ t
   432  	subtle.XORBytes(msg, c2, msg)
   433  
   434  	md := sm3.New()
   435  	md.Write(C2Bytes[:len(C2Bytes)/2])
   436  	md.Write(msg)
   437  	md.Write(C2Bytes[len(C2Bytes)/2:])
   438  	u := md.Sum(nil)
   439  
   440  	if _subtle.ConstantTimeCompare(u, c3) == 1 {
   441  		return msg, nil
   442  	}
   443  	return nil, ErrDecryption
   444  }
   445  
   446  func parseCiphertext(c *sm2Curve, ciphertext []byte, opts *DecrypterOpts) (*_sm2ec.SM2P256Point, []byte, []byte, error) {
   447  	bitSize := c.curve.Params().BitSize
   448  	// Encode the coordinates and let SetBytes reject invalid points.
   449  	byteLen := (bitSize + 7) / 8
   450  	splicingOrder := C1C3C2
   451  	if opts != nil {
   452  		splicingOrder = opts.cipherTextSplicingOrder
   453  	}
   454  
   455  	b := ciphertext[0]
   456  	switch b {
   457  	case uncompressed:
   458  		if len(ciphertext) <= 1+2*byteLen+sm3.Size {
   459  			return nil, nil, nil, errCiphertextTooShort
   460  		}
   461  		C1, err := c.newPoint().SetBytes(ciphertext[:1+2*byteLen])
   462  		if err != nil {
   463  			return nil, nil, nil, err
   464  		}
   465  		c2, c3 := parseCiphertextC2C3(ciphertext[1+2*byteLen:], splicingOrder)
   466  		return C1, c2, c3, nil
   467  	case compressed02, compressed03:
   468  		C1, err := c.newPoint().SetBytes(ciphertext[:1+byteLen])
   469  		if err != nil {
   470  			return nil, nil, nil, err
   471  		}
   472  		c2, c3 := parseCiphertextC2C3(ciphertext[1+byteLen:], splicingOrder)
   473  		return C1, c2, c3, nil
   474  	case byte(0x30):
   475  		return parseCiphertextASN1(c, ciphertext)
   476  	default:
   477  		return nil, nil, nil, errors.New("sm2: invalid/unsupport ciphertext format")
   478  	}
   479  }
   480  
   481  func parseCiphertextC2C3(ciphertext []byte, order ciphertextSplicingOrder) ([]byte, []byte) {
   482  	if order == C1C3C2 {
   483  		return ciphertext[sm3.Size:], ciphertext[:sm3.Size]
   484  	}
   485  	return ciphertext[:len(ciphertext)-sm3.Size], ciphertext[len(ciphertext)-sm3.Size:]
   486  }
   487  
   488  func unmarshalASN1Ciphertext(ciphertext []byte) (*big.Int, *big.Int, []byte, []byte, error) {
   489  	var (
   490  		x1, y1 = &big.Int{}, &big.Int{}
   491  		c2, c3 []byte
   492  		inner  cryptobyte.String
   493  	)
   494  	input := cryptobyte.String(ciphertext)
   495  	if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
   496  		!input.Empty() ||
   497  		!inner.ReadASN1Integer(x1) ||
   498  		!inner.ReadASN1Integer(y1) ||
   499  		!inner.ReadASN1Bytes(&c3, asn1.OCTET_STRING) ||
   500  		!inner.ReadASN1Bytes(&c2, asn1.OCTET_STRING) ||
   501  		!inner.Empty() {
   502  		return nil, nil, nil, nil, errors.New("sm2: invalid asn1 format ciphertext")
   503  	}
   504  	return x1, y1, c2, c3, nil
   505  }
   506  
   507  func parseCiphertextASN1(c *sm2Curve, ciphertext []byte) (*_sm2ec.SM2P256Point, []byte, []byte, error) {
   508  	x1, y1, c2, c3, err := unmarshalASN1Ciphertext(ciphertext)
   509  	if err != nil {
   510  		return nil, nil, nil, err
   511  	}
   512  	C1, err := c.pointFromAffine(x1, y1)
   513  	if err != nil {
   514  		return nil, nil, nil, err
   515  	}
   516  	return C1, c2, c3, nil
   517  }
   518  
   519  var defaultUID = []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}
   520  
   521  // CalculateZA ZA = H256(ENTLA || IDA || a || b || xG || yG || xA || yA).
   522  // Compliance with GB/T 32918.2-2016 5.5.
   523  //
   524  // This function will not use default UID even the uid argument is empty.
   525  func CalculateZA(pub *ecdsa.PublicKey, uid []byte) ([]byte, error) {
   526  	uidLen := len(uid)
   527  	if uidLen >= 0x2000 {
   528  		return nil, errors.New("sm2: the uid is too long")
   529  	}
   530  	entla := uint16(uidLen) << 3
   531  	md := sm3.New()
   532  	md.Write([]byte{byte(entla >> 8), byte(entla)})
   533  	if uidLen > 0 {
   534  		md.Write(uid)
   535  	}
   536  	a := new(big.Int).Sub(pub.Params().P, big.NewInt(3))
   537  	md.Write(toBytes(pub.Curve, a))
   538  	md.Write(toBytes(pub.Curve, pub.Params().B))
   539  	md.Write(toBytes(pub.Curve, pub.Params().Gx))
   540  	md.Write(toBytes(pub.Curve, pub.Params().Gy))
   541  	md.Write(toBytes(pub.Curve, pub.X))
   542  	md.Write(toBytes(pub.Curve, pub.Y))
   543  	return md.Sum(nil), nil
   544  }
   545  
   546  // CalculateSM2Hash calculates hash value for data including uid and public key parameters
   547  // according standards.
   548  //
   549  // uid can be nil, then it will use default uid (1234567812345678)
   550  func CalculateSM2Hash(pub *ecdsa.PublicKey, data, uid []byte) ([]byte, error) {
   551  	if len(uid) == 0 {
   552  		uid = defaultUID
   553  	}
   554  	za, err := CalculateZA(pub, uid)
   555  	if err != nil {
   556  		return nil, err
   557  	}
   558  	md := sm3.New()
   559  	md.Write(za)
   560  	md.Write(data)
   561  	return md.Sum(nil), nil
   562  }
   563  
   564  // SignASN1 signs a hash (which should be the result of hashing a larger message)
   565  // using the private key, priv. If the hash is longer than the bit-length of the
   566  // private key's curve order, the hash will be truncated to that length. It
   567  // returns the ASN.1 encoded signature.
   568  //
   569  // The signature is randomized. Most applications should use [crypto/rand.Reader]
   570  // as rand. Note that the returned signature does not depend deterministically on
   571  // the bytes read from rand, and may change between calls and/or between versions.
   572  //
   573  // If the opts argument is instance of [*SM2SignerOption], and its ForceGMSign is true,
   574  // then the hash will be treated as raw message.
   575  func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte, opts crypto.SignerOpts) ([]byte, error) {
   576  	if sm2Opts, ok := opts.(*SM2SignerOption); ok && sm2Opts.forceGMSign {
   577  		newHash, err := CalculateSM2Hash(&priv.PublicKey, hash, sm2Opts.uid)
   578  		if err != nil {
   579  			return nil, err
   580  		}
   581  		hash = newHash
   582  	}
   583  
   584  	randutil.MaybeReadByte(rand)
   585  
   586  	switch priv.Curve.Params() {
   587  	case P256().Params():
   588  		return signSM2EC(p256(), priv, rand, hash)
   589  	default:
   590  		return signLegacy(priv, rand, hash)
   591  	}
   592  }
   593  
   594  func (priv *PrivateKey) inverseOfPrivateKeyPlus1(c *sm2Curve) (*bigmod.Nat, error) {
   595  	var (
   596  		err            error
   597  		dp1Inv, oneNat *bigmod.Nat
   598  		dp1Bytes       []byte
   599  	)
   600  	priv.inverseOfKeyPlus1Once.Do(func() {
   601  		oneNat, _ = bigmod.NewNat().SetBytes(one.Bytes(), c.N)
   602  		dp1Inv, err = bigmod.NewNat().SetBytes(priv.D.Bytes(), c.N)
   603  		if err == nil {
   604  			dp1Inv.Add(oneNat, c.N)
   605  			if dp1Inv.IsZero() == 1 { // make sure private key is NOT N-1
   606  				err = errInvalidPrivateKey
   607  			} else {
   608  				dp1Bytes, err = _sm2ec.P256OrdInverse(dp1Inv.Bytes(c.N))
   609  				if err == nil {
   610  					priv.inverseOfKeyPlus1, err = bigmod.NewNat().SetBytes(dp1Bytes, c.N)
   611  				}
   612  			}
   613  		}
   614  	})
   615  	if err != nil {
   616  		return nil, errInvalidPrivateKey
   617  	}
   618  	return priv.inverseOfKeyPlus1, nil
   619  }
   620  
   621  func signSM2EC(c *sm2Curve, priv *PrivateKey, rand io.Reader, hash []byte) (sig []byte, err error) {
   622  	// dp1Inv = (d+1)⁻¹
   623  	dp1Inv, err := priv.inverseOfPrivateKeyPlus1(c)
   624  	if err != nil {
   625  		return nil, err
   626  	}
   627  
   628  	var (
   629  		k, r, s *bigmod.Nat
   630  		R       *_sm2ec.SM2P256Point
   631  	)
   632  
   633  	// hash to int
   634  	e := bigmod.NewNat()
   635  	hashToNat(c, e, hash)
   636  
   637  	for {
   638  		for {
   639  			k, R, err = randomPoint(c, rand, false)
   640  			if err != nil {
   641  				return nil, err
   642  			}
   643  			Rx, err := R.BytesX()
   644  			if err != nil {
   645  				return nil, err
   646  			}
   647  			r, err = bigmod.NewNat().SetOverflowingBytes(Rx, c.N)
   648  			if err != nil {
   649  				return nil, err
   650  			}
   651  
   652  			// r = [Rx + e]
   653  			r.Add(e, c.N)
   654  
   655  			// checks if r is zero or [r+k] is zero
   656  			if r.IsZero() == 0 {
   657  				t := bigmod.NewNat().Set(k).Add(r, c.N)
   658  				if t.IsZero() == 0 {
   659  					break
   660  				}
   661  			}
   662  		}
   663  		// s = [r * d]
   664  		s, err = bigmod.NewNat().SetBytes(priv.D.Bytes(), c.N)
   665  		if err != nil {
   666  			return nil, err
   667  		}
   668  		s.Mul(r, c.N)
   669  		// k = [k - s]
   670  		k.Sub(s, c.N)
   671  		// k = [(d+1)⁻¹ * (k - r * d)]
   672  		k.Mul(dp1Inv, c.N)
   673  		if k.IsZero() == 0 {
   674  			break
   675  		}
   676  	}
   677  
   678  	return encodeSignature(r.Bytes(c.N), k.Bytes(c.N))
   679  }
   680  
   681  func encodeSignature(r, s []byte) ([]byte, error) {
   682  	var b cryptobyte.Builder
   683  	b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
   684  		addASN1IntBytes(b, r)
   685  		addASN1IntBytes(b, s)
   686  	})
   687  	return b.Bytes()
   688  }
   689  
   690  // addASN1IntBytes encodes in ASN.1 a positive integer represented as
   691  // a big-endian byte slice with zero or more leading zeroes.
   692  func addASN1IntBytes(b *cryptobyte.Builder, bytes []byte) {
   693  	for len(bytes) > 0 && bytes[0] == 0 {
   694  		bytes = bytes[1:]
   695  	}
   696  	if len(bytes) == 0 {
   697  		b.SetError(errors.New("invalid integer"))
   698  		return
   699  	}
   700  	b.AddASN1(asn1.INTEGER, func(c *cryptobyte.Builder) {
   701  		if bytes[0]&0x80 != 0 {
   702  			c.AddUint8(0)
   703  		}
   704  		c.AddBytes(bytes)
   705  	})
   706  }
   707  
   708  var ErrInvalidSignature = errors.New("sm2: invalid signature")
   709  
   710  // RecoverPublicKeysFromSM2Signature recovers two or four SM2 public keys from a given signature and hash.
   711  // It takes the hash and signature as input and returns the recovered public keys as []*ecdsa.PublicKey.
   712  // If the signature or hash is invalid, it returns an error.
   713  // The function follows the SM2 algorithm to recover the public keys.
   714  func RecoverPublicKeysFromSM2Signature(hash, sig []byte) ([]*ecdsa.PublicKey, error) {
   715  	c := p256()
   716  	rBytes, sBytes, err := parseSignature(sig)
   717  	if err != nil {
   718  		return nil, err
   719  	}
   720  	r, err := bigmod.NewNat().SetBytes(rBytes, c.N)
   721  	if err != nil || r.IsZero() == 1 {
   722  		return nil, ErrInvalidSignature
   723  	}
   724  	s, err := bigmod.NewNat().SetBytes(sBytes, c.N)
   725  	if err != nil || s.IsZero() == 1 {
   726  		return nil, ErrInvalidSignature
   727  	}
   728  
   729  	e := bigmod.NewNat()
   730  	hashToNat(c, e, hash)
   731  
   732  	// p₁ = [-s]G
   733  	negS := bigmod.NewNat().ExpandFor(c.N).Sub(s, c.N)
   734  	p1, err := c.newPoint().ScalarBaseMult(negS.Bytes(c.N))
   735  	if err != nil {
   736  		return nil, err
   737  	}
   738  
   739  	// s = [r + s]
   740  	s.Add(r, c.N)
   741  	if s.IsZero() == 1 {
   742  		return nil, ErrInvalidSignature
   743  	}
   744  	// sBytes = (r+s)⁻¹
   745  	sBytes, err = _sm2ec.P256OrdInverse(s.Bytes(c.N))
   746  	if err != nil {
   747  		return nil, err
   748  	}
   749  
   750  	// r = (Rx + e) mod N
   751  	// Rx = r - e
   752  	r.Sub(e, c.N)
   753  	if r.IsZero() == 1 {
   754  		return nil, ErrInvalidSignature
   755  	}
   756  	pointRx := make([]*bigmod.Nat, 0, 2)
   757  	pointRx = append(pointRx, r)
   758  	// check if Rx in (N, P), small probability event
   759  	s.Set(r)
   760  	s = s.Add(c.N.Nat(), c.P)
   761  	if s.CmpGeq(c.N.Nat()) == 1 {
   762  		pointRx = append(pointRx, s)
   763  	}
   764  	pubs := make([]*ecdsa.PublicKey, 0, 4)
   765  	bytes := make([]byte, 32+1)
   766  	compressFlags := []byte{compressed02, compressed03}
   767  	// Rx has one or two possible values, so point R has two or four possible values
   768  	for _, x := range pointRx {
   769  		rBytes = x.Bytes(c.N)
   770  		copy(bytes[1:], rBytes)
   771  		for _, flag := range compressFlags {
   772  			bytes[0] = flag
   773  			// p0 = R
   774  			p0, err := c.newPoint().SetBytes(bytes)
   775  			if err != nil {
   776  				return nil, err
   777  			}
   778  			// p0 = R - [s]G
   779  			p0.Add(p0, p1)
   780  			// Pub = [(r + s)⁻¹](R - [s]G)
   781  			p0.ScalarMult(p0, sBytes)
   782  			pub := new(ecdsa.PublicKey)
   783  			pub.Curve = c.curve
   784  			pub.X, pub.Y, err = c.pointToAffine(p0)
   785  			if err != nil {
   786  				return nil, err
   787  			}
   788  			pubs = append(pubs, pub)
   789  		}
   790  	}
   791  
   792  	return pubs, nil
   793  }
   794  
   795  // VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the
   796  // public key, pub. Its return value records whether the signature is valid.
   797  //
   798  // Compliance with GB/T 32918.2-2016 regardless it's SM2 curve or not.
   799  // Caller should make sure the hash's correctness, in other words,
   800  // the caller must pre-calculate the hash value.
   801  func VerifyASN1(pub *ecdsa.PublicKey, hash, sig []byte) bool {
   802  	switch pub.Curve.Params() {
   803  	case P256().Params():
   804  		return verifySM2EC(p256(), pub, hash, sig)
   805  	default:
   806  		return verifyLegacy(pub, hash, sig)
   807  	}
   808  }
   809  
   810  func verifySM2EC(c *sm2Curve, pub *ecdsa.PublicKey, hash, sig []byte) bool {
   811  	rBytes, sBytes, err := parseSignature(sig)
   812  	if err != nil {
   813  		return false
   814  	}
   815  
   816  	Q, err := c.pointFromAffine(pub.X, pub.Y)
   817  	if err != nil {
   818  		return false
   819  	}
   820  
   821  	r, err := bigmod.NewNat().SetBytes(rBytes, c.N)
   822  	if err != nil || r.IsZero() == 1 {
   823  		return false
   824  	}
   825  	s, err := bigmod.NewNat().SetBytes(sBytes, c.N)
   826  	if err != nil || s.IsZero() == 1 {
   827  		return false
   828  	}
   829  
   830  	e := bigmod.NewNat()
   831  	hashToNat(c, e, hash)
   832  
   833  	// p₁ = [s]G
   834  	p1, err := c.newPoint().ScalarBaseMult(s.Bytes(c.N))
   835  	if err != nil {
   836  		return false
   837  	}
   838  
   839  	// s = [r + s]
   840  	s.Add(r, c.N)
   841  	if s.IsZero() == 1 {
   842  		return false
   843  	}
   844  
   845  	// p₂ = [r+s]Q
   846  	p2, err := Q.ScalarMult(Q, s.Bytes(c.N))
   847  	if err != nil {
   848  		return false
   849  	}
   850  
   851  	// BytesX returns an error for the point at infinity.
   852  	Rx, err := p1.Add(p1, p2).BytesX()
   853  	if err != nil {
   854  		return false
   855  	}
   856  
   857  	_, err = s.SetOverflowingBytes(Rx, c.N)
   858  	if err != nil {
   859  		return false
   860  	}
   861  	s.Add(e, c.N)
   862  
   863  	return s.Equal(r) == 1
   864  }
   865  
   866  // VerifyASN1WithSM2 verifies the signature in ASN.1 encoding format sig of raw msg
   867  // and uid using the public key, pub. The uid can be empty, meaning to use the default value.
   868  //
   869  // It returns value records whether the signature is valid. Compliance with GB/T 32918.2-2016.
   870  func VerifyASN1WithSM2(pub *ecdsa.PublicKey, uid, msg, sig []byte) bool {
   871  	digest, err := CalculateSM2Hash(pub, msg, uid)
   872  	if err != nil {
   873  		return false
   874  	}
   875  	return VerifyASN1(pub, digest, sig)
   876  }
   877  
   878  func parseSignature(sig []byte) (r, s []byte, err error) {
   879  	var inner cryptobyte.String
   880  	input := cryptobyte.String(sig)
   881  	if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
   882  		!input.Empty() ||
   883  		!inner.ReadASN1Integer(&r) ||
   884  		!inner.ReadASN1Integer(&s) ||
   885  		!inner.Empty() {
   886  		return nil, nil, errors.New("invalid ASN.1")
   887  	}
   888  	return r, s, nil
   889  }
   890  
   891  // hashToNat sets e to the left-most bits of hash, according to
   892  // SEC 1, Section 4.1.3, point 5 and Section 4.1.4, point 3.
   893  func hashToNat(c *sm2Curve, e *bigmod.Nat, hash []byte) {
   894  	// ECDSA asks us to take the left-most log2(N) bits of hash, and use them as
   895  	// an integer modulo N. This is the absolute worst of all worlds: we still
   896  	// have to reduce, because the result might still overflow N, but to take
   897  	// the left-most bits for P-521 we have to do a right shift.
   898  	if size := c.N.Size(); len(hash) > size {
   899  		hash = hash[:size]
   900  		if excess := len(hash)*8 - c.N.BitLen(); excess > 0 {
   901  			hash = append([]byte{}, hash...)
   902  			for i := len(hash) - 1; i >= 0; i-- {
   903  				hash[i] >>= excess
   904  				if i > 0 {
   905  					hash[i] |= hash[i-1] << (8 - excess)
   906  				}
   907  			}
   908  		}
   909  	}
   910  	_, err := e.SetOverflowingBytes(hash, c.N)
   911  	if err != nil {
   912  		panic("sm2: internal error: truncated hash is too long")
   913  	}
   914  }
   915  
   916  // IsSM2PublicKey check if given public key is a SM2 public key or not
   917  func IsSM2PublicKey(publicKey any) bool {
   918  	pub, ok := publicKey.(*ecdsa.PublicKey)
   919  	return ok && pub.Curve == sm2ec.P256()
   920  }
   921  
   922  // P256 returns sm2 curve signleton, this function is for backward compatibility.
   923  func P256() elliptic.Curve {
   924  	return sm2ec.P256()
   925  }
   926  
   927  // PublicKeyToECDH returns k as a [ecdh.PublicKey]. It returns an error if the key is
   928  // invalid according to the definition of [ecdh.Curve.NewPublicKey], or if the
   929  // Curve is not supported by ecdh.
   930  func PublicKeyToECDH(k *ecdsa.PublicKey) (*ecdh.PublicKey, error) {
   931  	c := curveToECDH(k.Curve)
   932  	if c == nil {
   933  		return nil, errors.New("sm2: unsupported curve by ecdh")
   934  	}
   935  	if !k.Curve.IsOnCurve(k.X, k.Y) {
   936  		return nil, errors.New("sm2: invalid public key")
   937  	}
   938  	return c.NewPublicKey(elliptic.Marshal(k.Curve, k.X, k.Y))
   939  }
   940  
   941  // ECDH returns k as a [ecdh.PrivateKey]. It returns an error if the key is
   942  // invalid according to the definition of [ecdh.Curve.NewPrivateKey], or if the
   943  // Curve is not supported by ecdh.
   944  func (k *PrivateKey) ECDH() (*ecdh.PrivateKey, error) {
   945  	c := curveToECDH(k.Curve)
   946  	if c == nil {
   947  		return nil, errors.New("sm2: unsupported curve by ecdh")
   948  	}
   949  	size := (k.Curve.Params().N.BitLen() + 7) / 8
   950  	if k.D.BitLen() > size*8 {
   951  		return nil, errors.New("sm2: invalid private key")
   952  	}
   953  	return c.NewPrivateKey(k.D.FillBytes(make([]byte, size)))
   954  }
   955  
   956  func curveToECDH(c elliptic.Curve) ecdh.Curve {
   957  	switch c {
   958  	case sm2ec.P256():
   959  		return ecdh.P256()
   960  	default:
   961  		return nil
   962  	}
   963  }
   964  
   965  // randomPoint returns a random scalar and the corresponding point using the
   966  // procedure given in FIPS 186-4, Appendix B.5.2 (rejection sampling).
   967  func randomPoint(c *sm2Curve, rand io.Reader, checkOrderMinus1 bool) (k *bigmod.Nat, p *_sm2ec.SM2P256Point, err error) {
   968  	k = bigmod.NewNat()
   969  	for {
   970  		b := make([]byte, c.N.Size())
   971  		if _, err = io.ReadFull(rand, b); err != nil {
   972  			return
   973  		}
   974  
   975  		// Mask off any excess bits to increase the chance of hitting a value in
   976  		// (0, N). These are the most dangerous lines in the package and maybe in
   977  		// the library: a single bit of bias in the selection of nonces would likely
   978  		// lead to key recovery, but no tests would fail. Look but DO NOT TOUCH.
   979  		if excess := len(b)*8 - c.N.BitLen(); excess > 0 {
   980  			// Just to be safe, assert that this only happens for the one curve that
   981  			// doesn't have a round number of bits.
   982  			if excess != 0 {
   983  				panic("sm2: internal error: unexpectedly masking off bits")
   984  			}
   985  			b[0] >>= excess
   986  		}
   987  
   988  		// Checking 0 < k <= N - 2.
   989  		// None of this matters anyway because the chance of selecting
   990  		// zero is cryptographically negligible.
   991  		if _, err = k.SetBytes(b, c.N); err == nil && k.IsZero() == 0 && (!checkOrderMinus1 || k.Equal(c.nMinus1) == 0) {
   992  			break
   993  		}
   994  
   995  		if testingOnlyRejectionSamplingLooped != nil {
   996  			testingOnlyRejectionSamplingLooped()
   997  		}
   998  	}
   999  
  1000  	p, err = c.newPoint().ScalarBaseMult(k.Bytes(c.N))
  1001  	return
  1002  }
  1003  
  1004  // testingOnlyRejectionSamplingLooped is called when rejection sampling in
  1005  // randomPoint rejects a candidate for being higher than the modulus.
  1006  var testingOnlyRejectionSamplingLooped func()
  1007  
  1008  type sm2Curve struct {
  1009  	newPoint func() *_sm2ec.SM2P256Point
  1010  	curve    elliptic.Curve
  1011  	N        *bigmod.Modulus
  1012  	P        *bigmod.Modulus
  1013  	nMinus1  *bigmod.Nat
  1014  	nMinus2  []byte
  1015  }
  1016  
  1017  // pointFromAffine is used to convert the PublicKey to a sm2 Point.
  1018  func (curve *sm2Curve) pointFromAffine(x, y *big.Int) (p *_sm2ec.SM2P256Point, err error) {
  1019  	bitSize := curve.curve.Params().BitSize
  1020  	// Reject values that would not get correctly encoded.
  1021  	if x.Sign() < 0 || y.Sign() < 0 {
  1022  		return p, errors.New("negative coordinate")
  1023  	}
  1024  	if x.BitLen() > bitSize || y.BitLen() > bitSize {
  1025  		return p, errors.New("overflowing coordinate")
  1026  	}
  1027  	// Encode the coordinates and let SetBytes reject invalid points.
  1028  	byteLen := (bitSize + 7) / 8
  1029  	buf := make([]byte, 1+2*byteLen)
  1030  	buf[0] = 4 // uncompressed point
  1031  	x.FillBytes(buf[1 : 1+byteLen])
  1032  	y.FillBytes(buf[1+byteLen : 1+2*byteLen])
  1033  	return curve.newPoint().SetBytes(buf)
  1034  }
  1035  
  1036  // pointToAffine is used to convert a sm2 Point to a PublicKey.
  1037  func (curve *sm2Curve) pointToAffine(p *_sm2ec.SM2P256Point) (x, y *big.Int, err error) {
  1038  	out := p.Bytes()
  1039  	if len(out) == 1 && out[0] == 0 {
  1040  		// This is the encoding of the point at infinity.
  1041  		return nil, nil, errors.New("sm2: public key point is the infinity")
  1042  	}
  1043  	byteLen := (curve.curve.Params().BitSize + 7) / 8
  1044  	x = new(big.Int).SetBytes(out[1 : 1+byteLen])
  1045  	y = new(big.Int).SetBytes(out[1+byteLen:])
  1046  	return x, y, nil
  1047  }
  1048  
  1049  var p256Once sync.Once
  1050  var _p256 *sm2Curve
  1051  
  1052  func p256() *sm2Curve {
  1053  	p256Once.Do(func() {
  1054  		_p256 = &sm2Curve{
  1055  			newPoint: func() *_sm2ec.SM2P256Point { return _sm2ec.NewSM2P256Point() },
  1056  		}
  1057  		precomputeParams(_p256, P256())
  1058  	})
  1059  	return _p256
  1060  }
  1061  
  1062  func precomputeParams(c *sm2Curve, curve elliptic.Curve) {
  1063  	params := curve.Params()
  1064  	c.curve = curve
  1065  	c.N, _ = bigmod.NewModulusFromBig(params.N)
  1066  	c.P, _ = bigmod.NewModulusFromBig(params.P)
  1067  	c.nMinus2 = new(big.Int).Sub(params.N, big.NewInt(2)).Bytes()
  1068  	c.nMinus1, _ = bigmod.NewNat().SetBytes(new(big.Int).Sub(params.N, big.NewInt(1)).Bytes(), c.N)
  1069  }
  1070  
  1071  var errInvalidPrivateKey = errors.New("sm2: invalid private key")