1 // cmac.h - originally written and placed in the public domain by Wei Dai
2 
3 /// \file cmac.h
4 /// \brief Classes for CMAC message authentication code
5 /// \since Crypto++ 5.6.0
6 
7 #ifndef CRYPTOPP_CMAC_H
8 #define CRYPTOPP_CMAC_H
9 
10 #include "seckey.h"
11 #include "secblock.h"
12 
13 /// \brief Enable CMAC and wide block ciphers
14 /// \details CMAC is only defined for AES. The library can support wide
15 ///  block ciphers like Kaylna and Threefish since we know the polynomials.
16 #ifndef CRYPTOPP_CMAC_WIDE_BLOCK_CIPHERS
17 # define CRYPTOPP_CMAC_WIDE_BLOCK_CIPHERS 1
18 #endif  // CRYPTOPP_CMAC_WIDE_BLOCK_CIPHERS
19 
NAMESPACE_BEGIN(CryptoPP)20 NAMESPACE_BEGIN(CryptoPP)
21 
22 /// \brief CMAC base implementation
23 /// \since Crypto++ 5.6.0
24 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CMAC_Base : public MessageAuthenticationCode
25 {
26 public:
27 
28 	virtual ~CMAC_Base() {}
29 	CMAC_Base() : m_counter(0) {}
30 
31 	void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params);
32 	void Update(const byte *input, size_t length);
33 	void TruncatedFinal(byte *mac, size_t size);
34 	unsigned int DigestSize() const {return GetCipher().BlockSize();}
35 	unsigned int OptimalBlockSize() const {return GetCipher().BlockSize();}
36 	unsigned int OptimalDataAlignment() const {return GetCipher().OptimalDataAlignment();}
37 	std::string AlgorithmProvider() const {return GetCipher().AlgorithmProvider();}
38 
39 protected:
40 	friend class EAX_Base;
41 
42 	const BlockCipher & GetCipher() const {return const_cast<CMAC_Base*>(this)->AccessCipher();}
43 	virtual BlockCipher & AccessCipher() =0;
44 
45 	void ProcessBuf();
46 	SecByteBlock m_reg;
47 	unsigned int m_counter;
48 };
49 
50 /// \brief CMAC message authentication code
51 /// \tparam T block cipher
52 /// \details Template parameter T should be a class derived from BlockCipherDocumentation, for example AES, with a block size of 8, 16, or 32.
53 /// \sa <a href="http://www.cryptolounge.org/wiki/CMAC">CMAC</a>
54 /// \since Crypto++ 5.6.0
55 template <class T>
56 class CMAC : public MessageAuthenticationCodeImpl<CMAC_Base, CMAC<T> >, public SameKeyLengthAs<T>
57 {
58 public:
59 	/// \brief Construct a CMAC
CMAC()60 	CMAC() {}
61 	/// \brief Construct a CMAC
62 	/// \param key the MAC key
63 	/// \param length the key size, in bytes
64 	CMAC(const byte *key, size_t length=SameKeyLengthAs<T>::DEFAULT_KEYLENGTH)
65 		{this->SetKey(key, length);}
66 
StaticAlgorithmName()67 	static std::string StaticAlgorithmName() {return std::string("CMAC(") + T::StaticAlgorithmName() + ")";}
68 
69 private:
AccessCipher()70 	BlockCipher & AccessCipher() {return m_cipher;}
71 	typename T::Encryption m_cipher;
72 };
73 
74 NAMESPACE_END
75 
76 #endif
77