Switch to unified view

a b/src/Common/SHA256.h
1
//
2
// This program is free software: you can redistribute it and/or modify
3
// it under the terms of the GNU Lesser General Public License as published by
4
// the Free Software Foundation, either version 3 of the License, or
5
// (at your option) any later version.
6
// 
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
// GNU Lesser General Public License for more details.
11
// 
12
// You should have received a copy of the GNU Lesser General Public License
13
// along with this program.  If not, see http://www.gnu.org/licenses/.
14
// 
15
16
#ifndef SHA256_H_
17
#define SHA256_H_
18
19
#include <cstring>
20
#include <string>
21
#include <cstdio>
22
23
class SHA256 {
24
  public:
25
    SHA256();
26
    virtual ~SHA256();
27
28
  protected:
29
    typedef unsigned char uint8;
30
    typedef unsigned int uint32;
31
    typedef unsigned long long uint64;
32
33
    const static uint32 sha256_k[];
34
    static const unsigned int SHA224_256_BLOCK_SIZE = (512/8);
35
  public:
36
    void init();
37
    void update(const unsigned char *message, unsigned int len);
38
    void final(unsigned char *digest);
39
    static const unsigned int DIGEST_SIZE = ( 256 / 8);
40
41
  protected:
42
    void transform(const unsigned char *message, unsigned int block_nb);
43
    unsigned int m_tot_len;
44
    unsigned int m_len;
45
    unsigned char m_block[2*SHA224_256_BLOCK_SIZE];
46
    uint32 m_h[8];
47
48
};
49
50
51
std::string sha256(std::string input);
52
53
#define SHA2_SHFR(x, n)    (x >> n)
54
#define SHA2_ROTR(x, n)   ((x >> n) | (x << ((sizeof(x) << 3) - n)))
55
#define SHA2_ROTL(x, n)   ((x << n) | (x >> ((sizeof(x) << 3) - n)))
56
#define SHA2_CH(x, y, z)  ((x & y) ^ (~x & z))
57
#define SHA2_MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
58
#define SHA256_F1(x) (SHA2_ROTR(x,  2) ^ SHA2_ROTR(x, 13) ^ SHA2_ROTR(x, 22))
59
#define SHA256_F2(x) (SHA2_ROTR(x,  6) ^ SHA2_ROTR(x, 11) ^ SHA2_ROTR(x, 25))
60
#define SHA256_F3(x) (SHA2_ROTR(x,  7) ^ SHA2_ROTR(x, 18) ^ SHA2_SHFR(x,  3))
61
#define SHA256_F4(x) (SHA2_ROTR(x, 17) ^ SHA2_ROTR(x, 19) ^ SHA2_SHFR(x, 10))
62
#define SHA2_UNPACK32(x, str)                 \
63
{                                             \
64
    *((str) + 3) = (uint8) ((x)      );       \
65
    *((str) + 2) = (uint8) ((x) >>  8);       \
66
    *((str) + 1) = (uint8) ((x) >> 16);       \
67
    *((str) + 0) = (uint8) ((x) >> 24);       \
68
}
69
#define SHA2_PACK32(str, x)                   \
70
{                                             \
71
    *(x) =   ((uint32) *((str) + 3)      )    \
72
           | ((uint32) *((str) + 2) <<  8)    \
73
           | ((uint32) *((str) + 1) << 16)    \
74
           | ((uint32) *((str) + 0) << 24);   \
75
}
76
77
#endif /* SHA256_H_ */