Salsa20.hpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 "Constants.hpp"
  12. #include "Utils.hpp"
  13. #if (!defined(ZT_SALSA20_SSE)) && (defined(__SSE2__) || defined(__WINDOWS__))
  14. #define ZT_SALSA20_SSE 1
  15. #endif
  16. #ifdef ZT_SALSA20_SSE
  17. #include <emmintrin.h>
  18. #endif // ZT_SALSA20_SSE
  19. namespace ZeroTier {
  20. /**
  21. * Salsa20 stream cipher
  22. */
  23. class Salsa20
  24. {
  25. public:
  26. Salsa20() throw() {}
  27. ~Salsa20() { Utils::burn(&_state,sizeof(_state)); }
  28. /**
  29. * @param key Key bits
  30. * @param kbits Number of key bits: 128 or 256 (recommended)
  31. * @param iv 64-bit initialization vector
  32. */
  33. Salsa20(const void *key,unsigned int kbits,const void *iv)
  34. throw()
  35. {
  36. init(key,kbits,iv);
  37. }
  38. /**
  39. * Initialize cipher
  40. *
  41. * @param key Key bits
  42. * @param kbits Number of key bits: 128 or 256 (recommended)
  43. * @param iv 64-bit initialization vector
  44. */
  45. void init(const void *key,unsigned int kbits,const void *iv)
  46. throw();
  47. /**
  48. * Encrypt/decrypt data using Salsa20/12
  49. *
  50. * @param in Input data
  51. * @param out Output buffer
  52. * @param bytes Length of data
  53. */
  54. void crypt12(const void *in,void *out,unsigned int bytes)
  55. throw();
  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)
  64. throw();
  65. private:
  66. union {
  67. #ifdef ZT_SALSA20_SSE
  68. __m128i v[4];
  69. #endif // ZT_SALSA20_SSE
  70. uint32_t i[16];
  71. } _state;
  72. };
  73. } // namespace ZeroTier
  74. #endif