Salsa20.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_SALSA20_HPP
  14. #define ZT_SALSA20_HPP
  15. #include "Constants.hpp"
  16. #include "Utils.hpp"
  17. #include "TriviallyCopyable.hpp"
  18. #ifdef ZT_ARCH_X64
  19. #define ZT_SALSA20_SSE 1
  20. #endif
  21. #define ZT_SALSA20_KEY_SIZE 32
  22. namespace ZeroTier {
  23. /**
  24. * Salsa20 stream cipher
  25. */
  26. class Salsa20 : public TriviallyCopyable
  27. {
  28. public:
  29. #ifdef ZT_SALSA20_SSE
  30. static constexpr bool accelerated() noexcept { return true; }
  31. #else
  32. static constexpr bool accelerated() noexcept { return false; }
  33. #endif
  34. ZT_INLINE Salsa20() noexcept {}
  35. ZT_INLINE ~Salsa20() { Utils::burn(&_state,sizeof(_state)); }
  36. /**
  37. * @param key 256-bit (32 byte) key
  38. * @param iv 64-bit initialization vector
  39. */
  40. ZT_INLINE Salsa20(const void *key,const void *iv) noexcept { init(key,iv); }
  41. /**
  42. * Initialize cipher
  43. *
  44. * @param key Key bits
  45. * @param iv 64-bit initialization vector
  46. */
  47. void init(const void *key,const void *iv) noexcept;
  48. /**
  49. * Encrypt/decrypt data using Salsa20/12
  50. *
  51. * @param in Input data
  52. * @param out Output buffer
  53. * @param bytes Length of data
  54. */
  55. void crypt12(const void *in,void *out,unsigned int bytes) noexcept;
  56. /**
  57. * Encrypt/decrypt data using Salsa20/20
  58. *
  59. * @param in Input data
  60. * @param out Output buffer
  61. * @param bytes Length of data
  62. */
  63. void crypt20(const void *in,void *out,unsigned int bytes) noexcept;
  64. private:
  65. union {
  66. #ifdef ZT_SALSA20_SSE
  67. __m128i v[4];
  68. #endif // ZT_SALSA20_SSE
  69. uint32_t i[16];
  70. } _state;
  71. };
  72. } // namespace ZeroTier
  73. #endif