package sdk import ( "PaymentCenter/app/third/paymentService/psbc/internal/gmutil/sm2/util" "crypto/elliptic" "encoding/binary" "math/big" ) // ZbSdk 众邦 type ZbSdk struct { BaseSdk } func NewZbSdk() SDK { return &ZbSdk{} } func (zb *ZbSdk) Kdf(c elliptic.Curve, x, y *big.Int, c2 []byte) error { data := elliptic.Marshal(c, x, y) ct := uint32(1) length := len(c2) end := (length + 31) / 32 result := make([]byte, 0) for i := 1; i <= end; i++ { bytes, err := zb.sm3hash(data, zb.uint32ToBytes(ct)) if err != nil { return err } result = append(result, bytes...) ct++ } last, err := zb.sm3hash(data, zb.uint32ToBytes(ct)) if err != nil { return err } if length%32 == 0 { result = append(result, last...) } else { result = append(result, last[:length%32]...) } for i := 0; i < length; i++ { c2[i] ^= result[i] } return nil } func (zb *ZbSdk) CalculateHash(x *big.Int, c2 []byte, y *big.Int) []byte { digest := util.New() digest.Write(zb.bigIntToByte(x)) digest.Write(c2) digest.Write(zb.bigIntToByte(y)) result := digest.Sum(nil)[:32] return result } func (zb *ZbSdk) GetZ(x *big.Int, y *big.Int, uid []byte) []byte { z := util.New() uidLen := len(uid) * 8 z.Write([]byte{byte((uidLen >> 8) & 0xFF)}) z.Write([]byte{byte(uidLen & 0xFF)}) z.Write(uid) sm2P256 := util.NewP256Sm2() z.Write(zb.bigIntToByte(sm2P256.A)) z.Write(zb.bigIntToByte(sm2P256.B)) z.Write(zb.bigIntToByte(sm2P256.Gx)) z.Write(zb.bigIntToByte(sm2P256.Gy)) z.Write(x.Bytes()) z.Write(y.Bytes()) return z.Sum(nil) } func (zb *ZbSdk) bigIntToByte(n *big.Int) []byte { byteArray := n.Bytes() // If the most significant byte's most significant bit is set, // prepend a 0 byte to the slice to avoid being interpreted as a negative number. if (byteArray[0] & 0x80) != 0 { byteArray = append([]byte{0}, byteArray...) } return byteArray } func (zb *ZbSdk) uint32ToBytes(x uint32) []byte { var buf = make([]byte, 4) binary.LittleEndian.PutUint32(buf, x) return buf }