github.com/klaytn/klaytn@v1.12.1/accounts/keystore/presale.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2016 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from accounts/keystore/presale.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package keystore
    22  
    23  import (
    24  	"crypto/aes"
    25  	"crypto/cipher"
    26  )
    27  
    28  func aesCTRXOR(key, inText, iv []byte) ([]byte, error) {
    29  	// AES-128 is selected due to size of encryptKey.
    30  	aesBlock, err := aes.NewCipher(key)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	stream := cipher.NewCTR(aesBlock, iv)
    35  	outText := make([]byte, len(inText))
    36  	stream.XORKeyStream(outText, inText)
    37  	return outText, err
    38  }
    39  
    40  func aesCBCDecrypt(key, cipherText, iv []byte) ([]byte, error) {
    41  	aesBlock, err := aes.NewCipher(key)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  	decrypter := cipher.NewCBCDecrypter(aesBlock, iv)
    46  	paddedPlaintext := make([]byte, len(cipherText))
    47  	decrypter.CryptBlocks(paddedPlaintext, cipherText)
    48  	plaintext := pkcs7Unpad(paddedPlaintext)
    49  	if plaintext == nil {
    50  		return nil, ErrDecrypt
    51  	}
    52  	return plaintext, err
    53  }
    54  
    55  // From https://leanpub.com/gocrypto/read#leanpub-auto-block-cipher-modes
    56  func pkcs7Unpad(in []byte) []byte {
    57  	if len(in) == 0 {
    58  		return nil
    59  	}
    60  
    61  	padding := in[len(in)-1]
    62  	if int(padding) > len(in) || padding > aes.BlockSize {
    63  		return nil
    64  	} else if padding == 0 {
    65  		return nil
    66  	}
    67  
    68  	for i := len(in) - 1; i > len(in)-int(padding)-1; i-- {
    69  		if in[i] != padding {
    70  			return nil
    71  		}
    72  	}
    73  	return in[:len(in)-int(padding)]
    74  }