Salsa20.hpp 1.7 KB

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