cmac.h 2.4 KB

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