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.

54 lines
1.4 KiB

  1. package cryptostore
  2. import (
  3. "github.com/pkg/errors"
  4. crypto "github.com/tendermint/go-crypto"
  5. )
  6. var (
  7. // SecretBox uses the algorithm from NaCL to store secrets securely
  8. SecretBox Encoder = secretbox{}
  9. // Noop doesn't do any encryption, should only be used in test code
  10. Noop Encoder = noop{}
  11. )
  12. // Encoder is used to encrypt any key with a passphrase for storage.
  13. //
  14. // This should use a well-designed symetric encryption algorithm
  15. type Encoder interface {
  16. Encrypt(key crypto.PrivKey, pass string) ([]byte, error)
  17. Decrypt(data []byte, pass string) (crypto.PrivKey, error)
  18. }
  19. func secret(passphrase string) []byte {
  20. // TODO: Sha256(Bcrypt(passphrase))
  21. return crypto.Sha256([]byte(passphrase))
  22. }
  23. type secretbox struct{}
  24. func (e secretbox) Encrypt(key crypto.PrivKey, pass string) ([]byte, error) {
  25. s := secret(pass)
  26. cipher := crypto.EncryptSymmetric(key.Bytes(), s)
  27. return cipher, nil
  28. }
  29. func (e secretbox) Decrypt(data []byte, pass string) (crypto.PrivKey, error) {
  30. s := secret(pass)
  31. private, err := crypto.DecryptSymmetric(data, s)
  32. if err != nil {
  33. return crypto.PrivKey{}, errors.Wrap(err, "Invalid Passphrase")
  34. }
  35. key, err := crypto.PrivKeyFromBytes(private)
  36. return key, errors.Wrap(err, "Invalid Passphrase")
  37. }
  38. type noop struct{}
  39. func (n noop) Encrypt(key crypto.PrivKey, pass string) ([]byte, error) {
  40. return key.Bytes(), nil
  41. }
  42. func (n noop) Decrypt(data []byte, pass string) (crypto.PrivKey, error) {
  43. return crypto.PrivKeyFromBytes(data)
  44. }