Crypto++
rc6.cpp
1 // rc6.cpp - written and placed in the public domain by Sean Woods
2 // based on Wei Dai's RC5 code.
3 
4 #include "pch.h"
5 #include "rc6.h"
6 #include "misc.h"
7 
8 NAMESPACE_BEGIN(CryptoPP)
9 
10 void RC6::Base::UncheckedSetKey(const byte *k, unsigned int keylen, const NameValuePairs &params)
11 {
12  AssertValidKeyLength(keylen);
13 
14  r = GetRoundsAndThrowIfInvalid(params, this);
15  sTable.New(2*(r+2));
16 
17  static const RC6_WORD MAGIC_P = 0xb7e15163L; // magic constant P for wordsize
18  static const RC6_WORD MAGIC_Q = 0x9e3779b9L; // magic constant Q for wordsize
19  static const int U=sizeof(RC6_WORD);
20 
21  const unsigned int c = STDMAX((keylen+U-1)/U, 1U); // RC6 paper says c=1 if keylen==0
22  SecBlock<RC6_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  RC6_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()] = rotlFixed((sTable[h % sTable.size()] + a + b), 3);
36  b = l[h % c] = rotlMod((l[h % c] + a + b), (a+b));
37  }
38 }
39 
41 
42 void RC6::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
43 {
44  const RC6_WORD *sptr = sTable;
45  RC6_WORD a, b, c, d, t, u;
46 
47  Block::Get(inBlock)(a)(b)(c)(d);
48  b += sptr[0];
49  d += sptr[1];
50  sptr += 2;
51 
52  for(unsigned i=0; i<r; i++)
53  {
54  t = rotlFixed(b*(2*b+1), 5);
55  u = rotlFixed(d*(2*d+1), 5);
56  a = rotlMod(a^t,u) + sptr[0];
57  c = rotlMod(c^u,t) + sptr[1];
58  t = a; a = b; b = c; c = d; d = t;
59  sptr += 2;
60  }
61 
62  a += sptr[0];
63  c += sptr[1];
64 
65  Block::Put(xorBlock, outBlock)(a)(b)(c)(d);
66 }
67 
68 void RC6::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
69 {
70  const RC6_WORD *sptr = sTable.end();
71  RC6_WORD a, b, c, d, t, u;
72 
73  Block::Get(inBlock)(a)(b)(c)(d);
74 
75  sptr -= 2;
76  c -= sptr[1];
77  a -= sptr[0];
78 
79  for (unsigned i=0; i < r; i++)
80  {
81  sptr -= 2;
82  t = a; a = d; d = c; c = b; b = t;
83  u = rotlFixed(d*(2*d+1), 5);
84  t = rotlFixed(b*(2*b+1), 5);
85  c = rotrMod(c-sptr[1], t) ^ u;
86  a = rotrMod(a-sptr[0], u) ^ t;
87  }
88 
89  sptr -= 2;
90  d -= sTable[1];
91  b -= sTable[0];
92 
93  Block::Put(xorBlock, outBlock)(a)(b)(c)(d);
94 }
95 
96 NAMESPACE_END
RC6
Definition: rc6.h:20
interface for retrieving values given their names
Definition: cryptlib.h:225