crypto.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. "os"
  12. "encoding/hex"
  13. "encoding/json"
  14. "errors"
  15. "code.google.com/p/go-uuid/uuid"
  16. "code.google.com/p/go.crypto/pbkdf2"
  17. "code.google.com/p/go.crypto/ripemd160"
  18. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  19. "github.com/ethereum/go-ethereum/crypto/sha3"
  20. "github.com/ethereum/go-ethereum/ethutil"
  21. "github.com/obscuren/ecies"
  22. )
  23. func init() {
  24. // specify the params for the s256 curve
  25. ecies.AddParamsForCurve(S256(), ecies.ECIES_AES128_SHA256)
  26. }
  27. func Sha3(data ...[]byte) []byte {
  28. d := sha3.NewKeccak256()
  29. for _, b := range data {
  30. d.Write(b)
  31. }
  32. return d.Sum(nil)
  33. }
  34. // Creates an ethereum address given the bytes and the nonce
  35. func CreateAddress(b []byte, nonce uint64) []byte {
  36. return Sha3(ethutil.NewValue([]interface{}{b, nonce}).Encode())[12:]
  37. }
  38. func Sha256(data []byte) []byte {
  39. hash := sha256.Sum256(data)
  40. return hash[:]
  41. }
  42. func Ripemd160(data []byte) []byte {
  43. ripemd := ripemd160.New()
  44. ripemd.Write(data)
  45. return ripemd.Sum(nil)
  46. }
  47. func Ecrecover(data []byte) []byte {
  48. var in = struct {
  49. hash []byte
  50. sig []byte
  51. }{data[:32], data[32:]}
  52. r, _ := secp256k1.RecoverPubkey(in.hash, in.sig)
  53. return r
  54. }
  55. // New methods using proper ecdsa keys from the stdlib
  56. func ToECDSA(prv []byte) *ecdsa.PrivateKey {
  57. if len(prv) == 0 {
  58. return nil
  59. }
  60. priv := new(ecdsa.PrivateKey)
  61. priv.PublicKey.Curve = S256()
  62. priv.D = ethutil.BigD(prv)
  63. priv.PublicKey.X, priv.PublicKey.Y = S256().ScalarBaseMult(prv)
  64. return priv
  65. }
  66. func FromECDSA(prv *ecdsa.PrivateKey) []byte {
  67. if prv == nil {
  68. return nil
  69. }
  70. return prv.D.Bytes()
  71. }
  72. func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
  73. if len(pub) == 0 {
  74. return nil
  75. }
  76. x, y := elliptic.Unmarshal(S256(), pub)
  77. return &ecdsa.PublicKey{S256(), x, y}
  78. }
  79. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  80. if pub == nil || pub.X == nil || pub.Y == nil {
  81. return nil
  82. }
  83. return elliptic.Marshal(S256(), pub.X, pub.Y)
  84. }
  85. // HexToECDSA parses a secp256k1 private key.
  86. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  87. b, err := hex.DecodeString(hexkey)
  88. if err != nil {
  89. return nil, errors.New("invalid hex string")
  90. }
  91. if len(b) != 32 {
  92. return nil, errors.New("invalid length, need 256 bits")
  93. }
  94. return ToECDSA(b), nil
  95. }
  96. // LoadECDSA loads a secp256k1 private key from the given file.
  97. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  98. buf := make([]byte, 32)
  99. fd, err := os.Open(file)
  100. if err != nil {
  101. return nil, err
  102. }
  103. defer fd.Close()
  104. if _, err := io.ReadFull(fd, buf); err != nil {
  105. return nil, err
  106. }
  107. return ToECDSA(buf), nil
  108. }
  109. func GenerateKey() (*ecdsa.PrivateKey, error) {
  110. return ecdsa.GenerateKey(S256(), rand.Reader)
  111. }
  112. func SigToPub(hash, sig []byte) *ecdsa.PublicKey {
  113. s := Ecrecover(append(hash, sig...))
  114. x, y := elliptic.Unmarshal(S256(), s)
  115. return &ecdsa.PublicKey{S256(), x, y}
  116. }
  117. func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
  118. if len(hash) != 32 {
  119. return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
  120. }
  121. sig, err = secp256k1.Sign(hash, ethutil.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8))
  122. return
  123. }
  124. func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) {
  125. return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil)
  126. }
  127. func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) {
  128. key := ecies.ImportECDSA(prv)
  129. return key.Decrypt(rand.Reader, ct, nil, nil)
  130. }
  131. // creates a Key and stores that in the given KeyStore by decrypting a presale key JSON
  132. func ImportPreSaleKey(keyStore KeyStore2, keyJSON []byte, password string) (*Key, error) {
  133. key, err := decryptPreSaleKey(keyJSON, password)
  134. if err != nil {
  135. return nil, err
  136. }
  137. key.Id = uuid.NewRandom()
  138. err = keyStore.StoreKey(key, password)
  139. return key, err
  140. }
  141. func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error) {
  142. preSaleKeyStruct := struct {
  143. EncSeed string
  144. EthAddr string
  145. Email string
  146. BtcAddr string
  147. }{}
  148. err = json.Unmarshal(fileContent, &preSaleKeyStruct)
  149. if err != nil {
  150. return nil, err
  151. }
  152. encSeedBytes, err := hex.DecodeString(preSaleKeyStruct.EncSeed)
  153. iv := encSeedBytes[:16]
  154. cipherText := encSeedBytes[16:]
  155. /*
  156. See https://github.com/ethereum/pyethsaletool
  157. pyethsaletool generates the encryption key from password by
  158. 2000 rounds of PBKDF2 with HMAC-SHA-256 using password as salt (:().
  159. 16 byte key length within PBKDF2 and resulting key is used as AES key
  160. */
  161. passBytes := []byte(password)
  162. derivedKey := pbkdf2.Key(passBytes, passBytes, 2000, 16, sha256.New)
  163. plainText, err := aesCBCDecrypt(derivedKey, cipherText, iv)
  164. ethPriv := Sha3(plainText)
  165. ecKey := ToECDSA(ethPriv)
  166. key = &Key{
  167. Id: nil,
  168. Address: PubkeyToAddress(ecKey.PublicKey),
  169. PrivateKey: ecKey,
  170. }
  171. derivedAddr := ethutil.Bytes2Hex(key.Address)
  172. expectedAddr := preSaleKeyStruct.EthAddr
  173. if derivedAddr != expectedAddr {
  174. err = errors.New("decrypted addr not equal to expected addr")
  175. }
  176. return key, err
  177. }
  178. func aesCBCDecrypt(key []byte, cipherText []byte, iv []byte) (plainText []byte, err error) {
  179. aesBlock, err := aes.NewCipher(key)
  180. if err != nil {
  181. return plainText, err
  182. }
  183. decrypter := cipher.NewCBCDecrypter(aesBlock, iv)
  184. paddedPlainText := make([]byte, len(cipherText))
  185. decrypter.CryptBlocks(paddedPlainText, cipherText)
  186. plainText = PKCS7Unpad(paddedPlainText)
  187. if plainText == nil {
  188. err = errors.New("Decryption failed: PKCS7Unpad failed after decryption")
  189. }
  190. return plainText, err
  191. }
  192. // From https://leanpub.com/gocrypto/read#leanpub-auto-block-cipher-modes
  193. func PKCS7Pad(in []byte) []byte {
  194. padding := 16 - (len(in) % 16)
  195. if padding == 0 {
  196. padding = 16
  197. }
  198. for i := 0; i < padding; i++ {
  199. in = append(in, byte(padding))
  200. }
  201. return in
  202. }
  203. func PKCS7Unpad(in []byte) []byte {
  204. if len(in) == 0 {
  205. return nil
  206. }
  207. padding := in[len(in)-1]
  208. if int(padding) > len(in) || padding > aes.BlockSize {
  209. return nil
  210. } else if padding == 0 {
  211. return nil
  212. }
  213. for i := len(in) - 1; i > len(in)-int(padding)-1; i-- {
  214. if in[i] != padding {
  215. return nil
  216. }
  217. }
  218. return in[:len(in)-int(padding)]
  219. }
  220. func PubkeyToAddress(p ecdsa.PublicKey) []byte {
  221. pubBytes := FromECDSAPub(&p)
  222. return Sha3(pubBytes[1:])[12:]
  223. }