key_store_passphrase.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright 2014 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. /*
  17. This key store behaves as KeyStorePlain with the difference that
  18. the private key is encrypted and on disk uses another JSON encoding.
  19. The crypto is documented at https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
  20. */
  21. package accounts
  22. import (
  23. "bytes"
  24. "crypto/aes"
  25. "crypto/sha256"
  26. "encoding/hex"
  27. "encoding/json"
  28. "fmt"
  29. "io/ioutil"
  30. "path/filepath"
  31. "github.com/ethereum/go-ethereum/common"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/crypto/randentropy"
  34. "github.com/pborman/uuid"
  35. "golang.org/x/crypto/pbkdf2"
  36. "golang.org/x/crypto/scrypt"
  37. )
  38. const (
  39. keyHeaderKDF = "scrypt"
  40. // n,r,p = 2^18, 8, 1 uses 256MB memory and approx 1s CPU time on a modern CPU.
  41. StandardScryptN = 1 << 18
  42. StandardScryptP = 1
  43. // n,r,p = 2^12, 8, 6 uses 4MB memory and approx 100ms CPU time on a modern CPU.
  44. LightScryptN = 1 << 12
  45. LightScryptP = 6
  46. scryptR = 8
  47. scryptDKLen = 32
  48. )
  49. type keyStorePassphrase struct {
  50. keysDirPath string
  51. scryptN int
  52. scryptP int
  53. }
  54. func (ks keyStorePassphrase) GetKey(addr common.Address, filename, auth string) (*Key, error) {
  55. // Load the key from the keystore and decrypt its contents
  56. keyjson, err := ioutil.ReadFile(filename)
  57. if err != nil {
  58. return nil, err
  59. }
  60. key, err := DecryptKey(keyjson, auth)
  61. if err != nil {
  62. return nil, err
  63. }
  64. // Make sure we're really operating on the requested key (no swap attacks)
  65. if key.Address != addr {
  66. return nil, fmt.Errorf("key content mismatch: have account %x, want %x", key.Address, addr)
  67. }
  68. return key, nil
  69. }
  70. func (ks keyStorePassphrase) StoreKey(filename string, key *Key, auth string) error {
  71. keyjson, err := EncryptKey(key, auth, ks.scryptN, ks.scryptP)
  72. if err != nil {
  73. return err
  74. }
  75. return writeKeyFile(filename, keyjson)
  76. }
  77. func (ks keyStorePassphrase) JoinPath(filename string) string {
  78. if filepath.IsAbs(filename) {
  79. return filename
  80. } else {
  81. return filepath.Join(ks.keysDirPath, filename)
  82. }
  83. }
  84. // EncryptKey encrypts a key using the specified scrypt parameters into a json
  85. // blob that can be decrypted later on.
  86. func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error) {
  87. authArray := []byte(auth)
  88. salt := randentropy.GetEntropyCSPRNG(32)
  89. derivedKey, err := scrypt.Key(authArray, salt, scryptN, scryptR, scryptP, scryptDKLen)
  90. if err != nil {
  91. return nil, err
  92. }
  93. encryptKey := derivedKey[:16]
  94. keyBytes := crypto.FromECDSA(key.PrivateKey)
  95. iv := randentropy.GetEntropyCSPRNG(aes.BlockSize) // 16
  96. cipherText, err := aesCTRXOR(encryptKey, keyBytes, iv)
  97. if err != nil {
  98. return nil, err
  99. }
  100. mac := crypto.Keccak256(derivedKey[16:32], cipherText)
  101. scryptParamsJSON := make(map[string]interface{}, 5)
  102. scryptParamsJSON["n"] = scryptN
  103. scryptParamsJSON["r"] = scryptR
  104. scryptParamsJSON["p"] = scryptP
  105. scryptParamsJSON["dklen"] = scryptDKLen
  106. scryptParamsJSON["salt"] = hex.EncodeToString(salt)
  107. cipherParamsJSON := cipherparamsJSON{
  108. IV: hex.EncodeToString(iv),
  109. }
  110. cryptoStruct := cryptoJSON{
  111. Cipher: "aes-128-ctr",
  112. CipherText: hex.EncodeToString(cipherText),
  113. CipherParams: cipherParamsJSON,
  114. KDF: "scrypt",
  115. KDFParams: scryptParamsJSON,
  116. MAC: hex.EncodeToString(mac),
  117. }
  118. encryptedKeyJSONV3 := encryptedKeyJSONV3{
  119. hex.EncodeToString(key.Address[:]),
  120. cryptoStruct,
  121. key.Id.String(),
  122. version,
  123. }
  124. return json.Marshal(encryptedKeyJSONV3)
  125. }
  126. // DecryptKey decrypts a key from a json blob, returning the private key itself.
  127. func DecryptKey(keyjson []byte, auth string) (*Key, error) {
  128. // Parse the json into a simple map to fetch the key version
  129. m := make(map[string]interface{})
  130. if err := json.Unmarshal(keyjson, &m); err != nil {
  131. return nil, err
  132. }
  133. // Depending on the version try to parse one way or another
  134. var (
  135. keyBytes, keyId []byte
  136. err error
  137. )
  138. if version, ok := m["version"].(string); ok && version == "1" {
  139. k := new(encryptedKeyJSONV1)
  140. if err := json.Unmarshal(keyjson, k); err != nil {
  141. return nil, err
  142. }
  143. keyBytes, keyId, err = decryptKeyV1(k, auth)
  144. } else {
  145. k := new(encryptedKeyJSONV3)
  146. if err := json.Unmarshal(keyjson, k); err != nil {
  147. return nil, err
  148. }
  149. keyBytes, keyId, err = decryptKeyV3(k, auth)
  150. }
  151. // Handle any decryption errors and return the key
  152. if err != nil {
  153. return nil, err
  154. }
  155. key := crypto.ToECDSA(keyBytes)
  156. return &Key{
  157. Id: uuid.UUID(keyId),
  158. Address: crypto.PubkeyToAddress(key.PublicKey),
  159. PrivateKey: key,
  160. }, nil
  161. }
  162. func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byte, keyId []byte, err error) {
  163. if keyProtected.Version != version {
  164. return nil, nil, fmt.Errorf("Version not supported: %v", keyProtected.Version)
  165. }
  166. if keyProtected.Crypto.Cipher != "aes-128-ctr" {
  167. return nil, nil, fmt.Errorf("Cipher not supported: %v", keyProtected.Crypto.Cipher)
  168. }
  169. keyId = uuid.Parse(keyProtected.Id)
  170. mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
  171. if err != nil {
  172. return nil, nil, err
  173. }
  174. iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
  175. if err != nil {
  176. return nil, nil, err
  177. }
  178. cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
  179. if err != nil {
  180. return nil, nil, err
  181. }
  182. derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
  183. if err != nil {
  184. return nil, nil, err
  185. }
  186. calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
  187. if !bytes.Equal(calculatedMAC, mac) {
  188. return nil, nil, ErrDecrypt
  189. }
  190. plainText, err := aesCTRXOR(derivedKey[:16], cipherText, iv)
  191. if err != nil {
  192. return nil, nil, err
  193. }
  194. return plainText, keyId, err
  195. }
  196. func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
  197. keyId = uuid.Parse(keyProtected.Id)
  198. mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
  199. if err != nil {
  200. return nil, nil, err
  201. }
  202. iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
  203. if err != nil {
  204. return nil, nil, err
  205. }
  206. cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
  207. if err != nil {
  208. return nil, nil, err
  209. }
  210. derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
  211. if err != nil {
  212. return nil, nil, err
  213. }
  214. calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
  215. if !bytes.Equal(calculatedMAC, mac) {
  216. return nil, nil, ErrDecrypt
  217. }
  218. plainText, err := aesCBCDecrypt(crypto.Keccak256(derivedKey[:16])[:16], cipherText, iv)
  219. if err != nil {
  220. return nil, nil, err
  221. }
  222. return plainText, keyId, err
  223. }
  224. func getKDFKey(cryptoJSON cryptoJSON, auth string) ([]byte, error) {
  225. authArray := []byte(auth)
  226. salt, err := hex.DecodeString(cryptoJSON.KDFParams["salt"].(string))
  227. if err != nil {
  228. return nil, err
  229. }
  230. dkLen := ensureInt(cryptoJSON.KDFParams["dklen"])
  231. if cryptoJSON.KDF == "scrypt" {
  232. n := ensureInt(cryptoJSON.KDFParams["n"])
  233. r := ensureInt(cryptoJSON.KDFParams["r"])
  234. p := ensureInt(cryptoJSON.KDFParams["p"])
  235. return scrypt.Key(authArray, salt, n, r, p, dkLen)
  236. } else if cryptoJSON.KDF == "pbkdf2" {
  237. c := ensureInt(cryptoJSON.KDFParams["c"])
  238. prf := cryptoJSON.KDFParams["prf"].(string)
  239. if prf != "hmac-sha256" {
  240. return nil, fmt.Errorf("Unsupported PBKDF2 PRF: %s", prf)
  241. }
  242. key := pbkdf2.Key(authArray, salt, c, dkLen, sha256.New)
  243. return key, nil
  244. }
  245. return nil, fmt.Errorf("Unsupported KDF: %s", cryptoJSON.KDF)
  246. }
  247. // TODO: can we do without this when unmarshalling dynamic JSON?
  248. // why do integers in KDF params end up as float64 and not int after
  249. // unmarshal?
  250. func ensureInt(x interface{}) int {
  251. res, ok := x.(int)
  252. if !ok {
  253. res = int(x.(float64))
  254. }
  255. return res
  256. }