1 #include <qpdf/SHA2_native.hh>
2 #include <stdexcept>
3 #include <cstdio>
4 #include <qpdf/PointerHolder.hh>
5 #include <qpdf/QUtil.hh>
6 
7 
SHA2_native(int bits)8 SHA2_native::SHA2_native(int bits) :
9     bits(bits)
10 {
11     switch (bits)
12     {
13       case 256:
14         sph_sha256_init(&this->ctx256);
15         break;
16       case 384:
17         sph_sha384_init(&this->ctx384);
18         break;
19       case 512:
20         sph_sha512_init(&this->ctx512);
21         break;
22       default:
23         badBits();
24         break;
25     }
26 }
27 
28 void
badBits()29 SHA2_native::badBits()
30 {
31     throw std::logic_error("SHA2_native has bits != 256, 384, or 512");
32 }
33 
34 void
update(unsigned char const * buf,size_t len)35 SHA2_native::update(unsigned char const* buf, size_t len)
36 {
37     switch (bits)
38     {
39       case 256:
40         sph_sha256(&this->ctx256, buf, len);
41         break;
42       case 384:
43         sph_sha384(&this->ctx384, buf, len);
44         break;
45       case 512:
46         sph_sha512(&this->ctx512, buf, len);
47         break;
48       default:
49         badBits();
50         break;
51     }
52 }
53 
54 void
finalize()55 SHA2_native::finalize()
56 {
57     switch (bits)
58     {
59       case 256:
60         sph_sha256_close(&this->ctx256, sha256sum);
61         break;
62       case 384:
63         sph_sha384_close(&this->ctx384, sha384sum);
64         break;
65       case 512:
66         sph_sha512_close(&this->ctx512, sha512sum);
67         break;
68       default:
69         badBits();
70         break;
71     }
72 }
73 
74 std::string
getRawDigest()75 SHA2_native::getRawDigest()
76 {
77     std::string result;
78     switch (bits)
79     {
80       case 256:
81         result = std::string(reinterpret_cast<char*>(this->sha256sum),
82                              sizeof(this->sha256sum));
83         break;
84       case 384:
85         result = std::string(reinterpret_cast<char*>(this->sha384sum),
86                              sizeof(this->sha384sum));
87         break;
88       case 512:
89         result = std::string(reinterpret_cast<char*>(this->sha512sum),
90                              sizeof(this->sha512sum));
91         break;
92       default:
93         badBits();
94         break;
95     }
96     return result;
97 }
98