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

     1  // Package signature
     2  //
     3  // @author: xwc1125
     4  package signature
     5  
     6  import (
     7  	"crypto/ecdsa"
     8  	"errors"
     9  )
    10  
    11  // MarshalPubkeyWithECDSA marshal ecdsa publicKey to bytes
    12  func MarshalPubkeyWithECDSA(pub *ecdsa.PublicKey) ([]byte, error) {
    13  	if pub == nil || pub.X == nil || pub.Y == nil {
    14  		return nil, errors.New("pub is nil")
    15  	}
    16  	if ecdsa, err := GetECDSA(CurveName(pub.Curve)); err != nil {
    17  		return nil, err
    18  	} else {
    19  		return ecdsa.MarshalPublicKey(pub)
    20  	}
    21  }
    22  
    23  // UnmarshalPubkeyWithECDSA converts bytes to a  public key.
    24  func UnmarshalPubkeyWithECDSA(curveName string, pub []byte) (*ecdsa.PublicKey, error) {
    25  	if len(pub) == 0 {
    26  		return nil, errors.New("pub bytes is empty")
    27  	}
    28  
    29  	if ecdsa, err := GetECDSA(curveName); err != nil {
    30  		return nil, err
    31  	} else {
    32  		return ecdsa.UnmarshalPublicKey(CurveType(curveName), pub)
    33  	}
    34  }
    35  
    36  func MarshalPubkeyWithECDSAX509(pub *ecdsa.PublicKey) ([]byte, error) {
    37  	if pub == nil || pub.X == nil || pub.Y == nil {
    38  		return nil, errors.New("pub is nil")
    39  	}
    40  	if ecdsa, err := GetECDSA(CurveName(pub.Curve)); err != nil {
    41  		return nil, err
    42  	} else {
    43  		return ecdsa.MarshalPublicKeyX509(pub)
    44  	}
    45  }
    46  
    47  func MarshalPrvkeyWithECDSA(prv *ecdsa.PrivateKey) ([]byte, error) {
    48  	if prv == nil {
    49  		return nil, errors.New("ecdsa private key is empty")
    50  	}
    51  
    52  	if ecdsa, err := GetECDSA(CurveName(prv.Curve)); err != nil {
    53  		return nil, err
    54  	} else {
    55  		return ecdsa.MarshalPrivateKey(prv)
    56  	}
    57  }
    58  
    59  func UnMarshalPrvkeyWithECDSA(curveName string, key []byte) (*ecdsa.PrivateKey, error) {
    60  	if key == nil {
    61  		return nil, errors.New("private key is empty")
    62  	}
    63  
    64  	if ecdsa, err := GetECDSA(curveName); err != nil {
    65  		return nil, err
    66  	} else {
    67  		return ecdsa.UnmarshalPrivateKey(CurveType(curveName), key)
    68  	}
    69  }
    70  
    71  func MarshalPrvkeyWithECDSAX509(prv *ecdsa.PrivateKey) ([]byte, error) {
    72  	if prv == nil {
    73  		return nil, errors.New("ecdsa private key is empty")
    74  	}
    75  	if ecdsa, err := GetECDSA(CurveName(prv.Curve)); err != nil {
    76  		return nil, err
    77  	} else {
    78  		return ecdsa.MarshalPrivateKeyX509(prv)
    79  	}
    80  }