func VerifyASN1(pub *ecdsa.PublicKey, hash, sig []byte) bool {
	var (
		r, s  = &big.Int{}, &big.Int{}
		inner cryptobyte.String
	)
	input := cryptobyte.String(sig)
	if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
		!input.Empty() ||
		!inner.ReadASN1Integer(r) ||
		!inner.ReadASN1Integer(s) ||
		!inner.Empty() {
		return false
	}
	return Verify(pub, hash, r, s)
}
VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the
public key, pub. Its return value records whether the signature is valid.
package sm2
import (
	"crypto"
	"crypto/aes"
	"crypto/cipher"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/sha512"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"math/big"
	"strings"
	"sync"
	"github.com/emmansun/gmsm/sm3"
	"golang.org/x/crypto/cryptobyte"
	"golang.org/x/crypto/cryptobyte/asn1"
)
const (
	uncompressed byte = 0x04
	compressed02 byte = 0x02
	compressed03 byte = 0x03
	mixed06      byte = 0x06
	mixed07      byte = 0x07
)
type invertible interface {
	Inverse(k *big.Int) *big.Int
}
type combinedMult interface {
	CombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int)
}
type PrivateKey struct {
	ecdsa.PrivateKey
}
type pointMarshalMode byte
const (
	MarshalUncompressed pointMarshalMode = iota
	MarshalCompressed
	MarshalMixed
)
type EncrypterOpts struct {
	PointMarshalMode pointMarshalMode
}
func (mode pointMarshalMode) mashal(curve elliptic.Curve, x, y *big.Int) []byte {
	switch mode {
	case MarshalCompressed:
		return point2CompressedBytes(curve, x, y)
	case MarshalMixed:
		return point2MixedBytes(curve, x, y)
	default:
		return point2UncompressedBytes(curve, x, y)
	}
}
var defaultEncrypterOpts = EncrypterOpts{MarshalUncompressed}
var directSigning crypto.Hash = 0
type Signer interface {
	SignWithSM2(rand io.Reader, uid, msg []byte) ([]byte, error)
}
type SM2SignerOption struct {
	UID         []byte
	ForceGMSign bool
}
func NewSM2SignerOption(forceGMSign bool, uid []byte) *SM2SignerOption {
	opt := &SM2SignerOption{
		UID:         uid,
		ForceGMSign: forceGMSign,
	}
	if forceGMSign && len(uid) == 0 {
		opt.UID = defaultUID
	}
	return opt
}
func (*SM2SignerOption) HashFunc() crypto.Hash {
	return directSigning
}
func (priv *PrivateKey) FromECPrivateKey(key *ecdsa.PrivateKey) (*PrivateKey, error) {
	if key.Curve != P256() {
		return nil, errors.New("It's NOT a sm2 curve private key")
	}
	priv.PrivateKey = *key
	return priv, nil
}
func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
	var r, s *big.Int
	var err error
	if sm2Opts, ok := opts.(*SM2SignerOption); ok && sm2Opts.ForceGMSign {
		r, s, err = SignWithSM2(rand, &priv.PrivateKey, sm2Opts.UID, digest)
	} else {
		r, s, err = Sign(rand, &priv.PrivateKey, digest)
	}
	if err != nil {
		return nil, err
	}
	var b cryptobyte.Builder
	b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
		b.AddASN1BigInt(r)
		b.AddASN1BigInt(s)
	})
	return b.Bytes()
}
func (priv *PrivateKey) SignWithSM2(rand io.Reader, uid, msg []byte) ([]byte, error) {
	return priv.Sign(rand, msg, NewSM2SignerOption(true, uid))
}
func (priv *PrivateKey) Decrypt(rand io.Reader, msg []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
	return Decrypt(priv, msg)
}
var (
	one      = new(big.Int).SetInt64(1)
	initonce sync.Once
)
func P256() elliptic.Curve {
	initonce.Do(initP256)
	return p256
}
func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
	params := c.Params()
	b := make([]byte, params.BitSize/8+8)
	_, err = io.ReadFull(rand, b)
	if err != nil {
		return
	}
	k = new(big.Int).SetBytes(b)
	n := new(big.Int).Sub(params.N, one)
	k.Mod(k, n)
	k.Add(k, one)
	return
}
const maxRetryLimit = 100
func kdf(z []byte, len int) ([]byte, bool) {
	limit := (len + sm3.Size - 1) >> sm3.SizeBitSize
	md := sm3.New()
	var countBytes [4]byte
	var ct uint32 = 1
	k := make([]byte, len+sm3.Size-1)
	for i := 0; i < limit; i++ {
		binary.BigEndian.PutUint32(countBytes[:], ct)
		md.Write(z)
		md.Write(countBytes[:])
		copy(k[i*sm3.Size:], md.Sum(nil))
		ct++
		md.Reset()
	}
	for i := 0; i < len; i++ {
		if k[i] != 0 {
			return k[:len], true
		}
	}
	return k, false
}
func calculateC3(curve elliptic.Curve, x2, y2 *big.Int, msg []byte) []byte {
	md := sm3.New()
	md.Write(toBytes(curve, x2))
	md.Write(msg)
	md.Write(toBytes(curve, y2))
	return md.Sum(nil)
}
func Encrypt(random io.Reader, pub *ecdsa.PublicKey, msg []byte, opts *EncrypterOpts) ([]byte, error) {
	curve := pub.Curve
	msgLen := len(msg)
	if msgLen == 0 {
		return nil, nil
	}
	if opts == nil {
		opts = &defaultEncrypterOpts
	}
	if pub.X.Sign() == 0 && pub.Y.Sign() == 0 {
		return nil, errors.New("SM2: invalid public key")
	}
	for {
		k, err := randFieldElement(curve, random)
		if err != nil {
			return nil, err
		}
		x1, y1 := curve.ScalarBaseMult(k.Bytes())
		c1 := opts.PointMarshalMode.mashal(curve, x1, y1)
		x2, y2 := curve.ScalarMult(pub.X, pub.Y, k.Bytes())
		var kdfCount int = 0
		t, success := kdf(append(toBytes(curve, x2), toBytes(curve, y2)...), msgLen)
		if !success {
			kdfCount++
			if kdfCount > maxRetryLimit {
				return nil, fmt.Errorf("SM2: A5, failed to calculate valid t, tried %v times", kdfCount)
			}
			continue
		}
		c2 := make([]byte, msgLen)
		for i := 0; i < msgLen; i++ {
			c2[i] = msg[i] ^ t[i]
		}
		c3 := calculateC3(curve, x2, y2, msg)
		return append(append(c1, c3...), c2...), nil
	}
}
func GenerateKey(rand io.Reader) (*PrivateKey, error) {
	c := P256()
	k, err := randFieldElement(c, rand)
	if err != nil {
		return nil, err
	}
	priv := new(PrivateKey)
	priv.PublicKey.Curve = c
	priv.D = k
	priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
	return priv, nil
}
func Decrypt(priv *PrivateKey, ciphertext []byte) ([]byte, error) {
	ciphertextLen := len(ciphertext)
	if ciphertextLen <= 1+(priv.Params().BitSize/8)+sm3.Size {
		return nil, errors.New("SM2: invalid ciphertext length")
	}
	curve := priv.Curve
	x1, y1, c3Start, err := bytes2Point(curve, ciphertext)
	if err != nil {
		return nil, err
	}
	x2, y2 := curve.ScalarMult(x1, y1, priv.D.Bytes())
	c2 := ciphertext[c3Start+sm3.Size:]
	msgLen := len(c2)
	t, success := kdf(append(toBytes(curve, x2), toBytes(curve, y2)...), msgLen)
	if !success {
		return nil, errors.New("SM2: invalid cipher text")
	}
	msg := make([]byte, msgLen)
	for i := 0; i < msgLen; i++ {
		msg[i] = c2[i] ^ t[i]
	}
	c3 := ciphertext[c3Start : c3Start+sm3.Size]
	u := calculateC3(curve, x2, y2, msg)
	for i := 0; i < sm3.Size; i++ {
		if c3[i] != u[i] {
			return nil, errors.New("SM2: invalid hash value")
		}
	}
	return msg, nil
}
func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
	orderBits := c.Params().N.BitLen()
	orderBytes := (orderBits + 7) / 8
	if len(hash) > orderBytes {
		hash = hash[:orderBytes]
	}
	ret := new(big.Int).SetBytes(hash)
	excess := len(hash)*8 - orderBits
	if excess > 0 {
		ret.Rsh(ret, uint(excess))
	}
	return ret
}
const (
	aesIV = "IV for ECDSA CTR"
)
var errZeroParam = errors.New("zero parameter")
func fermatInverse(k, N *big.Int) *big.Int {
	two := big.NewInt(2)
	nMinus2 := new(big.Int).Sub(N, two)
	return new(big.Int).Exp(k, nMinus2, N)
}
func Sign(rand io.Reader, priv *ecdsa.PrivateKey, hash []byte) (r, s *big.Int, err error) {
	if !strings.EqualFold(priv.Params().Name, P256().Params().Name) {
		return ecdsa.Sign(rand, priv, hash)
	}
	maybeReadByte(rand)
	entropylen := (priv.Curve.Params().BitSize + 7) / 16
	if entropylen > 32 {
		entropylen = 32
	}
	entropy := make([]byte, entropylen)
	_, err = io.ReadFull(rand, entropy)
	if err != nil {
		return
	}
	md := sha512.New()
	md.Write(priv.D.Bytes())  
	md.Write(entropy)         
	md.Write(hash)            
	key := md.Sum(nil)[:32]   
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, nil, err
	}
	csprng := cipher.StreamReader{
		R: zeroReader,
		S: cipher.NewCTR(block, []byte(aesIV)),
	}
	c := priv.PublicKey.Curve
	N := c.Params().N
	if N.Sign() == 0 {
		return nil, nil, errZeroParam
	}
	var k *big.Int
	e := hashToInt(hash, c)
	for {
		for {
			k, err = randFieldElement(c, csprng)
			if err != nil {
				r = nil
				return
			}
			r, _ = priv.Curve.ScalarBaseMult(k.Bytes())  
			r.Add(r, e)                                  
			r.Mod(r, N)                                  
			if r.Sign() != 0 {
				t := new(big.Int).Add(r, k)
				if t.Cmp(N) != 0 {  
					break
				}
			}
		}
		s = new(big.Int).Mul(priv.D, r)
		s = new(big.Int).Sub(k, s)
		dp1 := new(big.Int).Add(priv.D, one)
		var dp1Inv *big.Int
		if in, ok := priv.Curve.(invertible); ok {
			dp1Inv = in.Inverse(dp1)
		} else {
			dp1Inv = fermatInverse(dp1, N)  
		}
		s.Mul(s, dp1Inv)
		s.Mod(s, N)  
		if s.Sign() != 0 {
			break
		}
	}
	return
}
var defaultUID = []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}
func calculateZA(pub *ecdsa.PublicKey, uid []byte) ([]byte, error) {
	uidLen := len(uid)
	if uidLen >= 0x2000 {
		return nil, errors.New("the uid is too long")
	}
	entla := uint16(uidLen) << 3
	md := sm3.New()
	md.Write([]byte{byte(entla >> 8), byte(entla)})
	if uidLen > 0 {
		md.Write(uid)
	}
	a := new(big.Int).Sub(pub.Params().P, big.NewInt(3))
	md.Write(toBytes(pub.Curve, a))
	md.Write(toBytes(pub.Curve, pub.Params().B))
	md.Write(toBytes(pub.Curve, pub.Params().Gx))
	md.Write(toBytes(pub.Curve, pub.Params().Gy))
	md.Write(toBytes(pub.Curve, pub.X))
	md.Write(toBytes(pub.Curve, pub.Y))
	return md.Sum(nil), nil
}
func SignWithSM2(rand io.Reader, priv *ecdsa.PrivateKey, uid, msg []byte) (r, s *big.Int, err error) {
	if len(uid) == 0 {
		uid = defaultUID
	}
	za, err := calculateZA(&priv.PublicKey, uid)
	if err != nil {
		return nil, nil, err
	}
	md := sm3.New()
	md.Write(za)
	md.Write(msg)
	return Sign(rand, priv, md.Sum(nil))
}
func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte, opts crypto.SignerOpts) ([]byte, error) {
	return priv.Sign(rand, hash, opts)
}
func Verify(pub *ecdsa.PublicKey, hash []byte, r, s *big.Int) bool {
	if strings.EqualFold(pub.Params().Name, P256().Params().Name) {
		c := pub.Curve
		N := c.Params().N
		if r.Sign() <= 0 || s.Sign() <= 0 {
			return false
		}
		if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
			return false
		}
		e := hashToInt(hash, c)
		t := new(big.Int).Add(r, s)
		t.Mod(t, N)
		if t.Sign() == 0 {
			return false
		}
		var x *big.Int
		if opt, ok := c.(combinedMult); ok {
			x, _ = opt.CombinedMult(pub.X, pub.Y, s.Bytes(), t.Bytes())
		} else {
			x1, y1 := c.ScalarBaseMult(s.Bytes())
			x2, y2 := c.ScalarMult(pub.X, pub.Y, t.Bytes())
			x, _ = c.Add(x1, y1, x2, y2)
		}
		x.Add(x, e)
		x.Mod(x, N)
		return x.Cmp(r) == 0
	}
	return ecdsa.Verify(pub, hash, r, s)
}