Salsa20.hpp 1.4 KB

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