github.com/chain5j/chain5j-pkg@v1.0.7/crypto/signature/gmsm/key.go (about)

     1  // Package gmsm
     2  //
     3  // @author: xwc1125
     4  package gmsm
     5  
     6  import (
     7  	"crypto/ecdsa"
     8  	"errors"
     9  	"math/big"
    10  
    11  	"github.com/tjfoc/gmsm/sm2"
    12  )
    13  
    14  type PrivateKey sm2.PrivateKey
    15  type PublicKey sm2.PublicKey
    16  
    17  var errInvalidPubkey = errors.New("invalid public key")
    18  
    19  // ToECDSA sm2.PrivateKey to ecdsa.PrivateKey
    20  func ToECDSA(p *sm2.PrivateKey) *ecdsa.PrivateKey {
    21  	priv := new(ecdsa.PrivateKey)
    22  	priv.D = p.D
    23  	priv.PublicKey = *ToECDSAPubKey(&p.PublicKey)
    24  	return priv
    25  }
    26  
    27  // FromECDSA ecdsa.PrivateKey to sm2.PrivateKey
    28  func FromECDSA(p *ecdsa.PrivateKey) *sm2.PrivateKey {
    29  	priv := new(sm2.PrivateKey)
    30  	priv.D = p.D
    31  	priv.PublicKey = *FromECDSAPubKey(&p.PublicKey)
    32  	return priv
    33  }
    34  
    35  // ToECDSAPubKey sm2.PublicKey to ecdsa.PublicKey
    36  func ToECDSAPubKey(pub *sm2.PublicKey) *ecdsa.PublicKey {
    37  	return (*ecdsa.PublicKey)(pub)
    38  }
    39  
    40  // FromECDSAPubKey ecdsa.PublicKey to sm2.PublicKey
    41  func FromECDSAPubKey(pub *ecdsa.PublicKey) *sm2.PublicKey {
    42  	return (*sm2.PublicKey)(pub)
    43  }
    44  
    45  // PrivKeyBytesLen 私钥长度
    46  const PrivKeyBytesLen = 32
    47  
    48  // NewPrivateKey new sm2.PrivateKey
    49  func NewPrivateKey(d *big.Int) *sm2.PrivateKey {
    50  	b := make([]byte, 0, PrivKeyBytesLen)
    51  	dB := paddedAppend(PrivKeyBytesLen, b, d.Bytes())
    52  	priv, _ := PrivKeyFromBytes(dB)
    53  	return priv
    54  }
    55  
    56  // PrivKeyFromBytes bytes to sm2.privateKey
    57  func PrivKeyFromBytes(pk []byte) (*sm2.PrivateKey, *sm2.PublicKey) {
    58  	curve := Curve()
    59  	x, y := curve.ScalarBaseMult(pk)
    60  
    61  	priv := &sm2.PrivateKey{
    62  		PublicKey: sm2.PublicKey{
    63  			Curve: curve,
    64  			X:     x,
    65  			Y:     y,
    66  		},
    67  		D: new(big.Int).SetBytes(pk),
    68  	}
    69  
    70  	return priv, &priv.PublicKey
    71  }