sha1.hpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. *****
  3. sha1.hpp is a repackaging of the sha1.cpp and sha1.h files from the smallsha1
  4. library (http://code.google.com/p/smallsha1/) into a single header suitable for
  5. use as a header only library. This conversion was done by Peter Thorson
  6. (webmaster@zaphoyd.com) in 2013. All modifications to the code are redistributed
  7. under the same license as the original, which is listed below.
  8. *****
  9. Copyright (c) 2011, Micael Hildenborg
  10. All rights reserved.
  11. Redistribution and use in source and binary forms, with or without
  12. modification, are permitted provided that the following conditions are met:
  13. * Redistributions of source code must retain the above copyright
  14. notice, this list of conditions and the following disclaimer.
  15. * Redistributions in binary form must reproduce the above copyright
  16. notice, this list of conditions and the following disclaimer in the
  17. documentation and/or other materials provided with the distribution.
  18. * Neither the name of Micael Hildenborg nor the
  19. names of its contributors may be used to endorse or promote products
  20. derived from this software without specific prior written permission.
  21. THIS SOFTWARE IS PROVIDED BY Micael Hildenborg ''AS IS'' AND ANY
  22. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  23. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  24. DISCLAIMED. IN NO EVENT SHALL Micael Hildenborg BE LIABLE FOR ANY
  25. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  26. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  27. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  28. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  30. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. #ifndef __ASIO2_SHA1_IMPL_HPP__
  33. #define __ASIO2_SHA1_IMPL_HPP__
  34. #include <cstring>
  35. #include <cstdint>
  36. #include <cstddef>
  37. #include <string>
  38. namespace asio2
  39. {
  40. class sha1
  41. {
  42. protected:
  43. // Rotate an integer value to left.
  44. inline unsigned int rol(unsigned int value, unsigned int steps) {
  45. return ((value << steps) | (value >> (32 - steps)));
  46. }
  47. // Sets the first 16 integers in the buffert to zero.
  48. // Used for clearing the W buffert.
  49. inline void clearWBuffert(unsigned int * buffert)
  50. {
  51. for (int pos = 16; --pos >= 0;)
  52. {
  53. buffert[pos] = 0;
  54. }
  55. }
  56. inline void innerHash(unsigned int * result, unsigned int * w)
  57. {
  58. unsigned int a = result[0];
  59. unsigned int b = result[1];
  60. unsigned int c = result[2];
  61. unsigned int d = result[3];
  62. unsigned int e = result[4];
  63. int round = 0;
  64. #define ASIO2_SHA1MACRO(func,val) \
  65. { \
  66. const unsigned int t = rol(a, 5) + (func) + e + val + w[round]; \
  67. e = d; \
  68. d = c; \
  69. c = rol(b, 30); \
  70. b = a; \
  71. a = t; \
  72. }
  73. while (round < 16)
  74. {
  75. ASIO2_SHA1MACRO((b & c) | (~b & d), 0x5a827999)
  76. ++round;
  77. }
  78. while (round < 20)
  79. {
  80. w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
  81. ASIO2_SHA1MACRO((b & c) | (~b & d), 0x5a827999)
  82. ++round;
  83. }
  84. while (round < 40)
  85. {
  86. w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
  87. ASIO2_SHA1MACRO(b ^ c ^ d, 0x6ed9eba1)
  88. ++round;
  89. }
  90. while (round < 60)
  91. {
  92. w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
  93. ASIO2_SHA1MACRO((b & c) | (b & d) | (c & d), 0x8f1bbcdc)
  94. ++round;
  95. }
  96. while (round < 80)
  97. {
  98. w[round] = rol((w[round - 3] ^ w[round - 8] ^ w[round - 14] ^ w[round - 16]), 1);
  99. ASIO2_SHA1MACRO(b ^ c ^ d, 0xca62c1d6)
  100. ++round;
  101. }
  102. #undef ASIO2_SHA1MACRO
  103. result[0] += a;
  104. result[1] += b;
  105. result[2] += c;
  106. result[3] += d;
  107. result[4] += e;
  108. }
  109. /// Calculate a SHA1 hash
  110. /**
  111. * @param src points to any kind of data to be hashed.
  112. * @param bytelength the number of bytes to hash from the src pointer.
  113. * @param hash should point to a buffer of at least 20 bytes of size for storing
  114. * the sha1 result in.
  115. */
  116. inline void calc(void const * src, size_t bytelength, unsigned char * hash) {
  117. // Init the result array.
  118. unsigned int result[5] = { 0x67452301, 0xefcdab89, 0x98badcfe,
  119. 0x10325476, 0xc3d2e1f0 };
  120. // Cast the void src pointer to be the byte array we can work with.
  121. unsigned char const * sarray = (unsigned char const *)src;
  122. // The reusable round buffer
  123. unsigned int w[80];
  124. // Loop through all complete 64byte blocks.
  125. size_t endCurrentBlock;
  126. size_t currentBlock = 0;
  127. if (bytelength >= 64) {
  128. size_t const endOfFullBlocks = bytelength - 64;
  129. while (currentBlock <= endOfFullBlocks) {
  130. endCurrentBlock = currentBlock + 64;
  131. // Init the round buffer with the 64 byte block data.
  132. for (int roundPos = 0; currentBlock < endCurrentBlock; currentBlock += 4)
  133. {
  134. // This line will swap endian on big endian and keep endian on
  135. // little endian.
  136. w[roundPos++] = (unsigned int)sarray[currentBlock + 3]
  137. | (((unsigned int)sarray[currentBlock + 2]) << 8)
  138. | (((unsigned int)sarray[currentBlock + 1]) << 16)
  139. | (((unsigned int)sarray[currentBlock]) << 24);
  140. }
  141. innerHash(result, w);
  142. }
  143. }
  144. // Handle the last and not full 64 byte block if existing.
  145. endCurrentBlock = bytelength - currentBlock;
  146. clearWBuffert(w);
  147. size_t lastBlockBytes = 0;
  148. for (; lastBlockBytes < endCurrentBlock; ++lastBlockBytes) {
  149. w[lastBlockBytes >> 2] |= (unsigned int)sarray[lastBlockBytes + currentBlock] << ((3 - (lastBlockBytes & 3)) << 3);
  150. }
  151. w[lastBlockBytes >> 2] |= 0x80 << ((3 - (lastBlockBytes & 3)) << 3);
  152. if (endCurrentBlock >= 56) {
  153. innerHash(result, w);
  154. clearWBuffert(w);
  155. }
  156. w[15] = static_cast<unsigned int>(bytelength << 3);
  157. innerHash(result, w);
  158. // Store hash in result pointer, and make sure we get in in the correct
  159. // order on both endian models.
  160. for (int hashByte = 20; --hashByte >= 0;) {
  161. hash[hashByte] = (result[hashByte >> 2] >> (((3 - hashByte) & 0x3) << 3)) & 0xff;
  162. }
  163. }
  164. unsigned char hash_[20];
  165. public:
  166. /**
  167. * @construct Construct a sha1 object with a std::string.
  168. */
  169. sha1(const std::string & message)
  170. {
  171. calc((void const *)message.data(), message.size(), hash_);
  172. }
  173. /**
  174. * @construct Construct a sha1 object with a char pointer.
  175. */
  176. sha1(const char * message)
  177. {
  178. calc((const void*)message, std::strlen(message), hash_);
  179. }
  180. /**
  181. * @construct Construct a sha1 object with a unsigned char pointer.
  182. */
  183. sha1(const void * message, std::size_t size)
  184. {
  185. calc((const void*)message, size, hash_);
  186. }
  187. /* Convert digest to std::string value */
  188. std::string str(bool upper = false)
  189. {
  190. /* Hex numbers. */
  191. char hex_upper[16] = {
  192. '0', '1', '2', '3',
  193. '4', '5', '6', '7',
  194. '8', '9', 'A', 'B',
  195. 'C', 'D', 'E', 'F'
  196. };
  197. char hex_lower[16] = {
  198. '0', '1', '2', '3',
  199. '4', '5', '6', '7',
  200. '8', '9', 'a', 'b',
  201. 'c', 'd', 'e', 'f'
  202. };
  203. std::string str;
  204. str.reserve(20 << 1);
  205. for (std::size_t i = 0; i < 20; ++i)
  206. {
  207. int t = hash_[i];
  208. int a = t / 16;
  209. int b = t % 16;
  210. str.append(1, upper ? hex_upper[a] : hex_lower[a]);
  211. str.append(1, upper ? hex_upper[b] : hex_lower[b]);
  212. }
  213. return str;
  214. }
  215. };
  216. } // namespace asio2
  217. #endif // __ASIO2_SHA1_IMPL_HPP__