Crypt.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 net.sf.l2j.gameserver;
  16. import java.nio.ByteBuffer;
  17. /**
  18. * This class ...
  19. *
  20. * @version $Revision: 1.3.4.3 $ $Date: 2005/03/27 15:29:18 $
  21. */
  22. public class Crypt
  23. {
  24. private final byte[] _key = new byte[16];
  25. private boolean _isEnabled;
  26. public void setKey(byte[] key)
  27. {
  28. System.arraycopy(key,0, _key, 0, key.length);
  29. _isEnabled = true;
  30. }
  31. public void decrypt(ByteBuffer buf)
  32. {
  33. if (!_isEnabled)
  34. return;
  35. final int sz = buf.remaining();
  36. int temp = 0;
  37. for (int i = 0; i < sz; i++)
  38. {
  39. int temp2 = buf.get(i);
  40. buf.put(i, (byte)(temp2 ^ _key[i&15] ^ temp));
  41. temp = temp2;
  42. }
  43. int old = _key[8] &0xff;
  44. old |= _key[9] << 8 &0xff00;
  45. old |= _key[10] << 0x10 &0xff0000;
  46. old |= _key[11] << 0x18 &0xff000000;
  47. old += sz;
  48. _key[8] = (byte)(old &0xff);
  49. _key[9] = (byte)(old >> 0x08 &0xff);
  50. _key[10] = (byte)(old >> 0x10 &0xff);
  51. _key[11] = (byte)(old >> 0x18 &0xff);
  52. }
  53. public void encrypt(ByteBuffer buf)
  54. {
  55. if (!_isEnabled)
  56. return;
  57. int temp = 0;
  58. final int sz = buf.remaining();
  59. for (int i = 0; i < sz; i++)
  60. {
  61. int temp2 = buf.get(i);
  62. temp = temp2 ^ _key[i&15] ^ temp;
  63. buf.put(i, (byte) temp);
  64. }
  65. int old = _key[8] &0xff;
  66. old |= _key[9] << 8 &0xff00;
  67. old |= _key[10] << 0x10 &0xff0000;
  68. old |= _key[11] << 0x18 &0xff000000;
  69. old += sz;
  70. _key[8] = (byte)(old &0xff);
  71. _key[9] = (byte)(old >> 0x08 &0xff);
  72. _key[10] = (byte)(old >> 0x10 &0xff);
  73. _key[11] = (byte)(old >> 0x18 &0xff);
  74. }
  75. }