SHA1.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. 100% free public domain implementation of the SHA-1
  3. algorithm by Dominik Reichl <Dominik.Reichl@swp-net.de>
  4. === Test Vectors (from FIPS PUB 180-1) ===
  5. "abc"
  6. A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
  7. "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
  8. 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
  9. A million repetitions of "a"
  10. 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
  11. */
  12. #ifndef ___SHA1_H___
  13. #define ___SHA1_H___
  14. #include <stdio.h> // Needed for file access
  15. #include <memory.h> // Needed for memset and memcpy
  16. //#define LITTLE_ENDIAN
  17. #define MAX_FILE_READ_BUFFER 8000
  18. class CSHA1
  19. {
  20. public:
  21. // Rotate x bits to the left
  22. #define ROL32(value, bits) (((value)<<(bits))|((value)>>(32-(bits))))
  23. #ifdef LITTLE_ENDIAN
  24. #define SHABLK0(i) (block->l[i] = (ROL32(block->l[i],24) & 0xFF00FF00) | (ROL32(block->l[i],8) & 0x00FF00FF))
  25. #else
  26. #define SHABLK0(i) (block->l[i])
  27. #endif
  28. #define SHABLK(i) (block->l[i&15] = ROL32(block->l[(i+13)&15] ^ block->l[(i+8)&15] ^ block->l[(i+2)&15] ^ block->l[i&15],1))
  29. // SHA-1 rounds
  30. #define R0(v,w,x,y,z,i) { z+=((w&(x^y))^y)+SHABLK0(i)+0x5A827999+ROL32(v,5); w=ROL32(w,30); }
  31. #define R1(v,w,x,y,z,i) { z+=((w&(x^y))^y)+SHABLK(i)+0x5A827999+ROL32(v,5); w=ROL32(w,30); }
  32. #define R2(v,w,x,y,z,i) { z+=(w^x^y)+SHABLK(i)+0x6ED9EBA1+ROL32(v,5); w=ROL32(w,30); }
  33. #define R3(v,w,x,y,z,i) { z+=(((w|x)&y)|(w&x))+SHABLK(i)+0x8F1BBCDC+ROL32(v,5); w=ROL32(w,30); }
  34. #define R4(v,w,x,y,z,i) { z+=(w^x^y)+SHABLK(i)+0xCA62C1D6+ROL32(v,5); w=ROL32(w,30); }
  35. typedef union {
  36. unsigned char c[64];
  37. unsigned long l[16];
  38. } SHA1_WORKSPACE_BLOCK;
  39. // Two different formats for ReportHash(...)
  40. enum { REPORT_HEX = 0, REPORT_DIGIT = 1 };
  41. // Constructor and Destructor
  42. CSHA1();
  43. virtual ~CSHA1();
  44. unsigned long m_state[5];
  45. unsigned long m_count[2];
  46. unsigned char m_buffer[64];
  47. unsigned char m_digest[20];
  48. void Reset();
  49. // Update the hash value
  50. void Update(unsigned char* data, unsigned int len);
  51. bool HashFile(char *szFileName);
  52. // Finalize hash and report
  53. void Final();
  54. void ReportHash(char *szReport, unsigned char uReportType = REPORT_HEX);
  55. void GetHash(unsigned char *uDest);
  56. private:
  57. // Private SHA-1 transformation
  58. void Transform(unsigned long state[5], unsigned char buffer[64]);
  59. };
  60. #endif // ___SHA1_H___