crypto.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. package crypto
  17. import (
  18. "crypto/aes"
  19. "crypto/cipher"
  20. "crypto/ecdsa"
  21. "crypto/elliptic"
  22. "crypto/rand"
  23. "crypto/sha256"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "math/big"
  28. "os"
  29. "encoding/hex"
  30. "encoding/json"
  31. "errors"
  32. "github.com/ethereum/go-ethereum/common"
  33. "github.com/ethereum/go-ethereum/crypto/ecies"
  34. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  35. "github.com/ethereum/go-ethereum/crypto/sha3"
  36. "github.com/ethereum/go-ethereum/rlp"
  37. "github.com/pborman/uuid"
  38. "golang.org/x/crypto/pbkdf2"
  39. "golang.org/x/crypto/ripemd160"
  40. )
  41. func Keccak256(data ...[]byte) []byte {
  42. d := sha3.NewKeccak256()
  43. for _, b := range data {
  44. d.Write(b)
  45. }
  46. return d.Sum(nil)
  47. }
  48. func Keccak256Hash(data ...[]byte) (h common.Hash) {
  49. d := sha3.NewKeccak256()
  50. for _, b := range data {
  51. d.Write(b)
  52. }
  53. d.Sum(h[:0])
  54. return h
  55. }
  56. // Creates an ethereum address given the bytes and the nonce
  57. func CreateAddress(b common.Address, nonce uint64) common.Address {
  58. data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
  59. return common.BytesToAddress(Keccak256(data)[12:])
  60. //return Sha3(common.NewValue([]interface{}{b, nonce}).Encode())[12:]
  61. }
  62. func Sha256(data []byte) []byte {
  63. hash := sha256.Sum256(data)
  64. return hash[:]
  65. }
  66. func Ripemd160(data []byte) []byte {
  67. ripemd := ripemd160.New()
  68. ripemd.Write(data)
  69. return ripemd.Sum(nil)
  70. }
  71. func Ecrecover(hash, sig []byte) ([]byte, error) {
  72. return secp256k1.RecoverPubkey(hash, sig)
  73. }
  74. // New methods using proper ecdsa keys from the stdlib
  75. func ToECDSA(prv []byte) *ecdsa.PrivateKey {
  76. if len(prv) == 0 {
  77. return nil
  78. }
  79. priv := new(ecdsa.PrivateKey)
  80. priv.PublicKey.Curve = secp256k1.S256()
  81. priv.D = common.BigD(prv)
  82. priv.PublicKey.X, priv.PublicKey.Y = secp256k1.S256().ScalarBaseMult(prv)
  83. return priv
  84. }
  85. func FromECDSA(prv *ecdsa.PrivateKey) []byte {
  86. if prv == nil {
  87. return nil
  88. }
  89. return prv.D.Bytes()
  90. }
  91. func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
  92. if len(pub) == 0 {
  93. return nil
  94. }
  95. x, y := elliptic.Unmarshal(secp256k1.S256(), pub)
  96. return &ecdsa.PublicKey{secp256k1.S256(), x, y}
  97. }
  98. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  99. if pub == nil || pub.X == nil || pub.Y == nil {
  100. return nil
  101. }
  102. return elliptic.Marshal(secp256k1.S256(), pub.X, pub.Y)
  103. }
  104. // HexToECDSA parses a secp256k1 private key.
  105. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  106. b, err := hex.DecodeString(hexkey)
  107. if err != nil {
  108. return nil, errors.New("invalid hex string")
  109. }
  110. if len(b) != 32 {
  111. return nil, errors.New("invalid length, need 256 bits")
  112. }
  113. return ToECDSA(b), nil
  114. }
  115. // LoadECDSA loads a secp256k1 private key from the given file.
  116. // The key data is expected to be hex-encoded.
  117. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  118. buf := make([]byte, 64)
  119. fd, err := os.Open(file)
  120. if err != nil {
  121. return nil, err
  122. }
  123. defer fd.Close()
  124. if _, err := io.ReadFull(fd, buf); err != nil {
  125. return nil, err
  126. }
  127. key, err := hex.DecodeString(string(buf))
  128. if err != nil {
  129. return nil, err
  130. }
  131. return ToECDSA(key), nil
  132. }
  133. // SaveECDSA saves a secp256k1 private key to the given file with
  134. // restrictive permissions. The key data is saved hex-encoded.
  135. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  136. k := hex.EncodeToString(FromECDSA(key))
  137. return ioutil.WriteFile(file, []byte(k), 0600)
  138. }
  139. func GenerateKey() (*ecdsa.PrivateKey, error) {
  140. return ecdsa.GenerateKey(secp256k1.S256(), rand.Reader)
  141. }
  142. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  143. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  144. return false
  145. }
  146. vint := uint32(v)
  147. // reject upper range of s values (ECDSA malleability)
  148. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  149. if homestead && s.Cmp(secp256k1.HalfN) > 0 {
  150. return false
  151. }
  152. // Frontier: allow s to be in full N range
  153. if s.Cmp(secp256k1.N) >= 0 {
  154. return false
  155. }
  156. if r.Cmp(secp256k1.N) < 0 && (vint == 27 || vint == 28) {
  157. return true
  158. } else {
  159. return false
  160. }
  161. }
  162. func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
  163. s, err := Ecrecover(hash, sig)
  164. if err != nil {
  165. return nil, err
  166. }
  167. x, y := elliptic.Unmarshal(secp256k1.S256(), s)
  168. return &ecdsa.PublicKey{secp256k1.S256(), x, y}, nil
  169. }
  170. func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
  171. if len(hash) != 32 {
  172. return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
  173. }
  174. seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)
  175. defer zeroBytes(seckey)
  176. sig, err = secp256k1.Sign(hash, seckey)
  177. return
  178. }
  179. func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) {
  180. return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil)
  181. }
  182. func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) {
  183. key := ecies.ImportECDSA(prv)
  184. return key.Decrypt(rand.Reader, ct, nil, nil)
  185. }
  186. // Used only by block tests.
  187. func ImportBlockTestKey(privKeyBytes []byte) error {
  188. ks := NewKeyStorePassphrase(common.DefaultDataDir()+"/keystore", LightScryptN, LightScryptP)
  189. ecKey := ToECDSA(privKeyBytes)
  190. key := &Key{
  191. Id: uuid.NewRandom(),
  192. Address: PubkeyToAddress(ecKey.PublicKey),
  193. PrivateKey: ecKey,
  194. }
  195. err := ks.StoreKey(key, "")
  196. return err
  197. }
  198. // creates a Key and stores that in the given KeyStore by decrypting a presale key JSON
  199. func ImportPreSaleKey(keyStore KeyStore, keyJSON []byte, password string) (*Key, error) {
  200. key, err := decryptPreSaleKey(keyJSON, password)
  201. if err != nil {
  202. return nil, err
  203. }
  204. key.Id = uuid.NewRandom()
  205. err = keyStore.StoreKey(key, password)
  206. return key, err
  207. }
  208. func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error) {
  209. preSaleKeyStruct := struct {
  210. EncSeed string
  211. EthAddr string
  212. Email string
  213. BtcAddr string
  214. }{}
  215. err = json.Unmarshal(fileContent, &preSaleKeyStruct)
  216. if err != nil {
  217. return nil, err
  218. }
  219. encSeedBytes, err := hex.DecodeString(preSaleKeyStruct.EncSeed)
  220. iv := encSeedBytes[:16]
  221. cipherText := encSeedBytes[16:]
  222. /*
  223. See https://github.com/ethereum/pyethsaletool
  224. pyethsaletool generates the encryption key from password by
  225. 2000 rounds of PBKDF2 with HMAC-SHA-256 using password as salt (:().
  226. 16 byte key length within PBKDF2 and resulting key is used as AES key
  227. */
  228. passBytes := []byte(password)
  229. derivedKey := pbkdf2.Key(passBytes, passBytes, 2000, 16, sha256.New)
  230. plainText, err := aesCBCDecrypt(derivedKey, cipherText, iv)
  231. if err != nil {
  232. return nil, err
  233. }
  234. ethPriv := Keccak256(plainText)
  235. ecKey := ToECDSA(ethPriv)
  236. key = &Key{
  237. Id: nil,
  238. Address: PubkeyToAddress(ecKey.PublicKey),
  239. PrivateKey: ecKey,
  240. }
  241. derivedAddr := hex.EncodeToString(key.Address.Bytes()) // needed because .Hex() gives leading "0x"
  242. expectedAddr := preSaleKeyStruct.EthAddr
  243. if derivedAddr != expectedAddr {
  244. err = fmt.Errorf("decrypted addr '%s' not equal to expected addr '%s'", derivedAddr, expectedAddr)
  245. }
  246. return key, err
  247. }
  248. // AES-128 is selected due to size of encryptKey
  249. func aesCTRXOR(key, inText, iv []byte) ([]byte, error) {
  250. aesBlock, err := aes.NewCipher(key)
  251. if err != nil {
  252. return nil, err
  253. }
  254. stream := cipher.NewCTR(aesBlock, iv)
  255. outText := make([]byte, len(inText))
  256. stream.XORKeyStream(outText, inText)
  257. return outText, err
  258. }
  259. func aesCBCDecrypt(key, cipherText, iv []byte) ([]byte, error) {
  260. aesBlock, err := aes.NewCipher(key)
  261. if err != nil {
  262. return nil, err
  263. }
  264. decrypter := cipher.NewCBCDecrypter(aesBlock, iv)
  265. paddedPlaintext := make([]byte, len(cipherText))
  266. decrypter.CryptBlocks(paddedPlaintext, cipherText)
  267. plaintext := PKCS7Unpad(paddedPlaintext)
  268. if plaintext == nil {
  269. err = errors.New("Decryption failed: PKCS7Unpad failed after AES decryption")
  270. }
  271. return plaintext, err
  272. }
  273. // From https://leanpub.com/gocrypto/read#leanpub-auto-block-cipher-modes
  274. func PKCS7Unpad(in []byte) []byte {
  275. if len(in) == 0 {
  276. return nil
  277. }
  278. padding := in[len(in)-1]
  279. if int(padding) > len(in) || padding > aes.BlockSize {
  280. return nil
  281. } else if padding == 0 {
  282. return nil
  283. }
  284. for i := len(in) - 1; i > len(in)-int(padding)-1; i-- {
  285. if in[i] != padding {
  286. return nil
  287. }
  288. }
  289. return in[:len(in)-int(padding)]
  290. }
  291. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  292. pubBytes := FromECDSAPub(&p)
  293. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  294. }
  295. func zeroBytes(bytes []byte) {
  296. for i := range bytes {
  297. bytes[i] = 0
  298. }
  299. }