You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

202 lines
5.3 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  1. package keys
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/pkg/errors"
  6. crypto "github.com/tendermint/go-crypto"
  7. "github.com/tendermint/go-crypto/keys/words"
  8. dbm "github.com/tendermint/tmlibs/db"
  9. )
  10. // dbKeybase combines encyption and storage implementation to provide
  11. // a full-featured key manager
  12. type dbKeybase struct {
  13. db dbm.DB
  14. codec words.Codec
  15. }
  16. func New(db dbm.DB, codec words.Codec) dbKeybase {
  17. return dbKeybase{
  18. db: db,
  19. codec: codec,
  20. }
  21. }
  22. var _ Keybase = dbKeybase{}
  23. // Create generates a new key and persists it to storage, encrypted
  24. // using the passphrase. It returns the generated seedphrase
  25. // (mnemonic) and the key Info. It returns an error if it fails to
  26. // generate a key for the given algo type, or if another key is
  27. // already stored under the same name.
  28. func (kb dbKeybase) Create(name, passphrase string, algo CryptoAlgo) (Info, string, error) {
  29. // NOTE: secret is SHA256 hashed by secp256k1 and ed25519.
  30. // 16 byte secret corresponds to 12 BIP39 words.
  31. // XXX: Ledgers use 24 words now - should we ?
  32. secret := crypto.CRandBytes(16)
  33. priv, err := generate(algo, secret)
  34. if err != nil {
  35. return Info{}, "", err
  36. }
  37. // encrypt and persist the key
  38. info := kb.writeKey(priv, name, passphrase)
  39. // we append the type byte to the serialized secret to help with
  40. // recovery
  41. // ie [secret] = [type] + [secret]
  42. typ := cryptoAlgoToByte(algo)
  43. secret = append([]byte{typ}, secret...)
  44. // return the mnemonic phrase
  45. words, err := kb.codec.BytesToWords(secret)
  46. seed := strings.Join(words, " ")
  47. return info, seed, err
  48. }
  49. // Recover converts a seedphrase to a private key and persists it,
  50. // encrypted with the given passphrase. Functions like Create, but
  51. // seedphrase is input not output.
  52. func (kb dbKeybase) Recover(name, passphrase, seedphrase string) (Info, error) {
  53. words := strings.Split(strings.TrimSpace(seedphrase), " ")
  54. secret, err := kb.codec.WordsToBytes(words)
  55. if err != nil {
  56. return Info{}, err
  57. }
  58. // secret is comprised of the actual secret with the type
  59. // appended.
  60. // ie [secret] = [type] + [secret]
  61. typ, secret := secret[0], secret[1:]
  62. algo := byteToCryptoAlgo(typ)
  63. priv, err := generate(algo, secret)
  64. if err != nil {
  65. return Info{}, err
  66. }
  67. // encrypt and persist key.
  68. public := kb.writeKey(priv, name, passphrase)
  69. return public, err
  70. }
  71. // List returns the keys from storage in alphabetical order.
  72. func (kb dbKeybase) List() ([]Info, error) {
  73. var res []Info
  74. iter := kb.db.Iterator(nil, nil)
  75. defer iter.Close()
  76. for ; iter.Valid(); iter.Next() {
  77. // key := iter.Key()
  78. info, err := readInfo(iter.Value())
  79. if err != nil {
  80. return nil, err
  81. }
  82. res = append(res, info)
  83. }
  84. return res, nil
  85. }
  86. // Get returns the public information about one key.
  87. func (kb dbKeybase) Get(name string) (Info, error) {
  88. bs := kb.db.Get(infoKey(name))
  89. return readInfo(bs)
  90. }
  91. // Sign signs the msg with the named key.
  92. // It returns an error if the key doesn't exist or the decryption fails.
  93. func (kb dbKeybase) Sign(name, passphrase string, msg []byte) (sig crypto.Signature, pub crypto.PubKey, err error) {
  94. info, err := kb.Get(name)
  95. if err != nil {
  96. return
  97. }
  98. priv, err := unarmorDecryptPrivKey(info.PrivKeyArmor, passphrase)
  99. if err != nil {
  100. return
  101. }
  102. sig = priv.Sign(msg)
  103. pub = priv.PubKey()
  104. return
  105. }
  106. func (kb dbKeybase) Export(name string) (armor string, err error) {
  107. bz := kb.db.Get(infoKey(name))
  108. if bz == nil {
  109. return "", errors.New("No key to export with name " + name)
  110. }
  111. return armorInfoBytes(bz), nil
  112. }
  113. func (kb dbKeybase) Import(name string, armor string) (err error) {
  114. bz := kb.db.Get(infoKey(name))
  115. if len(bz) > 0 {
  116. return errors.New("Cannot overwrite data for name " + name)
  117. }
  118. infoBytes, err := unarmorInfoBytes(armor)
  119. if err != nil {
  120. return
  121. }
  122. kb.db.Set(infoKey(name), infoBytes)
  123. return nil
  124. }
  125. // Delete removes key forever, but we must present the
  126. // proper passphrase before deleting it (for security).
  127. func (kb dbKeybase) Delete(name, passphrase string) error {
  128. // verify we have the proper password before deleting
  129. info, err := kb.Get(name)
  130. if err != nil {
  131. return err
  132. }
  133. _, err = unarmorDecryptPrivKey(info.PrivKeyArmor, passphrase)
  134. if err != nil {
  135. return err
  136. }
  137. kb.db.DeleteSync(infoKey(name))
  138. return nil
  139. }
  140. // Update changes the passphrase with which an already stored key is
  141. // encrypted.
  142. //
  143. // oldpass must be the current passphrase used for encryption,
  144. // newpass will be the only valid passphrase from this time forward.
  145. func (kb dbKeybase) Update(name, oldpass, newpass string) error {
  146. info, err := kb.Get(name)
  147. if err != nil {
  148. return err
  149. }
  150. key, err := unarmorDecryptPrivKey(info.PrivKeyArmor, oldpass)
  151. if err != nil {
  152. return err
  153. }
  154. kb.writeKey(key, name, newpass)
  155. return nil
  156. }
  157. func (kb dbKeybase) writeKey(priv crypto.PrivKey, name, passphrase string) Info {
  158. // generate the encrypted privkey
  159. privArmor := encryptArmorPrivKey(priv, passphrase)
  160. // make Info
  161. info := newInfo(name, priv.PubKey(), privArmor)
  162. // write them both
  163. kb.db.SetSync(infoKey(name), info.bytes())
  164. return info
  165. }
  166. func generate(algo CryptoAlgo, secret []byte) (crypto.PrivKey, error) {
  167. switch algo {
  168. case AlgoEd25519:
  169. return crypto.GenPrivKeyEd25519FromSecret(secret), nil
  170. case AlgoSecp256k1:
  171. return crypto.GenPrivKeySecp256k1FromSecret(secret), nil
  172. default:
  173. err := errors.Errorf("Cannot generate keys for algorithm: %s", algo)
  174. return nil, err
  175. }
  176. }
  177. func infoKey(name string) []byte {
  178. return []byte(fmt.Sprintf("%s.info", name))
  179. }