Counter Strike : Global Offensive Source Code
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.

99 lines
2.2 KiB

  1. // blowfish.cpp - written and placed in the public domain by Wei Dai
  2. #include "pch.h"
  3. #include "blowfish.h"
  4. #include "misc.h"
  5. NAMESPACE_BEGIN(CryptoPP)
  6. void Blowfish::Base::UncheckedSetKey(const byte *key_string, unsigned int keylength, const NameValuePairs &)
  7. {
  8. AssertValidKeyLength(keylength);
  9. unsigned i, j=0, k;
  10. word32 data, dspace[2] = {0, 0};
  11. memcpy(pbox, p_init, sizeof(p_init));
  12. memcpy(sbox, s_init, sizeof(s_init));
  13. // Xor key string into encryption key vector
  14. for (i=0 ; i<ROUNDS+2 ; ++i)
  15. {
  16. data = 0 ;
  17. for (k=0 ; k<4 ; ++k )
  18. data = (data << 8) | key_string[j++ % keylength];
  19. pbox[i] ^= data;
  20. }
  21. crypt_block(dspace, pbox);
  22. for (i=0; i<ROUNDS; i+=2)
  23. crypt_block(pbox+i, pbox+i+2);
  24. crypt_block(pbox+ROUNDS, sbox);
  25. for (i=0; i<4*256-2; i+=2)
  26. crypt_block(sbox+i, sbox+i+2);
  27. if (!IsForwardTransformation())
  28. for (i=0; i<(ROUNDS+2)/2; i++)
  29. std::swap(pbox[i], pbox[ROUNDS+1-i]);
  30. }
  31. // this version is only used to make pbox and sbox
  32. void Blowfish::Base::crypt_block(const word32 in[2], word32 out[2]) const
  33. {
  34. word32 left = in[0];
  35. word32 right = in[1];
  36. const word32 *const s=sbox;
  37. const word32 *p=pbox;
  38. left ^= p[0];
  39. for (unsigned i=0; i<ROUNDS/2; i++)
  40. {
  41. right ^= (((s[GETBYTE(left,3)] + s[256+GETBYTE(left,2)])
  42. ^ s[2*256+GETBYTE(left,1)]) + s[3*256+GETBYTE(left,0)])
  43. ^ p[2*i+1];
  44. left ^= (((s[GETBYTE(right,3)] + s[256+GETBYTE(right,2)])
  45. ^ s[2*256+GETBYTE(right,1)]) + s[3*256+GETBYTE(right,0)])
  46. ^ p[2*i+2];
  47. }
  48. right ^= p[ROUNDS+1];
  49. out[0] = right;
  50. out[1] = left;
  51. }
  52. void Blowfish::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
  53. {
  54. typedef BlockGetAndPut<word32, BigEndian> Block;
  55. word32 left, right;
  56. Block::Get(inBlock)(left)(right);
  57. const word32 *const s=sbox;
  58. const word32 *p=pbox;
  59. left ^= p[0];
  60. for (unsigned i=0; i<ROUNDS/2; i++)
  61. {
  62. right ^= (((s[GETBYTE(left,3)] + s[256+GETBYTE(left,2)])
  63. ^ s[2*256+GETBYTE(left,1)]) + s[3*256+GETBYTE(left,0)])
  64. ^ p[2*i+1];
  65. left ^= (((s[GETBYTE(right,3)] + s[256+GETBYTE(right,2)])
  66. ^ s[2*256+GETBYTE(right,1)]) + s[3*256+GETBYTE(right,0)])
  67. ^ p[2*i+2];
  68. }
  69. right ^= p[ROUNDS+1];
  70. Block::Put(xorBlock, outBlock)(right)(left);
  71. }
  72. NAMESPACE_END