Salsa20.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_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. ZT_ALWAYS_INLINE Salsa20() noexcept {}
  35. ZT_ALWAYS_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_ALWAYS_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