Coverage Report

Created: 2025-08-26 07:13

/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
6.33M
    Pipeline("sha2", next)
10
6.33M
{
11
6.33M
    if (bits) {
12
6.33M
        resetBits(bits);
13
6.33M
    }
14
6.33M
}
15
16
void
17
Pl_SHA2::write(unsigned char const* buf, size_t len)
18
6.51M
{
19
6.51M
    if (!in_progress) {
20
6.33M
        in_progress = true;
21
6.33M
    }
22
23
    // Write in chunks in case len is too big to fit in an int. Assume int is at least 32 bits.
24
6.51M
    static size_t const max_bytes = 1 << 30;
25
6.51M
    size_t bytes_left = len;
26
6.51M
    unsigned char const* data = buf;
27
12.9M
    while (bytes_left > 0) {
28
6.44M
        size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left);
29
6.44M
        crypto->SHA2_update(data, bytes);
30
6.44M
        bytes_left -= bytes;
31
6.44M
        data += bytes;
32
6.44M
    }
33
34
6.51M
    if (next()) {
35
0
        next()->write(buf, len);
36
0
    }
37
6.51M
}
38
39
void
40
Pl_SHA2::finish()
41
6.33M
{
42
6.33M
    if (next()) {
43
0
        next()->finish();
44
0
    }
45
6.33M
    crypto->SHA2_finalize();
46
6.33M
    in_progress = false;
47
6.33M
}
48
49
void
50
Pl_SHA2::resetBits(int bits)
51
6.33M
{
52
6.33M
    if (in_progress) {
53
0
        throw std::logic_error("bit reset requested for in-progress SHA2 Pipeline");
54
0
    }
55
6.33M
    crypto = QPDFCryptoProvider::getImpl();
56
6.33M
    crypto->SHA2_init(bits);
57
6.33M
}
58
59
std::string
60
Pl_SHA2::getRawDigest()
61
6.33M
{
62
6.33M
    if (in_progress) {
63
0
        throw std::logic_error("digest requested for in-progress SHA2 Pipeline");
64
0
    }
65
6.33M
    return crypto->SHA2_digest();
66
6.33M
}
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
}