GameCrypt.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. *
  18. * @author KenM
  19. */
  20. public class GameCrypt
  21. {
  22. private final byte[] _inKey = new byte[16];
  23. private final byte[] _outKey = new byte[16];
  24. private boolean _isEnabled;
  25. public void setKey(byte[] key)
  26. {
  27. System.arraycopy(key, 0, _inKey, 0, 16);
  28. System.arraycopy(key, 0, _outKey, 0, 16);
  29. }
  30. public void decrypt(byte[] raw, final int offset, final int size)
  31. {
  32. if (!_isEnabled)
  33. return;
  34. int temp = 0;
  35. for (int i = 0; i < size; i++)
  36. {
  37. int temp2 = raw[offset+i] & 0xFF;
  38. raw[offset+i] = (byte) (temp2 ^ _inKey[i&15] ^ temp);
  39. temp = temp2;
  40. }
  41. int old = _inKey[8] &0xff;
  42. old |= _inKey[9] << 8 &0xff00;
  43. old |= _inKey[10] << 0x10 &0xff0000;
  44. old |= _inKey[11] << 0x18 &0xff000000;
  45. old += size;
  46. _inKey[8] = (byte)(old &0xff);
  47. _inKey[9] = (byte)(old >> 0x08 &0xff);
  48. _inKey[10] = (byte)(old >> 0x10 &0xff);
  49. _inKey[11] = (byte)(old >> 0x18 &0xff);
  50. }
  51. public void encrypt(byte[] raw, final int offset, final int size)
  52. {
  53. if (!_isEnabled)
  54. {
  55. _isEnabled = true;
  56. return;
  57. }
  58. int temp = 0;
  59. for (int i = 0; i < size; i++)
  60. {
  61. int temp2 = raw[offset+i] & 0xFF;
  62. temp = temp2 ^ _outKey[i&15] ^ temp;
  63. raw[offset+i] = (byte) temp;
  64. }
  65. int old = _outKey[8] &0xff;
  66. old |= _outKey[9] << 8 &0xff00;
  67. old |= _outKey[10] << 0x10 &0xff0000;
  68. old |= _outKey[11] << 0x18 &0xff000000;
  69. old += size;
  70. _outKey[8] = (byte)(old &0xff);
  71. _outKey[9] = (byte)(old >> 0x08 &0xff);
  72. _outKey[10] = (byte)(old >> 0x10 &0xff);
  73. _outKey[11] = (byte)(old >> 0x18 &0xff);
  74. }
  75. }