blake2s.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Based on public domain code written in 2012 by Samuel Neves
  2. #ifndef _RAR_BLAKE2_
  3. #define _RAR_BLAKE2_
  4. #define BLAKE2_DIGEST_SIZE 32
  5. #define BLAKE2_THREADS_NUMBER 8
  6. enum blake2s_constant
  7. {
  8. BLAKE2S_BLOCKBYTES = 64,
  9. BLAKE2S_OUTBYTES = 32
  10. };
  11. // Alignment to 64 improves performance of both SSE and non-SSE versions.
  12. // Alignment to n*16 is required for SSE version, so we selected 64.
  13. // We use the custom alignment scheme instead of __declspec(align(x)),
  14. // because it is less compiler dependent. Also the compiler directive
  15. // does not help if structure is a member of class allocated through
  16. // 'new' operator.
  17. struct blake2s_state
  18. {
  19. enum { BLAKE_ALIGNMENT = 64 };
  20. // buffer and uint32 h[8], t[2], f[2];
  21. enum { BLAKE_DATA_SIZE = 48 + 2 * BLAKE2S_BLOCKBYTES };
  22. byte ubuf[BLAKE_DATA_SIZE + BLAKE_ALIGNMENT];
  23. byte *buf; // byte buf[2 * BLAKE2S_BLOCKBYTES].
  24. uint32 *h, *t, *f; // uint32 h[8], t[2], f[2].
  25. size_t buflen;
  26. byte last_node;
  27. blake2s_state()
  28. {
  29. set_pointers();
  30. }
  31. // Required when we declare and assign in the same command.
  32. blake2s_state(blake2s_state &st)
  33. {
  34. set_pointers();
  35. *this=st;
  36. }
  37. void set_pointers()
  38. {
  39. // Set aligned pointers. Must be done in constructor, not in Init(),
  40. // so assignments like 'blake2sp_state res=blake2ctx' work correctly
  41. // even if blake2sp_init is not called for 'res'.
  42. buf = (byte *) ALIGN_VALUE(ubuf, BLAKE_ALIGNMENT);
  43. h = (uint32 *) (buf + 2 * BLAKE2S_BLOCKBYTES);
  44. t = h + 8;
  45. f = t + 2;
  46. }
  47. void init()
  48. {
  49. memset( ubuf, 0, sizeof( ubuf ) );
  50. buflen = 0;
  51. last_node = 0;
  52. }
  53. // Since we use pointers, the default = would work incorrectly.
  54. blake2s_state& operator = (blake2s_state &st)
  55. {
  56. if (this != &st)
  57. {
  58. memcpy(buf, st.buf, BLAKE_DATA_SIZE);
  59. buflen = st.buflen;
  60. last_node = st.last_node;
  61. }
  62. return *this;
  63. }
  64. };
  65. #ifdef RAR_SMP
  66. class ThreadPool;
  67. #endif
  68. struct blake2sp_state
  69. {
  70. blake2s_state S[8];
  71. blake2s_state R;
  72. byte buf[8 * BLAKE2S_BLOCKBYTES];
  73. size_t buflen;
  74. #ifdef RAR_SMP
  75. ThreadPool *ThPool;
  76. uint MaxThreads;
  77. #endif
  78. };
  79. void blake2sp_init( blake2sp_state *S );
  80. void blake2sp_update( blake2sp_state *S, const byte *in, size_t inlen );
  81. void blake2sp_final( blake2sp_state *S, byte *digest );
  82. #endif