Salsa20.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. */
  31. Salsa20(const void *key,unsigned int kbits,const void *iv)
  32. throw()
  33. {
  34. init(key,kbits,iv);
  35. }
  36. /**
  37. * Initialize cipher
  38. *
  39. * @param key Key bits
  40. * @param kbits Number of key bits: 128 or 256 (recommended)
  41. * @param iv 64-bit initialization vector
  42. */
  43. void init(const void *key,unsigned int kbits,const void *iv)
  44. throw();
  45. /**
  46. * Encrypt data using Salsa20/12
  47. *
  48. * @param in Input data
  49. * @param out Output buffer
  50. * @param bytes Length of data
  51. */
  52. void encrypt12(const void *in,void *out,unsigned int bytes)
  53. throw();
  54. /**
  55. * Encrypt data using Salsa20/20
  56. *
  57. * @param in Input data
  58. * @param out Output buffer
  59. * @param bytes Length of data
  60. */
  61. void encrypt20(const void *in,void *out,unsigned int bytes)
  62. throw();
  63. /**
  64. * Decrypt data
  65. *
  66. * @param in Input data
  67. * @param out Output buffer
  68. * @param bytes Length of data
  69. */
  70. inline void decrypt12(const void *in,void *out,unsigned int bytes)
  71. throw()
  72. {
  73. encrypt12(in,out,bytes);
  74. }
  75. /**
  76. * Decrypt data
  77. *
  78. * @param in Input data
  79. * @param out Output buffer
  80. * @param bytes Length of data
  81. */
  82. inline void decrypt20(const void *in,void *out,unsigned int bytes)
  83. throw()
  84. {
  85. encrypt20(in,out,bytes);
  86. }
  87. private:
  88. union {
  89. #ifdef ZT_SALSA20_SSE
  90. __m128i v[4];
  91. #endif // ZT_SALSA20_SSE
  92. uint32_t i[16];
  93. } _state;
  94. };
  95. } // namespace ZeroTier
  96. #endif