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.

97 lines
2.3 KiB

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