key_store_passphrase.go 8.6 KB

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