Salsa20.hpp 1.7 KB

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