GameCrypt.java 2.4 KB

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