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

     1  // Package secp256k1
     2  //
     3  // @author: xwc1125
     4  package secp256k1
     5  
     6  import (
     7  	"crypto/ecdsa"
     8  	"crypto/elliptic"
     9  	"errors"
    10  
    11  	"github.com/chain5j/chain5j-pkg/crypto/signature/secp256k1/btcecv1"
    12  )
    13  
    14  func MarshalPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
    15  	privateKey := btcecv1.PrivateKey{
    16  		PublicKey: ecdsa.PublicKey{
    17  			Curve: btcecv1.S256(),
    18  			X:     key.X,
    19  			Y:     key.Y,
    20  		},
    21  		D: key.D,
    22  	}
    23  	return privateKey.Serialize(), nil
    24  }
    25  
    26  func UnmarshalPrivateKey(curve elliptic.Curve, data []byte) (*ecdsa.PrivateKey, error) {
    27  	privateKey, _ := btcecv1.PrivKeyFromBytes(btcecv1.S256(), data)
    28  	if privateKey != nil {
    29  		return privateKey.ToECDSA(), nil
    30  	}
    31  	return nil, errors.New("unmarshal private key err")
    32  }
    33  
    34  func MarshalPublicKey(pub *ecdsa.PublicKey) ([]byte, error) {
    35  	publicKey := btcecv1.PublicKey{
    36  		Curve: pub.Curve,
    37  		X:     pub.X,
    38  		Y:     pub.Y,
    39  	}
    40  	return publicKey.SerializeUncompressed(), nil
    41  }
    42  
    43  func UnmarshalPublicKey(curve elliptic.Curve, data []byte) (*ecdsa.PublicKey, error) {
    44  	pubKey, err := btcecv1.ParsePubKey(data, btcecv1.S256())
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	return pubKey.ToECDSA(), nil
    49  }
    50  
    51  // =================x509=================
    52  
    53  func MarshalPrivateKeyX509(key *ecdsa.PrivateKey) ([]byte, error) {
    54  	privateKey := btcecv1.PrivateKey{
    55  		PublicKey: ecdsa.PublicKey{
    56  			Curve: btcecv1.S256(),
    57  			X:     key.X,
    58  			Y:     key.Y,
    59  		},
    60  		D: key.D,
    61  	}
    62  	return privateKey.Serialize(), nil
    63  }
    64  
    65  func UnmarshalPrivateKeyX509(curve elliptic.Curve, data []byte) (*ecdsa.PrivateKey, error) {
    66  	privateKey, _ := btcecv1.PrivKeyFromBytes(btcecv1.S256(), data)
    67  	if privateKey != nil {
    68  		return privateKey.ToECDSA(), nil
    69  	}
    70  	return nil, errors.New("unmarshal private key err")
    71  }
    72  
    73  func MarshalPublicKeyX509(pub *ecdsa.PublicKey) ([]byte, error) {
    74  	return MarshalPublicKey(pub)
    75  }
    76  
    77  func UnmarshalPublicKeyX509(curve elliptic.Curve, data []byte) (*ecdsa.PublicKey, error) {
    78  	return UnmarshalPublicKey(curve, data)
    79  }