github.com/hellobchain/newcryptosm@v0.0.0-20221019060107-edb949a317e9/ecdsa/sm2_z.go (about)

     1  package ecdsa
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/binary"
     6  	"github.com/hellobchain/newcryptosm/sm2"
     7  	"github.com/hellobchain/newcryptosm/sm3"
     8  	"math/big"
     9  )
    10  
    11  func big2Bytes(big *big.Int) []byte {
    12  	r := make([]byte, 32)
    13  	bigBytes := big.Bytes()
    14  	copy(r[32-len(bigBytes):], bigBytes)
    15  	return r
    16  }
    17  
    18  func GetZ(key *PublicKey) []byte {
    19  	return GetZWithID(key, []byte("1234567812345678"))
    20  }
    21  
    22  func msgHash(za, msg []byte) *big.Int {
    23  	e := sm3.New()
    24  	e.Write(za)
    25  	e.Write(msg)
    26  	return new(big.Int).SetBytes(e.Sum(nil)[:32])
    27  }
    28  
    29  func GetEWithID(key *PublicKey, msg []byte, uid []byte) *big.Int {
    30  	za := GetZWithID(key, uid)
    31  	return msgHash(za, msg)
    32  }
    33  
    34  func GetE(key *PublicKey, msg []byte) *big.Int {
    35  	za := GetZ(key)
    36  	return msgHash(za, msg)
    37  }
    38  
    39  func GetZWithID(key *PublicKey, id []byte) []byte {
    40  	entl := make([]byte, 2)
    41  	binary.BigEndian.PutUint16(entl, uint16(len(id)*8))
    42  	a := big2Bytes(new(big.Int).Sub(key.Curve.Params().P, new(big.Int).SetInt64(3)))
    43  	b := big2Bytes(key.Curve.Params().B)
    44  	xG := big2Bytes(key.Curve.Params().Gx)
    45  	yG := big2Bytes(key.Curve.Params().Gy)
    46  	x := big2Bytes(key.X)
    47  	y := big2Bytes(key.Y)
    48  	h := sm3.New()
    49  	h.Write(entl)
    50  	h.Write(id)
    51  	h.Write(a)
    52  	h.Write(b)
    53  	h.Write(xG)
    54  	h.Write(yG)
    55  	h.Write(x)
    56  	h.Write(y)
    57  	return h.Sum(nil)
    58  }
    59  
    60  func getZBefore(uidValue []byte) []byte {
    61  	uidValueLen := len(uidValue)
    62  	var entl []byte
    63  	var zHashLen int
    64  	if uidValueLen != 0 {
    65  		zHashLen = 6
    66  		entl = make([]byte, 2)
    67  		binary.BigEndian.PutUint16(entl, uint16(uidValueLen<<3))
    68  	} else {
    69  		zHashLen = 4
    70  		entl = nil
    71  	}
    72  
    73  	a := big2Bytes(new(big.Int).Sub(sm2.SM2().Params().P, new(big.Int).SetInt64(3)))
    74  	b := big2Bytes(sm2.SM2().Params().B)
    75  	xG := big2Bytes(sm2.SM2().Params().Gx)
    76  	yG := big2Bytes(sm2.SM2().Params().Gy)
    77  	zHashed := make([][]byte, zHashLen)
    78  	if zHashLen == 4 {
    79  		zHashed[0] = a
    80  		zHashed[1] = b
    81  		zHashed[2] = xG
    82  		zHashed[3] = yG
    83  	} else {
    84  		zHashed[0] = entl
    85  		zHashed[1] = uidValue
    86  		zHashed[2] = a
    87  		zHashed[3] = b
    88  		zHashed[4] = xG
    89  		zHashed[5] = yG
    90  	}
    91  	return bytes.Join(zHashed, nil)
    92  }