Coverage Report

Created: 2025-07-14 06:20

/src/qpdf/libqpdf/Pl_SHA2.cc
Line
Count
Source (jump to first uncovered line)
1
#include <qpdf/Pl_SHA2.hh>
2
3
#include <qpdf/QPDFCryptoProvider.hh>
4
#include <qpdf/QUtil.hh>
5
6
#include <stdexcept>
7
8
Pl_SHA2::Pl_SHA2(int bits, Pipeline* next) :
9
5.74M
    Pipeline("sha2", next)
10
5.74M
{
11
5.74M
    if (bits) {
12
5.74M
        resetBits(bits);
13
5.74M
    }
14
5.74M
}
15
16
void
17
Pl_SHA2::write(unsigned char const* buf, size_t len)
18
5.90M
{
19
5.90M
    if (!in_progress) {
20
5.74M
        in_progress = true;
21
5.74M
    }
22
23
    // Write in chunks in case len is too big to fit in an int. Assume int is at least 32 bits.
24
5.90M
    static size_t const max_bytes = 1 << 30;
25
5.90M
    size_t bytes_left = len;
26
5.90M
    unsigned char const* data = buf;
27
11.7M
    while (bytes_left > 0) {
28
5.84M
        size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left);
29
5.84M
        crypto->SHA2_update(data, bytes);
30
5.84M
        bytes_left -= bytes;
31
5.84M
        data += bytes;
32
5.84M
    }
33
34
5.90M
    if (next()) {
35
0
        next()->write(buf, len);
36
0
    }
37
5.90M
}
38
39
void
40
Pl_SHA2::finish()
41
5.74M
{
42
5.74M
    if (next()) {
43
0
        next()->finish();
44
0
    }
45
5.74M
    crypto->SHA2_finalize();
46
5.74M
    in_progress = false;
47
5.74M
}
48
49
void
50
Pl_SHA2::resetBits(int bits)
51
5.74M
{
52
5.74M
    if (in_progress) {
53
0
        throw std::logic_error("bit reset requested for in-progress SHA2 Pipeline");
54
0
    }
55
5.74M
    crypto = QPDFCryptoProvider::getImpl();
56
5.74M
    crypto->SHA2_init(bits);
57
5.74M
}
58
59
std::string
60
Pl_SHA2::getRawDigest()
61
5.74M
{
62
5.74M
    if (in_progress) {
63
0
        throw std::logic_error("digest requested for in-progress SHA2 Pipeline");
64
0
    }
65
5.74M
    return crypto->SHA2_digest();
66
5.74M
}
67
68
std::string
69
Pl_SHA2::getHexDigest()
70
0
{
71
0
    if (in_progress) {
72
0
        throw std::logic_error("digest requested for in-progress SHA2 Pipeline");
73
0
    }
74
0
    return QUtil::hex_encode(getRawDigest());
75
0
}