Salsa20.hpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. Salsa20() {}
  28. ~Salsa20() { Utils::burn(&_state,sizeof(_state)); }
  29. /**
  30. * @param key 256-bit (32 byte) key
  31. * @param iv 64-bit initialization vector
  32. */
  33. Salsa20(const void *key,const void *iv)
  34. {
  35. init(key,iv);
  36. }
  37. /**
  38. * Initialize cipher
  39. *
  40. * @param key Key bits
  41. * @param iv 64-bit initialization vector
  42. */
  43. void init(const void *key,const void *iv);
  44. /**
  45. * Encrypt/decrypt data using Salsa20/12
  46. *
  47. * @param in Input data
  48. * @param out Output buffer
  49. * @param bytes Length of data
  50. */
  51. void crypt12(const void *in,void *out,unsigned int bytes);
  52. /**
  53. * Encrypt/decrypt data using Salsa20/20
  54. *
  55. * @param in Input data
  56. * @param out Output buffer
  57. * @param bytes Length of data
  58. */
  59. void crypt20(const void *in,void *out,unsigned int bytes);
  60. private:
  61. union {
  62. #ifdef ZT_SALSA20_SSE
  63. __m128i v[4];
  64. #endif // ZT_SALSA20_SSE
  65. uint32_t i[16];
  66. } _state;
  67. };
  68. } // namespace ZeroTier
  69. #endif