aes_gcm_storage.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package storage
  17. import (
  18. "crypto/aes"
  19. "crypto/cipher"
  20. "crypto/rand"
  21. "encoding/json"
  22. "io"
  23. "io/ioutil"
  24. "os"
  25. "github.com/ethereum/go-ethereum/log"
  26. )
  27. type storedCredential struct {
  28. // The iv
  29. Iv []byte `json:"iv"`
  30. // The ciphertext
  31. CipherText []byte `json:"c"`
  32. }
  33. // AESEncryptedStorage is a storage type which is backed by a json-file. The json-file contains
  34. // key-value mappings, where the keys are _not_ encrypted, only the values are.
  35. type AESEncryptedStorage struct {
  36. // File to read/write credentials
  37. filename string
  38. // Key stored in base64
  39. key []byte
  40. }
  41. // NewAESEncryptedStorage creates a new encrypted storage backed by the given file/key
  42. func NewAESEncryptedStorage(filename string, key []byte) *AESEncryptedStorage {
  43. return &AESEncryptedStorage{
  44. filename: filename,
  45. key: key,
  46. }
  47. }
  48. // Put stores a value by key. 0-length keys results in noop.
  49. func (s *AESEncryptedStorage) Put(key, value string) {
  50. if len(key) == 0 {
  51. return
  52. }
  53. data, err := s.readEncryptedStorage()
  54. if err != nil {
  55. log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
  56. return
  57. }
  58. ciphertext, iv, err := encrypt(s.key, []byte(value), []byte(key))
  59. if err != nil {
  60. log.Warn("Failed to encrypt entry", "err", err)
  61. return
  62. }
  63. encrypted := storedCredential{Iv: iv, CipherText: ciphertext}
  64. data[key] = encrypted
  65. if err = s.writeEncryptedStorage(data); err != nil {
  66. log.Warn("Failed to write entry", "err", err)
  67. }
  68. }
  69. // Get returns the previously stored value, or an error if it does not exist or
  70. // key is of 0-length.
  71. func (s *AESEncryptedStorage) Get(key string) (string, error) {
  72. if len(key) == 0 {
  73. return "", ErrZeroKey
  74. }
  75. data, err := s.readEncryptedStorage()
  76. if err != nil {
  77. log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
  78. return "", err
  79. }
  80. encrypted, exist := data[key]
  81. if !exist {
  82. log.Warn("Key does not exist", "key", key)
  83. return "", ErrNotFound
  84. }
  85. entry, err := decrypt(s.key, encrypted.Iv, encrypted.CipherText, []byte(key))
  86. if err != nil {
  87. log.Warn("Failed to decrypt key", "key", key)
  88. return "", err
  89. }
  90. return string(entry), nil
  91. }
  92. // Del removes a key-value pair. If the key doesn't exist, the method is a noop.
  93. func (s *AESEncryptedStorage) Del(key string) {
  94. data, err := s.readEncryptedStorage()
  95. if err != nil {
  96. log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
  97. return
  98. }
  99. delete(data, key)
  100. if err = s.writeEncryptedStorage(data); err != nil {
  101. log.Warn("Failed to write entry", "err", err)
  102. }
  103. }
  104. // readEncryptedStorage reads the file with encrypted creds
  105. func (s *AESEncryptedStorage) readEncryptedStorage() (map[string]storedCredential, error) {
  106. creds := make(map[string]storedCredential)
  107. raw, err := ioutil.ReadFile(s.filename)
  108. if err != nil {
  109. if os.IsNotExist(err) {
  110. // Doesn't exist yet
  111. return creds, nil
  112. }
  113. log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
  114. }
  115. if err = json.Unmarshal(raw, &creds); err != nil {
  116. log.Warn("Failed to unmarshal encrypted storage", "err", err, "file", s.filename)
  117. return nil, err
  118. }
  119. return creds, nil
  120. }
  121. // writeEncryptedStorage write the file with encrypted creds
  122. func (s *AESEncryptedStorage) writeEncryptedStorage(creds map[string]storedCredential) error {
  123. raw, err := json.Marshal(creds)
  124. if err != nil {
  125. return err
  126. }
  127. if err = ioutil.WriteFile(s.filename, raw, 0600); err != nil {
  128. return err
  129. }
  130. return nil
  131. }
  132. // encrypt encrypts plaintext with the given key, with additional data
  133. // The 'additionalData' is used to place the (plaintext) KV-store key into the V,
  134. // to prevent the possibility to alter a K, or swap two entries in the KV store with eachother.
  135. func encrypt(key []byte, plaintext []byte, additionalData []byte) ([]byte, []byte, error) {
  136. block, err := aes.NewCipher(key)
  137. if err != nil {
  138. return nil, nil, err
  139. }
  140. aesgcm, err := cipher.NewGCM(block)
  141. if err != nil {
  142. return nil, nil, err
  143. }
  144. nonce := make([]byte, aesgcm.NonceSize())
  145. if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
  146. return nil, nil, err
  147. }
  148. ciphertext := aesgcm.Seal(nil, nonce, plaintext, additionalData)
  149. return ciphertext, nonce, nil
  150. }
  151. func decrypt(key []byte, nonce []byte, ciphertext []byte, additionalData []byte) ([]byte, error) {
  152. block, err := aes.NewCipher(key)
  153. if err != nil {
  154. return nil, err
  155. }
  156. aesgcm, err := cipher.NewGCM(block)
  157. if err != nil {
  158. return nil, err
  159. }
  160. plaintext, err := aesgcm.Open(nil, nonce, ciphertext, additionalData)
  161. if err != nil {
  162. return nil, err
  163. }
  164. return plaintext, nil
  165. }