aeaf314fbf662412a0ae2f005fbe10ea57ce3095
[libcds.git] / tests / hashing / sha256.h
1 // //////////////////////////////////////////////////////////
2 // sha256.h
3 // Copyright (c) 2014,2015 Stephan Brumme. All rights reserved.
4 // see http://create.stephan-brumme.com/disclaimer.html
5 //
6
7 #pragma once
8
9 //#include "hash.h"
10 #include <string>
11
12 // define fixed size integer types
13 #ifdef _MSC_VER
14 // Windows
15 typedef unsigned __int8  uint8_t;
16 typedef unsigned __int32 uint32_t;
17 typedef unsigned __int64 uint64_t;
18 #else
19 // GCC
20 #include <stdint.h>
21 #endif
22
23
24 /// compute SHA256 hash
25 /** Usage:
26     SHA256 sha256;
27     std::string myHash  = sha256("Hello World");     // std::string
28     std::string myHash2 = sha256("How are you", 11); // arbitrary data, 11 bytes
29
30     // or in a streaming fashion:
31
32     SHA256 sha256;
33     while (more data available)
34       sha256.add(pointer to fresh data, number of new bytes);
35     std::string myHash3 = sha256.getHash();
36   */
37 class SHA256 //: public Hash
38 {
39 public:
40   /// split into 64 byte blocks (=> 512 bits), hash is 32 bytes long
41   enum { BlockSize = 512 / 8, HashBytes = 32 };
42
43   /// same as reset()
44   SHA256();
45
46   /// compute SHA256 of a memory block
47   std::string operator()(const void* data, size_t numBytes);
48   /// compute SHA256 of a string, excluding final zero
49   std::string operator()(const std::string& text);
50
51   /// add arbitrary number of bytes
52   void add(const void* data, size_t numBytes);
53
54   /// return latest hash as 64 hex characters
55   std::string getHash();
56   /// return latest hash as bytes
57   void        getHash(unsigned char buffer[HashBytes]);
58
59   /// restart
60   void reset();
61
62 private:
63   /// process 64 bytes
64   void processBlock(const void* data);
65   /// process everything left in the internal buffer
66   void processBuffer();
67
68   /// size of processed data in bytes
69   uint64_t m_numBytes;
70   /// valid bytes in m_buffer
71   size_t   m_bufferSize;
72   /// bytes not processed yet
73   uint8_t  m_buffer[BlockSize];
74
75   enum { HashValues = HashBytes / 4 };
76   /// hash, stored as integers
77   uint32_t m_hash[HashValues];
78 };