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