Crypto++ 8.2 Free C++ class library of cryptographic schemes

rc5.cpp
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
8 NAMESPACE_BEGIN(CryptoPP)
9
10 void RC5::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+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
42 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
61 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
misc.h
Utility functions for the Crypto++ library.
rc5.h
Classes for the RC5 block cipher.
SecBlock< RC5_WORD >
BlockGetAndPut
Access a block of memory.
Definition: misc.h:2587
LITTLE_ENDIAN_ORDER
byte order is little-endian
Definition: cryptlib.h:145
secblock.h
Classes and functions for secure memory allocations.
pch.h
Precompiled header file.
STDMAX
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:646
PutBlock
Access a block of memory.
Definition: misc.h:2550
CryptoPP
Crypto++ library namespace.
rotlMod
T rotlMod(T x, unsigned int y)
Performs a left rotate.
Definition: misc.h:1665
rotrMod
T rotrMod(T x, unsigned int y)
Performs a right rotate.
Definition: misc.h:1681
NameValuePairs
Interface for retrieving values given their names.
Definition: cryptlib.h:321