aboutsummaryrefslogtreecommitdiffstats
path: root/libqpdf/Pl_SHA2.cc
blob: 04ef924c492ab71d86c6c8f4cac463489d17b35c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <qpdf/Pl_SHA2.hh>

#include <qpdf/QPDFCryptoProvider.hh>
#include <qpdf/QUtil.hh>
#include <stdexcept>

Pl_SHA2::Pl_SHA2(int bits, Pipeline* next) :
    Pipeline("sha2", next),
    in_progress(false)
{
    if (bits) {
        resetBits(bits);
    }
}

void
Pl_SHA2::write(unsigned char const* buf, size_t len)
{
    if (!this->in_progress) {
        this->in_progress = true;
    }

    // Write in chunks in case len is too big to fit in an int. Assume int is at least 32 bits.
    static size_t const max_bytes = 1 << 30;
    size_t bytes_left = len;
    unsigned char const* data = buf;
    while (bytes_left > 0) {
        size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left);
        this->crypto->SHA2_update(data, bytes);
        bytes_left -= bytes;
        data += bytes;
    }

    if (this->getNext(true)) {
        this->getNext()->write(buf, len);
    }
}

void
Pl_SHA2::finish()
{
    if (this->getNext(true)) {
        this->getNext()->finish();
    }
    this->crypto->SHA2_finalize();
    this->in_progress = false;
}

void
Pl_SHA2::resetBits(int bits)
{
    if (this->in_progress) {
        throw std::logic_error("bit reset requested for in-progress SHA2 Pipeline");
    }
    this->crypto = QPDFCryptoProvider::getImpl();
    this->crypto->SHA2_init(bits);
}

std::string
Pl_SHA2::getRawDigest()
{
    if (this->in_progress) {
        throw std::logic_error("digest requested for in-progress SHA2 Pipeline");
    }
    return this->crypto->SHA2_digest();
}

std::string
Pl_SHA2::getHexDigest()
{
    if (this->in_progress) {
        throw std::logic_error("digest requested for in-progress SHA2 Pipeline");
    }
    return QUtil::hex_encode(getRawDigest());
}