Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.9 KiB

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