Salsa20.hpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Based on public domain code available at: http://cr.yp.to/snuffle.html
  3. *
  4. * This therefore is public domain.
  5. */
  6. #ifndef ZT_SALSA20_HPP
  7. #define ZT_SALSA20_HPP
  8. #include <stdio.h>
  9. #include <stdint.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include "Constants.hpp"
  13. #include "Utils.hpp"
  14. #ifndef ZT_SALSA20_SSE
  15. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64))
  16. #include <emmintrin.h>
  17. #define ZT_SALSA20_SSE 1
  18. #endif
  19. #endif
  20. namespace ZeroTier {
  21. /**
  22. * Salsa20 stream cipher
  23. */
  24. class Salsa20
  25. {
  26. public:
  27. ZT_ALWAYS_INLINE Salsa20() {}
  28. ZT_ALWAYS_INLINE ~Salsa20() { Utils::burn(&_state,sizeof(_state)); }
  29. /**
  30. * @param key 256-bit (32 byte) key
  31. * @param iv 64-bit initialization vector
  32. */
  33. ZT_ALWAYS_INLINE Salsa20(const void *key,const void *iv) { init(key,iv); }
  34. /**
  35. * Initialize cipher
  36. *
  37. * @param key Key bits
  38. * @param iv 64-bit initialization vector
  39. */
  40. void init(const void *key,const void *iv);
  41. /**
  42. * Encrypt/decrypt data using Salsa20/12
  43. *
  44. * @param in Input data
  45. * @param out Output buffer
  46. * @param bytes Length of data
  47. */
  48. void crypt12(const void *in,void *out,unsigned int bytes);
  49. /**
  50. * Encrypt/decrypt data using Salsa20/20
  51. *
  52. * @param in Input data
  53. * @param out Output buffer
  54. * @param bytes Length of data
  55. */
  56. void crypt20(const void *in,void *out,unsigned int bytes);
  57. private:
  58. union {
  59. #ifdef ZT_SALSA20_SSE
  60. __m128i v[4];
  61. #endif // ZT_SALSA20_SSE
  62. uint32_t i[16];
  63. } _state;
  64. };
  65. } // namespace ZeroTier
  66. #endif