github.com/Finschia/finschia-sdk@v0.48.1/crypto/keys/secp256r1/privkey.go (about)

     1  package secp256r1
     2  
     3  import (
     4  	"github.com/Finschia/finschia-sdk/crypto/keys/internal/ecdsa"
     5  	cryptotypes "github.com/Finschia/finschia-sdk/crypto/types"
     6  )
     7  
     8  // GenPrivKey generates a new secp256r1 private key. It uses operating system randomness.
     9  func GenPrivKey() (*PrivKey, error) {
    10  	key, err := ecdsa.GenPrivKey(secp256r1)
    11  	return &PrivKey{&ecdsaSK{key}}, err
    12  }
    13  
    14  // PubKey implements SDK PrivKey interface.
    15  func (m *PrivKey) PubKey() cryptotypes.PubKey {
    16  	return &PubKey{&ecdsaPK{m.Secret.PubKey()}}
    17  }
    18  
    19  // String implements SDK proto.Message interface.
    20  func (m *PrivKey) String() string {
    21  	return m.Secret.String(name)
    22  }
    23  
    24  // Type returns key type name. Implements SDK PrivKey interface.
    25  func (m *PrivKey) Type() string {
    26  	return name
    27  }
    28  
    29  // Sign hashes and signs the message usign ECDSA. Implements sdk.PrivKey interface.
    30  func (m *PrivKey) Sign(msg []byte) ([]byte, error) {
    31  	return m.Secret.Sign(msg)
    32  }
    33  
    34  // Bytes serialize the private key.
    35  func (m *PrivKey) Bytes() []byte {
    36  	if m == nil {
    37  		return nil
    38  	}
    39  	return m.Secret.Bytes()
    40  }
    41  
    42  // Equals implements SDK PrivKey interface.
    43  func (m *PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool {
    44  	sk2, ok := other.(*PrivKey)
    45  	if !ok {
    46  		return false
    47  	}
    48  	return m.Secret.Equal(&sk2.Secret.PrivateKey)
    49  }
    50  
    51  type ecdsaSK struct {
    52  	ecdsa.PrivKey
    53  }
    54  
    55  // Size implements proto.Marshaler interface
    56  func (sk *ecdsaSK) Size() int {
    57  	if sk == nil {
    58  		return 0
    59  	}
    60  	return fieldSize
    61  }
    62  
    63  // Unmarshal implements proto.Marshaler interface
    64  func (sk *ecdsaSK) Unmarshal(bz []byte) error {
    65  	return sk.PrivKey.Unmarshal(bz, secp256r1, fieldSize)
    66  }