keystore_passphrase.go 8.9 KB

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