github.com/0xsequence/ethkit@v1.25.0/go-ethereum/accounts/keystore/presale.go (about)

     1  // Copyright 2016 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  
    17  package keystore
    18  
    19  import (
    20  	"crypto/aes"
    21  	"crypto/cipher"
    22  	"crypto/sha256"
    23  	"encoding/hex"
    24  	"encoding/json"
    25  	"errors"
    26  	"fmt"
    27  
    28  	"github.com/0xsequence/ethkit/go-ethereum/accounts"
    29  	"github.com/0xsequence/ethkit/go-ethereum/crypto"
    30  	"github.com/google/uuid"
    31  	"golang.org/x/crypto/pbkdf2"
    32  )
    33  
    34  // creates a Key and stores that in the given KeyStore by decrypting a presale key JSON
    35  func importPreSaleKey(keyStore keyStore, keyJSON []byte, password string) (accounts.Account, *Key, error) {
    36  	key, err := decryptPreSaleKey(keyJSON, password)
    37  	if err != nil {
    38  		return accounts.Account{}, nil, err
    39  	}
    40  	key.Id, err = uuid.NewRandom()
    41  	if err != nil {
    42  		return accounts.Account{}, nil, err
    43  	}
    44  	a := accounts.Account{
    45  		Address: key.Address,
    46  		URL: accounts.URL{
    47  			Scheme: KeyStoreScheme,
    48  			Path:   keyStore.JoinPath(keyFileName(key.Address)),
    49  		},
    50  	}
    51  	err = keyStore.StoreKey(a.URL.Path, key, password)
    52  	return a, key, err
    53  }
    54  
    55  func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error) {
    56  	preSaleKeyStruct := struct {
    57  		EncSeed string
    58  		EthAddr string
    59  		Email   string
    60  		BtcAddr string
    61  	}{}
    62  	err = json.Unmarshal(fileContent, &preSaleKeyStruct)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  	encSeedBytes, err := hex.DecodeString(preSaleKeyStruct.EncSeed)
    67  	if err != nil {
    68  		return nil, errors.New("invalid hex in encSeed")
    69  	}
    70  	if len(encSeedBytes) < 16 {
    71  		return nil, errors.New("invalid encSeed, too short")
    72  	}
    73  	iv := encSeedBytes[:16]
    74  	cipherText := encSeedBytes[16:]
    75  	/*
    76  		See https://github.com/ethereum/pyethsaletool
    77  
    78  		pyethsaletool generates the encryption key from password by
    79  		2000 rounds of PBKDF2 with HMAC-SHA-256 using password as salt (:().
    80  		16 byte key length within PBKDF2 and resulting key is used as AES key
    81  	*/
    82  	passBytes := []byte(password)
    83  	derivedKey := pbkdf2.Key(passBytes, passBytes, 2000, 16, sha256.New)
    84  	plainText, err := aesCBCDecrypt(derivedKey, cipherText, iv)
    85  	if err != nil {
    86  		return nil, err
    87  	}
    88  	ethPriv := crypto.Keccak256(plainText)
    89  	ecKey := crypto.ToECDSAUnsafe(ethPriv)
    90  
    91  	key = &Key{
    92  		Id:         uuid.UUID{},
    93  		Address:    crypto.PubkeyToAddress(ecKey.PublicKey),
    94  		PrivateKey: ecKey,
    95  	}
    96  	derivedAddr := hex.EncodeToString(key.Address.Bytes()) // needed because .Hex() gives leading "0x"
    97  	expectedAddr := preSaleKeyStruct.EthAddr
    98  	if derivedAddr != expectedAddr {
    99  		err = fmt.Errorf("decrypted addr '%s' not equal to expected addr '%s'", derivedAddr, expectedAddr)
   100  	}
   101  	return key, err
   102  }
   103  
   104  func aesCTRXOR(key, inText, iv []byte) ([]byte, error) {
   105  	// AES-128 is selected due to size of encryptKey.
   106  	aesBlock, err := aes.NewCipher(key)
   107  	if err != nil {
   108  		return nil, err
   109  	}
   110  	stream := cipher.NewCTR(aesBlock, iv)
   111  	outText := make([]byte, len(inText))
   112  	stream.XORKeyStream(outText, inText)
   113  	return outText, err
   114  }
   115  
   116  func aesCBCDecrypt(key, cipherText, iv []byte) ([]byte, error) {
   117  	aesBlock, err := aes.NewCipher(key)
   118  	if err != nil {
   119  		return nil, err
   120  	}
   121  	decrypter := cipher.NewCBCDecrypter(aesBlock, iv)
   122  	paddedPlaintext := make([]byte, len(cipherText))
   123  	decrypter.CryptBlocks(paddedPlaintext, cipherText)
   124  	plaintext := pkcs7Unpad(paddedPlaintext)
   125  	if plaintext == nil {
   126  		return nil, ErrDecrypt
   127  	}
   128  	return plaintext, err
   129  }
   130  
   131  // From https://leanpub.com/gocrypto/read#leanpub-auto-block-cipher-modes
   132  func pkcs7Unpad(in []byte) []byte {
   133  	if len(in) == 0 {
   134  		return nil
   135  	}
   136  
   137  	padding := in[len(in)-1]
   138  	if int(padding) > len(in) || padding > aes.BlockSize {
   139  		return nil
   140  	} else if padding == 0 {
   141  		return nil
   142  	}
   143  
   144  	for i := len(in) - 1; i > len(in)-int(padding)-1; i-- {
   145  		if in[i] != padding {
   146  			return nil
   147  		}
   148  	}
   149  	return in[:len(in)-int(padding)]
   150  }