crypto.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. 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. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  150. return false
  151. }
  152. vint := uint32(v)
  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. seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)
  172. defer zeroBytes(seckey)
  173. sig, err = secp256k1.Sign(hash, seckey)
  174. return
  175. }
  176. func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) {
  177. return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil)
  178. }
  179. func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) {
  180. key := ecies.ImportECDSA(prv)
  181. return key.Decrypt(rand.Reader, ct, nil, nil)
  182. }
  183. // Used only by block tests.
  184. func ImportBlockTestKey(privKeyBytes []byte) error {
  185. ks := NewKeyStorePassphrase(common.DefaultDataDir() + "/keystore")
  186. ecKey := ToECDSA(privKeyBytes)
  187. key := &Key{
  188. Id: uuid.NewRandom(),
  189. Address: PubkeyToAddress(ecKey.PublicKey),
  190. PrivateKey: ecKey,
  191. }
  192. err := ks.StoreKey(key, "")
  193. return err
  194. }
  195. // creates a Key and stores that in the given KeyStore by decrypting a presale key JSON
  196. func ImportPreSaleKey(keyStore KeyStore, keyJSON []byte, password string) (*Key, error) {
  197. key, err := decryptPreSaleKey(keyJSON, password)
  198. if err != nil {
  199. return nil, err
  200. }
  201. key.Id = uuid.NewRandom()
  202. err = keyStore.StoreKey(key, password)
  203. return key, err
  204. }
  205. func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error) {
  206. preSaleKeyStruct := struct {
  207. EncSeed string
  208. EthAddr string
  209. Email string
  210. BtcAddr string
  211. }{}
  212. err = json.Unmarshal(fileContent, &preSaleKeyStruct)
  213. if err != nil {
  214. return nil, err
  215. }
  216. encSeedBytes, err := hex.DecodeString(preSaleKeyStruct.EncSeed)
  217. iv := encSeedBytes[:16]
  218. cipherText := encSeedBytes[16:]
  219. /*
  220. See https://github.com/ethereum/pyethsaletool
  221. pyethsaletool generates the encryption key from password by
  222. 2000 rounds of PBKDF2 with HMAC-SHA-256 using password as salt (:().
  223. 16 byte key length within PBKDF2 and resulting key is used as AES key
  224. */
  225. passBytes := []byte(password)
  226. derivedKey := pbkdf2.Key(passBytes, passBytes, 2000, 16, sha256.New)
  227. plainText, err := aesCBCDecrypt(derivedKey, cipherText, iv)
  228. ethPriv := Sha3(plainText)
  229. ecKey := ToECDSA(ethPriv)
  230. key = &Key{
  231. Id: nil,
  232. Address: PubkeyToAddress(ecKey.PublicKey),
  233. PrivateKey: ecKey,
  234. }
  235. derivedAddr := hex.EncodeToString(key.Address.Bytes()) // needed because .Hex() gives leading "0x"
  236. expectedAddr := preSaleKeyStruct.EthAddr
  237. if derivedAddr != expectedAddr {
  238. err = errors.New(fmt.Sprintf("decrypted addr not equal to expected addr ", derivedAddr, expectedAddr))
  239. }
  240. return key, err
  241. }
  242. // AES-128 is selected due to size of encryptKey
  243. func aesCTRXOR(key, inText, iv []byte) ([]byte, error) {
  244. aesBlock, err := aes.NewCipher(key)
  245. if err != nil {
  246. return nil, err
  247. }
  248. stream := cipher.NewCTR(aesBlock, iv)
  249. outText := make([]byte, len(inText))
  250. stream.XORKeyStream(outText, inText)
  251. return outText, err
  252. }
  253. func aesCBCDecrypt(key, cipherText, iv []byte) ([]byte, error) {
  254. aesBlock, err := aes.NewCipher(key)
  255. if err != nil {
  256. return nil, err
  257. }
  258. decrypter := cipher.NewCBCDecrypter(aesBlock, iv)
  259. paddedPlaintext := make([]byte, len(cipherText))
  260. decrypter.CryptBlocks(paddedPlaintext, cipherText)
  261. plaintext := PKCS7Unpad(paddedPlaintext)
  262. if plaintext == nil {
  263. err = errors.New("Decryption failed: PKCS7Unpad failed after AES decryption")
  264. }
  265. return plaintext, err
  266. }
  267. // From https://leanpub.com/gocrypto/read#leanpub-auto-block-cipher-modes
  268. func PKCS7Unpad(in []byte) []byte {
  269. if len(in) == 0 {
  270. return nil
  271. }
  272. padding := in[len(in)-1]
  273. if int(padding) > len(in) || padding > aes.BlockSize {
  274. return nil
  275. } else if padding == 0 {
  276. return nil
  277. }
  278. for i := len(in) - 1; i > len(in)-int(padding)-1; i-- {
  279. if in[i] != padding {
  280. return nil
  281. }
  282. }
  283. return in[:len(in)-int(padding)]
  284. }
  285. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  286. pubBytes := FromECDSAPub(&p)
  287. return common.BytesToAddress(Sha3(pubBytes[1:])[12:])
  288. }
  289. func zeroBytes(bytes []byte) {
  290. for i := range bytes {
  291. bytes[i] = 0
  292. }
  293. }