OSDN Git Service

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