Botan 3.13.0
Crypto and TLS for C&
crc32.cpp
Go to the documentation of this file.
1/*
2* CRC32
3* (C) 1999-2007 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/internal/crc32.h>
9
10#include <botan/internal/loadstor.h>
11#include <array>
12
13namespace Botan {
14
15namespace {
16
17// Sarwate's byte-at-a-time table for the reflected CRC32 polynomial
18consteval std::array<uint32_t, 256> crc32_table() noexcept {
19 std::array<uint32_t, 256> table = {};
20 for(size_t i = 0; i != 256; ++i) {
21 uint32_t crc = static_cast<uint32_t>(i);
22 for(size_t j = 0; j != 8; ++j) {
23 crc = (crc >> 1) ^ ((crc & 1) != 0 ? 0xEDB88320 : 0);
24 }
25 table[i] = crc;
26 }
27 return table;
28}
29
30alignas(256) constexpr auto CRC32_T0 = crc32_table();
31
32} // namespace
33
34/*
35* Update a CRC32 Checksum
36*/
37void CRC32::add_data(std::span<const uint8_t> input) {
38 uint32_t crc = m_crc;
39 for(; input.size() >= 16; input = input.last(input.size() - 16)) {
40 crc = CRC32_T0[(crc ^ input[0]) & 0xFF] ^ (crc >> 8);
41 crc = CRC32_T0[(crc ^ input[1]) & 0xFF] ^ (crc >> 8);
42 crc = CRC32_T0[(crc ^ input[2]) & 0xFF] ^ (crc >> 8);
43 crc = CRC32_T0[(crc ^ input[3]) & 0xFF] ^ (crc >> 8);
44 crc = CRC32_T0[(crc ^ input[4]) & 0xFF] ^ (crc >> 8);
45 crc = CRC32_T0[(crc ^ input[5]) & 0xFF] ^ (crc >> 8);
46 crc = CRC32_T0[(crc ^ input[6]) & 0xFF] ^ (crc >> 8);
47 crc = CRC32_T0[(crc ^ input[7]) & 0xFF] ^ (crc >> 8);
48 crc = CRC32_T0[(crc ^ input[8]) & 0xFF] ^ (crc >> 8);
49 crc = CRC32_T0[(crc ^ input[9]) & 0xFF] ^ (crc >> 8);
50 crc = CRC32_T0[(crc ^ input[10]) & 0xFF] ^ (crc >> 8);
51 crc = CRC32_T0[(crc ^ input[11]) & 0xFF] ^ (crc >> 8);
52 crc = CRC32_T0[(crc ^ input[12]) & 0xFF] ^ (crc >> 8);
53 crc = CRC32_T0[(crc ^ input[13]) & 0xFF] ^ (crc >> 8);
54 crc = CRC32_T0[(crc ^ input[14]) & 0xFF] ^ (crc >> 8);
55 crc = CRC32_T0[(crc ^ input[15]) & 0xFF] ^ (crc >> 8);
56 }
57
58 for(const uint8_t b : input) {
59 crc = CRC32_T0[(crc ^ b) & 0xFF] ^ (crc >> 8);
60 }
61
62 m_crc = crc;
63}
64
65/*
66* Finalize a CRC32 Checksum
67*/
68void CRC32::final_result(std::span<uint8_t> output) {
69 m_crc ^= 0xFFFFFFFF;
70 store_be(m_crc, output.data());
71 clear();
72}
73
74std::unique_ptr<HashFunction> CRC32::copy_state() const {
75 return std::make_unique<CRC32>(*this);
76}
77
78} // namespace Botan
void clear() override
Definition crc32.h:30
std::unique_ptr< HashFunction > copy_state() const override
Definition crc32.cpp:74
constexpr auto store_be(ParamTs &&... params)
Definition loadstor.h:745