github.com/turingchain2020/turingchain@v1.1.21/system/crypto/sm2/utils.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sm2
     6  
     7  import (
     8  	"math/big"
     9  
    10  	"github.com/btcsuite/btcd/btcec"
    11  	"github.com/tjfoc/gmsm/sm2"
    12  )
    13  
    14  const (
    15  	pubkeyUncompressed byte = 0x4 // x coord + y coord
    16  )
    17  
    18  func canonicalizeInt(val *big.Int) []byte {
    19  	b := val.Bytes()
    20  	if len(b) == 0 {
    21  		b = []byte{0x00}
    22  	}
    23  	if b[0]&0x80 != 0 {
    24  		paddedBytes := make([]byte, len(b)+1)
    25  		copy(paddedBytes[1:], b)
    26  		b = paddedBytes
    27  	}
    28  	return b
    29  }
    30  
    31  //Serialize 序列化
    32  func Serialize(r, s *big.Int) []byte {
    33  	rb := canonicalizeInt(r)
    34  	sb := canonicalizeInt(s)
    35  
    36  	length := 6 + len(rb) + len(sb)
    37  	b := make([]byte, length)
    38  
    39  	b[0] = 0x30
    40  	b[1] = byte(length - 2)
    41  	b[2] = 0x02
    42  	b[3] = byte(len(rb))
    43  	offset := copy(b[4:], rb) + 4
    44  	b[offset] = 0x02
    45  	b[offset+1] = byte(len(sb))
    46  	copy(b[offset+2:], sb)
    47  
    48  	return b
    49  }
    50  
    51  //Deserialize 反序列化
    52  func Deserialize(sigStr []byte) (*big.Int, *big.Int, error) {
    53  	sig, err := btcec.ParseDERSignature(sigStr, sm2.P256Sm2())
    54  	if err != nil {
    55  		return nil, nil, err
    56  	}
    57  
    58  	return sig.R, sig.S, nil
    59  }
    60  
    61  //SerializePublicKey 公钥序列化
    62  func SerializePublicKey(p *sm2.PublicKey, isCompress bool) []byte {
    63  	if isCompress {
    64  		return sm2.Compress(p)
    65  	}
    66  
    67  	b := make([]byte, 0, SM2PublicKeyLength)
    68  	b = append(b, pubkeyUncompressed)
    69  	b = paddedAppend(32, b, p.X.Bytes())
    70  	return paddedAppend(32, b, p.Y.Bytes())
    71  }
    72  
    73  //SerializePrivateKey 私钥序列化
    74  func SerializePrivateKey(p *sm2.PrivateKey) []byte {
    75  	b := make([]byte, 0, SM2PrivateKeyLength)
    76  	return paddedAppend(SM2PrivateKeyLength, b, p.D.Bytes())
    77  }
    78  
    79  func paddedAppend(size uint, dst, src []byte) []byte {
    80  	for i := 0; i < int(size)-len(src); i++ {
    81  		dst = append(dst, 0)
    82  	}
    83  	return append(dst, src...)
    84  }