key_store_passphrase.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. keyBytes0 := crypto.FromECDSA(key.PrivateKey)
  95. keyBytes := common.LeftPadBytes(keyBytes0, 32)
  96. iv := randentropy.GetEntropyCSPRNG(aes.BlockSize) // 16
  97. cipherText, err := aesCTRXOR(encryptKey, keyBytes, iv)
  98. if err != nil {
  99. return nil, err
  100. }
  101. mac := crypto.Keccak256(derivedKey[16:32], cipherText)
  102. scryptParamsJSON := make(map[string]interface{}, 5)
  103. scryptParamsJSON["n"] = scryptN
  104. scryptParamsJSON["r"] = scryptR
  105. scryptParamsJSON["p"] = scryptP
  106. scryptParamsJSON["dklen"] = scryptDKLen
  107. scryptParamsJSON["salt"] = hex.EncodeToString(salt)
  108. cipherParamsJSON := cipherparamsJSON{
  109. IV: hex.EncodeToString(iv),
  110. }
  111. cryptoStruct := cryptoJSON{
  112. Cipher: "aes-128-ctr",
  113. CipherText: hex.EncodeToString(cipherText),
  114. CipherParams: cipherParamsJSON,
  115. KDF: "scrypt",
  116. KDFParams: scryptParamsJSON,
  117. MAC: hex.EncodeToString(mac),
  118. }
  119. encryptedKeyJSONV3 := encryptedKeyJSONV3{
  120. hex.EncodeToString(key.Address[:]),
  121. cryptoStruct,
  122. key.Id.String(),
  123. version,
  124. }
  125. return json.Marshal(encryptedKeyJSONV3)
  126. }
  127. // DecryptKey decrypts a key from a json blob, returning the private key itself.
  128. func DecryptKey(keyjson []byte, auth string) (*Key, error) {
  129. // Parse the json into a simple map to fetch the key version
  130. m := make(map[string]interface{})
  131. if err := json.Unmarshal(keyjson, &m); err != nil {
  132. return nil, err
  133. }
  134. // Depending on the version try to parse one way or another
  135. var (
  136. keyBytes, keyId []byte
  137. err error
  138. )
  139. if version, ok := m["version"].(string); ok && version == "1" {
  140. k := new(encryptedKeyJSONV1)
  141. if err := json.Unmarshal(keyjson, k); err != nil {
  142. return nil, err
  143. }
  144. keyBytes, keyId, err = decryptKeyV1(k, auth)
  145. } else {
  146. k := new(encryptedKeyJSONV3)
  147. if err := json.Unmarshal(keyjson, k); err != nil {
  148. return nil, err
  149. }
  150. keyBytes, keyId, err = decryptKeyV3(k, auth)
  151. }
  152. // Handle any decryption errors and return the key
  153. if err != nil {
  154. return nil, err
  155. }
  156. key := crypto.ToECDSA(keyBytes)
  157. return &Key{
  158. Id: uuid.UUID(keyId),
  159. Address: crypto.PubkeyToAddress(key.PublicKey),
  160. PrivateKey: key,
  161. }, nil
  162. }
  163. func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byte, keyId []byte, err error) {
  164. if keyProtected.Version != version {
  165. return nil, nil, fmt.Errorf("Version not supported: %v", keyProtected.Version)
  166. }
  167. if keyProtected.Crypto.Cipher != "aes-128-ctr" {
  168. return nil, nil, fmt.Errorf("Cipher not supported: %v", keyProtected.Crypto.Cipher)
  169. }
  170. keyId = uuid.Parse(keyProtected.Id)
  171. mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
  172. if err != nil {
  173. return nil, nil, err
  174. }
  175. iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
  176. if err != nil {
  177. return nil, nil, err
  178. }
  179. cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
  180. if err != nil {
  181. return nil, nil, err
  182. }
  183. derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
  184. if err != nil {
  185. return nil, nil, err
  186. }
  187. calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
  188. if !bytes.Equal(calculatedMAC, mac) {
  189. return nil, nil, ErrDecrypt
  190. }
  191. plainText, err := aesCTRXOR(derivedKey[:16], cipherText, iv)
  192. if err != nil {
  193. return nil, nil, err
  194. }
  195. return plainText, keyId, err
  196. }
  197. func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
  198. keyId = uuid.Parse(keyProtected.Id)
  199. mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
  200. if err != nil {
  201. return nil, nil, err
  202. }
  203. iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
  204. if err != nil {
  205. return nil, nil, err
  206. }
  207. cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
  208. if err != nil {
  209. return nil, nil, err
  210. }
  211. derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
  212. if err != nil {
  213. return nil, nil, err
  214. }
  215. calculatedMAC := crypto.Keccak256(derivedKey[16:32], cipherText)
  216. if !bytes.Equal(calculatedMAC, mac) {
  217. return nil, nil, ErrDecrypt
  218. }
  219. plainText, err := aesCBCDecrypt(crypto.Keccak256(derivedKey[:16])[:16], cipherText, iv)
  220. if err != nil {
  221. return nil, nil, err
  222. }
  223. return plainText, keyId, err
  224. }
  225. func getKDFKey(cryptoJSON cryptoJSON, auth string) ([]byte, error) {
  226. authArray := []byte(auth)
  227. salt, err := hex.DecodeString(cryptoJSON.KDFParams["salt"].(string))
  228. if err != nil {
  229. return nil, err
  230. }
  231. dkLen := ensureInt(cryptoJSON.KDFParams["dklen"])
  232. if cryptoJSON.KDF == "scrypt" {
  233. n := ensureInt(cryptoJSON.KDFParams["n"])
  234. r := ensureInt(cryptoJSON.KDFParams["r"])
  235. p := ensureInt(cryptoJSON.KDFParams["p"])
  236. return scrypt.Key(authArray, salt, n, r, p, dkLen)
  237. } else if cryptoJSON.KDF == "pbkdf2" {
  238. c := ensureInt(cryptoJSON.KDFParams["c"])
  239. prf := cryptoJSON.KDFParams["prf"].(string)
  240. if prf != "hmac-sha256" {
  241. return nil, fmt.Errorf("Unsupported PBKDF2 PRF: %s", prf)
  242. }
  243. key := pbkdf2.Key(authArray, salt, c, dkLen, sha256.New)
  244. return key, nil
  245. }
  246. return nil, fmt.Errorf("Unsupported KDF: %s", cryptoJSON.KDF)
  247. }
  248. // TODO: can we do without this when unmarshalling dynamic JSON?
  249. // why do integers in KDF params end up as float64 and not int after
  250. // unmarshal?
  251. func ensureInt(x interface{}) int {
  252. res, ok := x.(int)
  253. if !ok {
  254. res = int(x.(float64))
  255. }
  256. return res
  257. }