crypto.go 8.7 KB

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