github.com/dashpay/godash@v0.0.0-20160726055534-e038a21e0e3d/btcec/privkey.go (about)

     1  // Copyright (c) 2013-2016 The btcsuite developers
     2  // Copyright (c) 2016 The Dash developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package btcec
     7  
     8  import (
     9  	"crypto/ecdsa"
    10  	"crypto/elliptic"
    11  	"crypto/rand"
    12  	"math/big"
    13  )
    14  
    15  // PrivateKey wraps an ecdsa.PrivateKey as a convenience mainly for signing
    16  // things with the the private key without having to directly import the ecdsa
    17  // package.
    18  type PrivateKey ecdsa.PrivateKey
    19  
    20  // PrivKeyFromBytes returns a private and public key for `curve' based on the
    21  // private key passed as an argument as a byte slice.
    22  func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*PrivateKey,
    23  	*PublicKey) {
    24  	x, y := curve.ScalarBaseMult(pk)
    25  
    26  	priv := &ecdsa.PrivateKey{
    27  		PublicKey: ecdsa.PublicKey{
    28  			Curve: curve,
    29  			X:     x,
    30  			Y:     y,
    31  		},
    32  		D: new(big.Int).SetBytes(pk),
    33  	}
    34  
    35  	return (*PrivateKey)(priv), (*PublicKey)(&priv.PublicKey)
    36  }
    37  
    38  // NewPrivateKey is a wrapper for ecdsa.GenerateKey that returns a PrivateKey
    39  // instead of the normal ecdsa.PrivateKey.
    40  func NewPrivateKey(curve elliptic.Curve) (*PrivateKey, error) {
    41  	key, err := ecdsa.GenerateKey(curve, rand.Reader)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  	return (*PrivateKey)(key), nil
    46  }
    47  
    48  // PubKey returns the PublicKey corresponding to this private key.
    49  func (p *PrivateKey) PubKey() *PublicKey {
    50  	return (*PublicKey)(&p.PublicKey)
    51  }
    52  
    53  // ToECDSA returns the private key as a *ecdsa.PrivateKey.
    54  func (p *PrivateKey) ToECDSA() *ecdsa.PrivateKey {
    55  	return (*ecdsa.PrivateKey)(p)
    56  }
    57  
    58  // Sign generates an ECDSA signature for the provided hash (which should be the result
    59  // of hashing a larger message) using the private key. Produced signature
    60  // is deterministic (same message and same key yield the same signature) and canonical
    61  // in accordance with RFC6979 and BIP0062.
    62  func (p *PrivateKey) Sign(hash []byte) (*Signature, error) {
    63  	return signRFC6979(p, hash)
    64  }
    65  
    66  // PrivKeyBytesLen defines the length in bytes of a serialized private key.
    67  const PrivKeyBytesLen = 32
    68  
    69  // Serialize returns the private key number d as a big-endian binary-encoded
    70  // number, padded to a length of 32 bytes.
    71  func (p *PrivateKey) Serialize() []byte {
    72  	b := make([]byte, 0, PrivKeyBytesLen)
    73  	return paddedAppend(PrivKeyBytesLen, b, p.ToECDSA().D.Bytes())
    74  }