Common.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file Common.cpp
  15. * @author Alex Leverington <nessence@gmail.com>
  16. * @author Gav Wood <i@gavwood.com>
  17. * @date 2014
  18. */
  19. #include "Common.h"
  20. #include <cstdint>
  21. #include <chrono>
  22. #include <thread>
  23. #include <mutex>
  24. #include <libscrypt/libscrypt.h>
  25. #include <libdevcore/Guards.h>
  26. #include <libdevcore/SHA3.h>
  27. #include <libdevcore/RLP.h>
  28. #if ETH_HAVE_SECP256K1
  29. #include <secp256k1/include/secp256k1.h>
  30. #endif
  31. #include "AES.h"
  32. #include "CryptoPP.h"
  33. #include "Exceptions.h"
  34. using namespace std;
  35. using namespace dev;
  36. using namespace dev::crypto;
  37. #ifdef ETH_HAVE_SECP256K1
  38. class Secp256k1Context
  39. {
  40. public:
  41. static secp256k1_context_t const* get() { if (!s_this) s_this = new Secp256k1Context; return s_this->m_ctx; }
  42. private:
  43. Secp256k1Context() { m_ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); }
  44. ~Secp256k1Context() { secp256k1_context_destroy(m_ctx); }
  45. secp256k1_context_t* m_ctx;
  46. static Secp256k1Context* s_this;
  47. };
  48. Secp256k1Context* Secp256k1Context::s_this = nullptr;
  49. #endif
  50. bool dev::SignatureStruct::isValid() const noexcept
  51. {
  52. if (v > 1 ||
  53. r >= h256("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") ||
  54. s >= h256("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") ||
  55. s < h256(1) ||
  56. r < h256(1))
  57. return false;
  58. return true;
  59. }
  60. Public SignatureStruct::recover(h256 const& _hash) const
  61. {
  62. return dev::recover((Signature)*this, _hash);
  63. }
  64. Address dev::ZeroAddress = Address();
  65. Public dev::toPublic(Secret const& _secret)
  66. {
  67. #ifdef ETH_HAVE_SECP256K1
  68. bytes o(65);
  69. int pubkeylen;
  70. if (!secp256k1_ec_pubkey_create(Secp256k1Context::get(), o.data(), &pubkeylen, _secret.data(), false))
  71. return Public();
  72. return FixedHash<64>(o.data()+1, Public::ConstructFromPointer);
  73. #else
  74. Public p;
  75. Secp256k1PP::get()->toPublic(_secret, p);
  76. return p;
  77. #endif
  78. }
  79. Address dev::toAddress(Public const& _public)
  80. {
  81. return right160(sha3(_public.ref()));
  82. }
  83. Address dev::toAddress(Secret const& _secret)
  84. {
  85. Public p;
  86. Secp256k1PP::get()->toPublic(_secret, p);
  87. return toAddress(p);
  88. }
  89. Address dev::toAddress(Address const& _from, u256 const& _nonce)
  90. {
  91. return right160(sha3(rlpList(_from, _nonce)));
  92. }
  93. void dev::encrypt(Public const& _k, bytesConstRef _plain, bytes& o_cipher)
  94. {
  95. bytes io = _plain.toBytes();
  96. Secp256k1PP::get()->encrypt(_k, io);
  97. o_cipher = std::move(io);
  98. }
  99. bool dev::decrypt(Secret const& _k, bytesConstRef _cipher, bytes& o_plaintext)
  100. {
  101. bytes io = _cipher.toBytes();
  102. Secp256k1PP::get()->decrypt(_k, io);
  103. if (io.empty())
  104. return false;
  105. o_plaintext = std::move(io);
  106. return true;
  107. }
  108. void dev::encryptECIES(Public const& _k, bytesConstRef _plain, bytes& o_cipher)
  109. {
  110. encryptECIES(_k, bytesConstRef(), _plain, o_cipher);
  111. }
  112. void dev::encryptECIES(Public const& _k, bytesConstRef _sharedMacData, bytesConstRef _plain, bytes& o_cipher)
  113. {
  114. bytes io = _plain.toBytes();
  115. Secp256k1PP::get()->encryptECIES(_k, _sharedMacData, io);
  116. o_cipher = std::move(io);
  117. }
  118. bool dev::decryptECIES(Secret const& _k, bytesConstRef _cipher, bytes& o_plaintext)
  119. {
  120. return decryptECIES(_k, bytesConstRef(), _cipher, o_plaintext);
  121. }
  122. bool dev::decryptECIES(Secret const& _k, bytesConstRef _sharedMacData, bytesConstRef _cipher, bytes& o_plaintext)
  123. {
  124. bytes io = _cipher.toBytes();
  125. if (!Secp256k1PP::get()->decryptECIES(_k, _sharedMacData, io))
  126. return false;
  127. o_plaintext = std::move(io);
  128. return true;
  129. }
  130. void dev::encryptSym(Secret const& _k, bytesConstRef _plain, bytes& o_cipher)
  131. {
  132. // TOOD: @alex @subtly do this properly.
  133. encrypt(KeyPair(_k).pub(), _plain, o_cipher);
  134. }
  135. bool dev::decryptSym(Secret const& _k, bytesConstRef _cipher, bytes& o_plain)
  136. {
  137. // TODO: @alex @subtly do this properly.
  138. return decrypt(_k, _cipher, o_plain);
  139. }
  140. std::pair<bytes, h128> dev::encryptSymNoAuth(SecureFixedHash<16> const& _k, bytesConstRef _plain)
  141. {
  142. h128 iv(Nonce::get().makeInsecure());
  143. return make_pair(encryptSymNoAuth(_k, iv, _plain), iv);
  144. }
  145. bytes dev::encryptAES128CTR(bytesConstRef _k, h128 const& _iv, bytesConstRef _plain)
  146. {
  147. if (_k.size() != 16 && _k.size() != 24 && _k.size() != 32)
  148. return bytes();
  149. SecByteBlock key(_k.data(), _k.size());
  150. try
  151. {
  152. CTR_Mode<AES>::Encryption e;
  153. e.SetKeyWithIV(key, key.size(), _iv.data());
  154. bytes ret(_plain.size());
  155. e.ProcessData(ret.data(), _plain.data(), _plain.size());
  156. return ret;
  157. }
  158. catch (CryptoPP::Exception& _e)
  159. {
  160. cerr << _e.what() << endl;
  161. return bytes();
  162. }
  163. }
  164. bytesSec dev::decryptAES128CTR(bytesConstRef _k, h128 const& _iv, bytesConstRef _cipher)
  165. {
  166. if (_k.size() != 16 && _k.size() != 24 && _k.size() != 32)
  167. return bytesSec();
  168. SecByteBlock key(_k.data(), _k.size());
  169. try
  170. {
  171. CTR_Mode<AES>::Decryption d;
  172. d.SetKeyWithIV(key, key.size(), _iv.data());
  173. bytesSec ret(_cipher.size());
  174. d.ProcessData(ret.writable().data(), _cipher.data(), _cipher.size());
  175. return ret;
  176. }
  177. catch (CryptoPP::Exception& _e)
  178. {
  179. cerr << _e.what() << endl;
  180. return bytesSec();
  181. }
  182. }
  183. static const Public c_zeroKey("3f17f1962b36e491b30a40b2405849e597ba5fb5");
  184. Public dev::recover(Signature const& _sig, h256 const& _message)
  185. {
  186. Public ret;
  187. #ifdef ETH_HAVE_SECP256K1
  188. bytes o(65);
  189. int pubkeylen;
  190. if (_sig[64] > 3 || !secp256k1_ecdsa_recover_compact(Secp256k1Context::get(), _message.data(), _sig.data(), o.data(), &pubkeylen, false, _sig[64]))
  191. return Public();
  192. ret = FixedHash<64>(o.data() + 1, Public::ConstructFromPointer);
  193. #else
  194. ret = Secp256k1PP::get()->recover(_sig, _message.ref());
  195. #endif
  196. if (ret == c_zeroKey)
  197. return Public();
  198. return ret;
  199. }
  200. static const u256 c_secp256k1n("115792089237316195423570985008687907852837564279074904382605163141518161494337");
  201. Signature dev::sign(Secret const& _k, h256 const& _hash)
  202. {
  203. Signature s;
  204. SignatureStruct& ss = *reinterpret_cast<SignatureStruct*>(&s);
  205. #ifdef ETH_HAVE_SECP256K1
  206. int v;
  207. if (!secp256k1_ecdsa_sign_compact(Secp256k1Context::get(), _hash.data(), s.data(), _k.data(), NULL, NULL, &v))
  208. return Signature();
  209. ss.v = v;
  210. #else
  211. s = Secp256k1PP::get()->sign(_k, _hash);
  212. #endif
  213. if (ss.s > c_secp256k1n / 2)
  214. {
  215. ss.v = ss.v ^ 1;
  216. ss.s = h256(c_secp256k1n - u256(ss.s));
  217. }
  218. assert(ss.s <= c_secp256k1n / 2);
  219. return s;
  220. }
  221. bool dev::verify(Public const& _p, Signature const& _s, h256 const& _hash)
  222. {
  223. if (!_p)
  224. return false;
  225. #ifdef ETH_HAVE_SECP256K1
  226. return _p == recover(_s, _hash);
  227. #else
  228. return Secp256k1PP::get()->verify(_p, _s, _hash.ref(), true);
  229. #endif
  230. }
  231. bytesSec dev::pbkdf2(string const& _pass, bytes const& _salt, unsigned _iterations, unsigned _dkLen)
  232. {
  233. bytesSec ret(_dkLen);
  234. if (PKCS5_PBKDF2_HMAC<SHA256>().DeriveKey(
  235. ret.writable().data(),
  236. _dkLen,
  237. 0,
  238. reinterpret_cast<byte const*>(_pass.data()),
  239. _pass.size(),
  240. _salt.data(),
  241. _salt.size(),
  242. _iterations
  243. ) != _iterations)
  244. BOOST_THROW_EXCEPTION(CryptoException() << errinfo_comment("Key derivation failed."));
  245. return ret;
  246. }
  247. bytesSec dev::scrypt(std::string const& _pass, bytes const& _salt, uint64_t _n, uint32_t _r, uint32_t _p, unsigned _dkLen)
  248. {
  249. bytesSec ret(_dkLen);
  250. if (libscrypt_scrypt(
  251. reinterpret_cast<uint8_t const*>(_pass.data()),
  252. _pass.size(),
  253. _salt.data(),
  254. _salt.size(),
  255. _n,
  256. _r,
  257. _p,
  258. ret.writable().data(),
  259. _dkLen
  260. ) != 0)
  261. BOOST_THROW_EXCEPTION(CryptoException() << errinfo_comment("Key derivation failed."));
  262. return ret;
  263. }
  264. void KeyPair::populateFromSecret(Secret const& _sec)
  265. {
  266. m_secret = _sec;
  267. if (Secp256k1PP::get()->verifySecret(m_secret, m_public))
  268. m_address = toAddress(m_public);
  269. }
  270. KeyPair KeyPair::create()
  271. {
  272. for (int i = 0; i < 100; ++i)
  273. {
  274. KeyPair ret(Secret::random());
  275. if (ret.address())
  276. return ret;
  277. }
  278. return KeyPair();
  279. }
  280. KeyPair KeyPair::fromEncryptedSeed(bytesConstRef _seed, std::string const& _password)
  281. {
  282. return KeyPair(Secret(sha3(aesDecrypt(_seed, _password))));
  283. }
  284. h256 crypto::kdf(Secret const& _priv, h256 const& _hash)
  285. {
  286. // H(H(r||k)^h)
  287. h256 s;
  288. sha3mac(Secret::random().ref(), _priv.ref(), s.ref());
  289. s ^= _hash;
  290. sha3(s.ref(), s.ref());
  291. if (!s || !_hash || !_priv)
  292. BOOST_THROW_EXCEPTION(InvalidState());
  293. return s;
  294. }
  295. Secret Nonce::next()
  296. {
  297. Guard l(x_value);
  298. if (!m_value)
  299. {
  300. m_value = Secret::random();
  301. if (!m_value)
  302. BOOST_THROW_EXCEPTION(InvalidState());
  303. }
  304. m_value = sha3Secure(m_value.ref());
  305. return sha3(~m_value);
  306. }