1 // crc.h - originally written and placed in the public domain by Wei Dai
2 
3 /// \file crc.h
4 /// \brief Classes for CRC-32 and CRC-32C checksum algorithm
5 
6 #ifndef CRYPTOPP_CRC32_H
7 #define CRYPTOPP_CRC32_H
8 
9 #include "cryptlib.h"
10 
11 NAMESPACE_BEGIN(CryptoPP)
12 
13 const word32 CRC32_NEGL = 0xffffffffL;
14 
15 #if (CRYPTOPP_LITTLE_ENDIAN)
16 #define CRC32_INDEX(c) (c & 0xff)
17 #define CRC32_SHIFTED(c) (c >> 8)
18 #else
19 #define CRC32_INDEX(c) (c >> 24)
20 #define CRC32_SHIFTED(c) (c << 8)
21 #endif
22 
23 /// \brief CRC-32 Checksum Calculation
24 /// \details Uses CRC polynomial 0xEDB88320
25 class CRC32 : public HashTransformation
26 {
27 public:
28 	CRYPTOPP_CONSTANT(DIGESTSIZE = 4);
29 	CRC32();
30 	void Update(const byte *input, size_t length);
31 	void TruncatedFinal(byte *hash, size_t size);
DigestSize()32 	unsigned int DigestSize() const {return DIGESTSIZE;}
StaticAlgorithmName()33     CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CRC32";}
AlgorithmName()34     std::string AlgorithmName() const {return StaticAlgorithmName();}
35 
UpdateByte(byte b)36 	void UpdateByte(byte b) {m_crc = m_tab[CRC32_INDEX(m_crc) ^ b] ^ CRC32_SHIFTED(m_crc);}
GetCrcByte(size_t i)37 	byte GetCrcByte(size_t i) const {return reinterpret_cast<const byte *>(&m_crc)[i];}
38 
39 	std::string AlgorithmProvider() const;
40 
41 protected:
Reset()42 	void Reset() {m_crc = CRC32_NEGL;}
43 
44 private:
45 	static const word32 m_tab[256];
46 	word32 m_crc;
47 };
48 
49 /// \brief CRC-32C Checksum Calculation
50 /// \details Uses CRC polynomial 0x82F63B78
51 /// \since Crypto++ 5.6.4
52 class CRC32C : public HashTransformation
53 {
54 public:
55 	CRYPTOPP_CONSTANT(DIGESTSIZE = 4);
56 	CRC32C();
57 	void Update(const byte *input, size_t length);
58 	void TruncatedFinal(byte *hash, size_t size);
DigestSize()59 	unsigned int DigestSize() const {return DIGESTSIZE;}
StaticAlgorithmName()60     CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CRC32C";}
AlgorithmName()61     std::string AlgorithmName() const {return StaticAlgorithmName();}
62 
UpdateByte(byte b)63 	void UpdateByte(byte b) {m_crc = m_tab[CRC32_INDEX(m_crc) ^ b] ^ CRC32_SHIFTED(m_crc);}
GetCrcByte(size_t i)64 	byte GetCrcByte(size_t i) const {return reinterpret_cast<const byte *>(&m_crc)[i];}
65 
66 	std::string AlgorithmProvider() const;
67 
68 protected:
Reset()69 	void Reset() {m_crc = CRC32_NEGL;}
70 
71 private:
72 	static const word32 m_tab[256];
73 	word32 m_crc;
74 };
75 
76 NAMESPACE_END
77 
78 #endif
79