privkey.go raw

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