Salsa20.hpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 <stdint.h>
  9. #include "Constants.hpp"
  10. #ifdef ZT_SALSA20_SSE
  11. #include <emmintrin.h>
  12. #endif // ZT_SALSA20_SSE
  13. namespace ZeroTier {
  14. /**
  15. * Salsa20 stream cipher
  16. */
  17. class Salsa20
  18. {
  19. public:
  20. Salsa20() throw() {}
  21. /**
  22. * @param key Key bits
  23. * @param kbits Number of key bits: 128 or 256 (recommended)
  24. * @param iv 64-bit initialization vector
  25. * @param rounds Number of rounds: 8, 12, or 20
  26. */
  27. Salsa20(const void *key,unsigned int kbits,const void *iv,unsigned int rounds)
  28. throw()
  29. {
  30. init(key,kbits,iv,rounds);
  31. }
  32. /**
  33. * Initialize cipher
  34. *
  35. * @param key Key bits
  36. * @param kbits Number of key bits: 128 or 256 (recommended)
  37. * @param iv 64-bit initialization vector
  38. * @param rounds Number of rounds: 8, 12, or 20
  39. */
  40. void init(const void *key,unsigned int kbits,const void *iv,unsigned int rounds)
  41. throw();
  42. /**
  43. * Encrypt data
  44. *
  45. * @param in Input data
  46. * @param out Output buffer
  47. * @param bytes Length of data
  48. */
  49. void encrypt(const void *in,void *out,unsigned int bytes)
  50. throw();
  51. /**
  52. * Decrypt data
  53. *
  54. * @param in Input data
  55. * @param out Output buffer
  56. * @param bytes Length of data
  57. */
  58. inline void decrypt(const void *in,void *out,unsigned int bytes)
  59. throw()
  60. {
  61. encrypt(in,out,bytes);
  62. }
  63. private:
  64. volatile union {
  65. #ifdef ZT_SALSA20_SSE
  66. __m128i v[4];
  67. #endif // ZT_SALSA20_SSE
  68. uint32_t i[16];
  69. } _state;
  70. unsigned int _roundsDiv2;
  71. };
  72. } // namespace ZeroTier
  73. #endif