Implement the SHA2 hash family
[libs/crypto.git] / source / blockhash.h
1 #ifndef MSP_CRYPTO_BLOCKHASH_H_
2 #define MSP_CRYPTO_BLOCKHASH_H_
3
4 #include <algorithm>
5 #include "hash.h"
6
7 namespace Msp {
8 namespace Crypto {
9
10 template<unsigned B>
11 class BlockHash: public Hash
12 {
13 protected:
14         enum
15         {
16                 BLOCK_SIZE = B
17         };
18
19         char unprocessed[BLOCK_SIZE];
20         unsigned unprocessed_bytes;
21
22         BlockHash();
23
24 public:
25         using Hash::update;
26         virtual void update(const char *, unsigned);
27
28 protected:
29         virtual void process_block(const char *) = 0;
30 };
31
32
33 template<unsigned B>
34 inline BlockHash<B>::BlockHash():
35         unprocessed_bytes(0)
36 { }
37
38 template<unsigned B>
39 void BlockHash<B>::update(const char *data, unsigned len)
40 {
41         if(unprocessed_bytes && unprocessed_bytes+len>=BLOCK_SIZE)
42         {
43                 unsigned needed = BLOCK_SIZE-unprocessed_bytes;
44                 std::copy(data, data+needed, unprocessed+unprocessed_bytes);
45                 process_block(unprocessed);
46                 data += needed;
47                 len -= needed;
48                 unprocessed_bytes = 0;
49         }
50
51         while(len>=BLOCK_SIZE)
52         {
53                 process_block(data);
54                 data += BLOCK_SIZE;
55                 len -= BLOCK_SIZE;
56         }
57
58         if(len>0)
59         {
60                 std::copy(data, data+len, unprocessed+unprocessed_bytes);
61                 unprocessed_bytes += len;
62         }
63 }
64
65 } // namespace Crypto
66 } // namespace Msp
67
68 #endif