crypto.go 8.0 KB

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