Salsa20.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 <cstdint>
  16. #include <cstdlib>
  17. #include <cstring>
  18. #include "Constants.hpp"
  19. #include "Utils.hpp"
  20. #include "TriviallyCopyable.hpp"
  21. #ifdef ZT_ARCH_X64
  22. #include <xmmintrin.h>
  23. #include <emmintrin.h>
  24. #include <immintrin.h>
  25. #define ZT_SALSA20_SSE 1
  26. #endif
  27. namespace ZeroTier {
  28. /**
  29. * Salsa20 stream cipher
  30. */
  31. class Salsa20 : public TriviallyCopyable
  32. {
  33. public:
  34. #ifdef ZT_SALSA20_SSE
  35. static constexpr bool accelerated() noexcept { return true; }
  36. #else
  37. static constexpr bool accelerated() noexcept { return false; }
  38. #endif
  39. ZT_INLINE Salsa20() noexcept {}
  40. ZT_INLINE ~Salsa20() { Utils::burn(&_state,sizeof(_state)); }
  41. /**
  42. * @param key 256-bit (32 byte) key
  43. * @param iv 64-bit initialization vector
  44. */
  45. ZT_INLINE Salsa20(const void *key,const void *iv) noexcept { init(key,iv); }
  46. /**
  47. * Initialize cipher
  48. *
  49. * @param key Key bits
  50. * @param iv 64-bit initialization vector
  51. */
  52. void init(const void *key,const void *iv) noexcept;
  53. /**
  54. * Encrypt/decrypt data using Salsa20/12
  55. *
  56. * @param in Input data
  57. * @param out Output buffer
  58. * @param bytes Length of data
  59. */
  60. void crypt12(const void *in,void *out,unsigned int bytes) noexcept;
  61. /**
  62. * Encrypt/decrypt data using Salsa20/20
  63. *
  64. * @param in Input data
  65. * @param out Output buffer
  66. * @param bytes Length of data
  67. */
  68. void crypt20(const void *in,void *out,unsigned int bytes) noexcept;
  69. private:
  70. union {
  71. #ifdef ZT_SALSA20_SSE
  72. __m128i v[4];
  73. #endif // ZT_SALSA20_SSE
  74. uint32_t i[16];
  75. } _state;
  76. };
  77. } // namespace ZeroTier
  78. #endif