Salsa20.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 data using Salsa20/12
  49. *
  50. * @param in Input data
  51. * @param out Output buffer
  52. * @param bytes Length of data
  53. */
  54. void encrypt12(const void *in,void *out,unsigned int bytes)
  55. throw();
  56. /**
  57. * Encrypt data using Salsa20/20
  58. *
  59. * @param in Input data
  60. * @param out Output buffer
  61. * @param bytes Length of data
  62. */
  63. void encrypt20(const void *in,void *out,unsigned int bytes)
  64. throw();
  65. /**
  66. * Decrypt data
  67. *
  68. * @param in Input data
  69. * @param out Output buffer
  70. * @param bytes Length of data
  71. */
  72. inline void decrypt12(const void *in,void *out,unsigned int bytes)
  73. throw()
  74. {
  75. encrypt12(in,out,bytes);
  76. }
  77. /**
  78. * Decrypt data
  79. *
  80. * @param in Input data
  81. * @param out Output buffer
  82. * @param bytes Length of data
  83. */
  84. inline void decrypt20(const void *in,void *out,unsigned int bytes)
  85. throw()
  86. {
  87. encrypt20(in,out,bytes);
  88. }
  89. private:
  90. union {
  91. #ifdef ZT_SALSA20_SSE
  92. __m128i v[4];
  93. #endif // ZT_SALSA20_SSE
  94. uint32_t i[16];
  95. } _state;
  96. };
  97. } // namespace ZeroTier
  98. #endif