1 // rc5.cpp - originally written and placed in the public domain by Wei Dai
2
3 #include "pch.h"
4 #include "rc5.h"
5 #include "misc.h"
6 #include "secblock.h"
7
NAMESPACE_BEGIN(CryptoPP)8 NAMESPACE_BEGIN(CryptoPP)
9
10 void RC5::Base::UncheckedSetKey(const byte *k, unsigned int keylen, const NameValuePairs ¶ms)
11 {
12 AssertValidKeyLength(keylen);
13
14 r = GetRoundsAndThrowIfInvalid(params, this);
15 sTable.New(2*(r+1));
16
17 static const RC5_WORD MAGIC_P = 0xb7e15163L; // magic constant P for wordsize
18 static const RC5_WORD MAGIC_Q = 0x9e3779b9L; // magic constant Q for wordsize
19 static const int U=sizeof(RC5_WORD);
20
21 const unsigned int c = STDMAX((keylen+U-1)/U, 1U); // RC6 paper says c=1 if keylen==0
22 SecBlock<RC5_WORD> l(c);
23
24 GetUserKey(LITTLE_ENDIAN_ORDER, l.begin(), c, k, keylen);
25
26 sTable[0] = MAGIC_P;
27 for (unsigned j=1; j<sTable.size();j++)
28 sTable[j] = sTable[j-1] + MAGIC_Q;
29
30 RC5_WORD a=0, b=0;
31 const unsigned n = 3*STDMAX((unsigned int)sTable.size(), c);
32
33 for (unsigned h=0; h < n; h++)
34 {
35 a = sTable[h % sTable.size()] = rotlConstant<3>((sTable[h % sTable.size()] + a + b));
36 b = l[h % c] = rotlMod((l[h % c] + a + b), (a+b));
37 }
38 }
39
40 typedef BlockGetAndPut<RC5::RC5_WORD, LittleEndian> Block;
41
ProcessAndXorBlock(const byte * inBlock,const byte * xorBlock,byte * outBlock) const42 void RC5::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
43 {
44 const RC5_WORD *sptr = sTable;
45 RC5_WORD a, b;
46
47 Block::Get(inBlock)(a)(b);
48 a += sptr[0];
49 b += sptr[1];
50 sptr += 2;
51
52 for(unsigned i=0; i<r; i++)
53 {
54 a = rotlMod(a^b,b) + sptr[2*i+0];
55 b = rotlMod(a^b,a) + sptr[2*i+1];
56 }
57
58 Block::Put(xorBlock, outBlock)(a)(b);
59 }
60
ProcessAndXorBlock(const byte * inBlock,const byte * xorBlock,byte * outBlock) const61 void RC5::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
62 {
63 const RC5_WORD *sptr = sTable.end();
64 RC5_WORD a, b;
65
66 Block::Get(inBlock)(a)(b);
67
68 for (unsigned i=0; i<r; i++)
69 {
70 sptr-=2;
71 b = rotrMod(b-sptr[1], a) ^ a;
72 a = rotrMod(a-sptr[0], b) ^ b;
73 }
74 b -= sTable[1];
75 a -= sTable[0];
76
77 Block::Put(xorBlock, outBlock)(a)(b);
78 }
79
80 NAMESPACE_END
81