ECDHE.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 ECDHE.h
  15. * @author Alex Leverington <nessence@gmail.com>
  16. * @date 2014
  17. *
  18. * Elliptic curve Diffie-Hellman ephemeral key exchange
  19. */
  20. #pragma once
  21. #include "AES.h"
  22. namespace dev
  23. {
  24. namespace crypto
  25. {
  26. /// Public key of remote and corresponding shared secret.
  27. using AliasSession = std::pair<Public,h256>;
  28. /**
  29. * @brief An addressable EC key pair.
  30. */
  31. class Alias
  32. {
  33. public:
  34. Alias(Secret const& _s): m_secret(_s) {};
  35. AliasSession session(Address _a) { return m_sessions.count(_a) ? m_sessions.find(_a)->second : AliasSession(); }
  36. private:
  37. std::map<Address,AliasSession> m_sessions;
  38. Secret m_secret;
  39. };
  40. namespace ecdh
  41. {
  42. void agree(Secret const& _s, Public const& _r, Secret& o_s);
  43. }
  44. /**
  45. * @brief Derive DH shared secret from EC keypairs.
  46. * As ephemeral keys are single-use, agreement is limited to a single occurence.
  47. */
  48. class ECDHE
  49. {
  50. public:
  51. /// Constructor (pass public key for ingress exchange).
  52. ECDHE(): m_ephemeral(KeyPair::create()) {};
  53. /// Public key sent to remote.
  54. Public pubkey() { return m_ephemeral.pub(); }
  55. Secret seckey() { return m_ephemeral.sec(); }
  56. /// Input public key for dh agreement, output generated shared secret.
  57. void agree(Public const& _remoteEphemeral, Secret& o_sharedSecret) const;
  58. protected:
  59. KeyPair m_ephemeral; ///< Ephemeral keypair; generated.
  60. mutable Public m_remoteEphemeral; ///< Public key of remote; parameter. Set once when agree is called, otherwise immutable.
  61. };
  62. }
  63. }