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.
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
17 type PrivateKey ecdsa.PrivateKey
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,
23 x, y := curve.ScalarBaseMult(pk)
25 priv := &ecdsa.PrivateKey{
26 PublicKey: ecdsa.PublicKey{
31 D: new(big.Int).SetBytes(pk),
34 return (*PrivateKey)(priv), (*PublicKey)(&priv.PublicKey)
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)
44 return (*PrivateKey)(key), nil
47 // PubKey returns the PublicKey corresponding to this private key.
48 func (p *PrivateKey) PubKey() *PublicKey {
49 return (*PublicKey)(&p.PublicKey)
52 // ToECDSA returns the private key as a *ecdsa.PrivateKey.
53 func (p *PrivateKey) ToECDSA() *ecdsa.PrivateKey {
54 return (*ecdsa.PrivateKey)(p)
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)
65 // PrivKeyBytesLen defines the length in bytes of a serialized private key.
66 const PrivKeyBytesLen = 32
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())