1 // mdc.h - written and placed in the public domain by Wei Dai
2
3#ifndef CRYPTOPP_MDC_H
4#define CRYPTOPP_MDC_H
5
6/** \file
7*/
8
9#include "seckey.h"
10#include "misc.h"
11
12NAMESPACE_BEGIN(CryptoPP)
13
14//! _
15template <class T>
16struct MDC_Info : public FixedBlockSize<T::DIGESTSIZE>, public FixedKeyLength<T::BLOCKSIZE>
17{
18	static std::string StaticAlgorithmName() {return std::string("MDC/")+T::StaticAlgorithmName();}
19};
20
21//! <a href="http://www.weidai.com/scan-mirror/cs.html#MDC">MDC</a>
22/*! a construction by Peter Gutmann to turn an iterated hash function into a PRF */
23template <class T>
24class MDC : public MDC_Info<T>
25{
26	class CRYPTOPP_NO_VTABLE Enc : public BlockCipherImpl<MDC_Info<T> >
27	{
28		typedef typename T::HashWordType HashWordType;
29
30	public:
31		void UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs &params)
32		{
33			this->AssertValidKeyLength(length);
34			memcpy_s(m_key, m_key.size(), userKey, this->KEYLENGTH);
35			T::CorrectEndianess(Key(), Key(), this->KEYLENGTH);
36		}
37
38		void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
39		{
40			T::CorrectEndianess(Buffer(), (HashWordType *)inBlock, this->BLOCKSIZE);
41			T::Transform(Buffer(), Key());
42			if (xorBlock)
43			{
44				T::CorrectEndianess(Buffer(), Buffer(), this->BLOCKSIZE);
45				xorbuf(outBlock, xorBlock, m_buffer, this->BLOCKSIZE);
46			}
47			else
48				T::CorrectEndianess((HashWordType *)outBlock, Buffer(), this->BLOCKSIZE);
49		}
50
51		bool IsPermutation() const {return false;}
52
53		unsigned int OptimalDataAlignment() const {return sizeof(HashWordType);}
54
55	private:
56		HashWordType *Key() {return (HashWordType *)m_key.data();}
57		const HashWordType *Key() const {return (const HashWordType *)m_key.data();}
58		HashWordType *Buffer() const {return (HashWordType *)m_buffer.data();}
59
60		// VC60 workaround: bug triggered if using FixedSizeAllocatorWithCleanup
61		FixedSizeSecBlock<byte, MDC_Info<T>::KEYLENGTH, AllocatorWithCleanup<byte> > m_key;
62		mutable FixedSizeSecBlock<byte, MDC_Info<T>::BLOCKSIZE, AllocatorWithCleanup<byte> > m_buffer;
63	};
64
65public:
66	//! use BlockCipher interface
67	typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
68};
69
70NAMESPACE_END
71
72#endif
73