Salsa20.hpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #if (!defined(ZT_SALSA20_SSE)) && (defined(__SSE2__) || defined(__WINDOWS__))
  15. #define ZT_SALSA20_SSE 1
  16. #endif
  17. #ifdef ZT_SALSA20_SSE
  18. #include <emmintrin.h>
  19. #endif // ZT_SALSA20_SSE
  20. namespace ZeroTier {
  21. /**
  22. * Salsa20 stream cipher
  23. */
  24. class Salsa20
  25. {
  26. public:
  27. inline Salsa20() {}
  28. 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. 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