GameCrypt.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.gameserver.network;
  16. /**
  17. * @author KenM
  18. */
  19. public class GameCrypt
  20. {
  21. private final byte[] _inKey = new byte[16];
  22. private final byte[] _outKey = new byte[16];
  23. private boolean _isEnabled;
  24. public void setKey(byte[] key)
  25. {
  26. System.arraycopy(key, 0, _inKey, 0, 16);
  27. System.arraycopy(key, 0, _outKey, 0, 16);
  28. }
  29. public void decrypt(byte[] raw, final int offset, final int size)
  30. {
  31. if (!_isEnabled)
  32. {
  33. return;
  34. }
  35. int temp = 0;
  36. for (int i = 0; i < size; i++)
  37. {
  38. int temp2 = raw[offset + i] & 0xFF;
  39. raw[offset + i] = (byte) (temp2 ^ _inKey[i & 15] ^ temp);
  40. temp = temp2;
  41. }
  42. int old = _inKey[8] & 0xff;
  43. old |= (_inKey[9] << 8) & 0xff00;
  44. old |= (_inKey[10] << 0x10) & 0xff0000;
  45. old |= (_inKey[11] << 0x18) & 0xff000000;
  46. old += size;
  47. _inKey[8] = (byte) (old & 0xff);
  48. _inKey[9] = (byte) ((old >> 0x08) & 0xff);
  49. _inKey[10] = (byte) ((old >> 0x10) & 0xff);
  50. _inKey[11] = (byte) ((old >> 0x18) & 0xff);
  51. }
  52. public void encrypt(byte[] raw, final int offset, final int size)
  53. {
  54. if (!_isEnabled)
  55. {
  56. _isEnabled = true;
  57. return;
  58. }
  59. int temp = 0;
  60. for (int i = 0; i < size; i++)
  61. {
  62. int temp2 = raw[offset + i] & 0xFF;
  63. temp = temp2 ^ _outKey[i & 15] ^ temp;
  64. raw[offset + i] = (byte) temp;
  65. }
  66. int old = _outKey[8] & 0xff;
  67. old |= (_outKey[9] << 8) & 0xff00;
  68. old |= (_outKey[10] << 0x10) & 0xff0000;
  69. old |= (_outKey[11] << 0x18) & 0xff000000;
  70. old += size;
  71. _outKey[8] = (byte) (old & 0xff);
  72. _outKey[9] = (byte) ((old >> 0x08) & 0xff);
  73. _outKey[10] = (byte) ((old >> 0x10) & 0xff);
  74. _outKey[11] = (byte) ((old >> 0x18) & 0xff);
  75. }
  76. }