]> git.tdb.fi Git - libs/crypto.git/blob - source/sha2.h
Implement the SHA2 hash family
[libs/crypto.git] / source / sha2.h
1 #ifndef MSP_CRYPTO_SHA2_H_
2 #define MSP_CRYPTO_SHA2_H_
3
4 #include <msp/core/inttypes.h>
5 #include "blockhash.h"
6
7 namespace Msp {
8 namespace Crypto {
9
10 template<typename C>
11 class SHA2: public BlockHash<C::BLOCK_SIZE>
12 {
13 private:
14         typedef C Constants;
15         typedef typename Constants::WordType WordType;
16
17         typename Constants::WordType buffer[8];
18         UInt64 processed_bytes;
19
20 public:
21         SHA2();
22         SHA2(const char *, unsigned);
23         SHA2(const std::string &);
24 private:
25         void init();
26
27 public:
28         virtual unsigned get_digest_size() const { return Constants::DIGEST_SIZE; }
29
30         virtual unsigned get_digest(char *, unsigned) const;
31
32 private:
33         virtual void process_block(const char *);
34 };
35
36
37 struct SHA2_256Constants
38 {
39         typedef UInt32 WordType;
40
41         enum
42         {
43                 WORD_SIZE = sizeof(WordType),
44                 BLOCK_SIZE = 64,   // 512 bits
45                 DIGEST_SIZE = 32,  // 256 bits
46                 N_ROUNDS = 64
47         };
48
49         static const WordType initial[8];
50         static const WordType round_constants[N_ROUNDS];
51         static const unsigned sigma_constants[12];
52 };
53
54 struct SHA2_512Constants
55 {
56         typedef UInt64 WordType;
57
58         enum
59         {
60                 WORD_SIZE = sizeof(WordType),
61                 BLOCK_SIZE = 128,  // 1024 bits
62                 DIGEST_SIZE = 64,  // 512 bits
63                 N_ROUNDS = 80
64         };
65
66         static const WordType initial[8];
67         static const WordType round_constants[N_ROUNDS];
68         static const unsigned sigma_constants[12];
69 };
70
71 typedef SHA2<SHA2_256Constants> SHA256;
72 typedef SHA2<SHA2_512Constants> SHA512;
73
74 } // namespace Crypto
75 } // namespace Msp
76
77 #endif