Ethereum  PoC-8
The C++ Implementation of Ethereum
AES.cpp
Go to the documentation of this file.
1 /*
2  This file is part of cpp-ethereum.
3 
4  cpp-ethereum is free software: you can redistribute it and/or modify
5  it under the terms of the GNU 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  cpp-ethereum 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 General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
16  */
22 #include "AES.h"
23 #include <cryptopp/aes.h>
24 #include <cryptopp/filters.h>
25 #include <cryptopp/pwdbased.h>
26 #include <cryptopp/modes.h>
27 #include <cryptopp/sha.h>
28 
29 using namespace dev;
30 using namespace dev::crypto;
31 
32 bytes dev::aesDecrypt(bytesConstRef _ivCipher, std::string const& _password, unsigned _rounds, bytesConstRef _salt)
33 {
34  bytes pw = asBytes(_password);
35 
36  if (!_salt.size())
37  _salt = &pw;
38 
39  bytes target(64);
40  CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::SHA256>().DeriveKey(target.data(), target.size(), 0, pw.data(), pw.size(), _salt.data(), _salt.size(), _rounds);
41 
42  try
43  {
44  CryptoPP::AES::Decryption aesDecryption(target.data(), 16);
45  auto cipher = _ivCipher.cropped(16);
46  auto iv = _ivCipher.cropped(0, 16);
47  CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv.data());
48  std::string decrypted;
49  CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decrypted));
50  stfDecryptor.Put(cipher.data(), cipher.size());
51  stfDecryptor.MessageEnd();
52  return asBytes(decrypted);
53  }
54  catch (std::exception const& e)
55  {
56  // FIXME: Handle this error better.
57  std::cerr << e.what() << '\n';
58  return bytes();
59  }
60 }
dev::vector_ref< byte const >
dev::crypto
Definition: Common.h:180
dev::vector_ref::cropped
vector_ref< _T > cropped(size_t _begin, size_t _count) const
Definition: vector_ref.h:60
dev::bytes
std::vector< byte > bytes
Definition: Common.h:72
dev::vector_ref::data
_T * data() const
Definition: vector_ref.h:49
dev::vector_ref::size
size_t size() const
Definition: vector_ref.h:53
AES.h
dev::asBytes
bytes asBytes(std::string const &_b)
Converts a string to a byte array containing the string's (byte) data.
Definition: CommonData.h:106
dev::aesDecrypt
bytes aesDecrypt(bytesConstRef _cipher, std::string const &_password, unsigned _rounds=2000, bytesConstRef _salt=bytesConstRef())
Definition: AES.cpp:32
dev
Definition: Address.cpp:21