privkey.go 2.2 KB

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