rc5.cpp

00001 // rc5.cpp - written and placed in the public domain by Wei Dai
00002 
00003 #include "pch.h"
00004 #include "rc5.h"
00005 #include "misc.h"
00006 
00007 NAMESPACE_BEGIN(CryptoPP)
00008 
00009 void RC5::Base::UncheckedSetKey(const byte *k, unsigned int keylen, const NameValuePairs &params)
00010 {
00011         AssertValidKeyLength(keylen);
00012 
00013         r = GetRoundsAndThrowIfInvalid(params, this);
00014         sTable.New(2*(r+1));
00015 
00016         static const RC5_WORD MAGIC_P = 0xb7e15163L;    // magic constant P for wordsize
00017         static const RC5_WORD MAGIC_Q = 0x9e3779b9L;    // magic constant Q for wordsize
00018         static const int U=sizeof(RC5_WORD);
00019 
00020         const unsigned int c = STDMAX((keylen+U-1)/U, 1U);      // RC6 paper says c=1 if keylen==0
00021         SecBlock<RC5_WORD> l(c);
00022 
00023         GetUserKey(LITTLE_ENDIAN_ORDER, l.begin(), c, k, keylen);
00024 
00025         sTable[0] = MAGIC_P;
00026         for (unsigned j=1; j<sTable.size();j++)
00027                 sTable[j] = sTable[j-1] + MAGIC_Q;
00028 
00029         RC5_WORD a=0, b=0;
00030         const unsigned n = 3*STDMAX((unsigned int)sTable.size(), c);
00031 
00032         for (unsigned h=0; h < n; h++)
00033         {
00034                 a = sTable[h % sTable.size()] = rotlFixed((sTable[h % sTable.size()] + a + b), 3);
00035                 b = l[h % c] = rotlMod((l[h % c] + a + b), (a+b));
00036         }
00037 }
00038 
00039 typedef BlockGetAndPut<RC5::RC5_WORD, LittleEndian> Block;
00040 
00041 void RC5::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
00042 {
00043         const RC5_WORD *sptr = sTable;
00044         RC5_WORD a, b;
00045 
00046         Block::Get(inBlock)(a)(b);
00047         a += sptr[0];
00048         b += sptr[1];
00049         sptr += 2;
00050 
00051         for(unsigned i=0; i<r; i++)
00052         {
00053                 a = rotlMod(a^b,b) + sptr[2*i+0];
00054                 b = rotlMod(a^b,a) + sptr[2*i+1];
00055         }
00056 
00057         Block::Put(xorBlock, outBlock)(a)(b);
00058 }
00059 
00060 void RC5::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
00061 {
00062         const RC5_WORD *sptr = sTable.end();
00063         RC5_WORD a, b;
00064 
00065         Block::Get(inBlock)(a)(b);
00066 
00067         for (unsigned i=0; i<r; i++)
00068         {
00069                 sptr-=2;
00070                 b = rotrMod(b-sptr[1], a) ^ a;
00071                 a = rotrMod(a-sptr[0], b) ^ b;
00072         }
00073         b -= sTable[1];
00074         a -= sTable[0];
00075 
00076         Block::Put(xorBlock, outBlock)(a)(b);
00077 }
00078 
00079 NAMESPACE_END

Generated on Sat Dec 23 02:07:09 2006 for Crypto++ by  doxygen 1.5.1-p1