Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. public class RC4 {
  2. private final byte[] S = new byte[256];
  3. private final byte[] T = new byte[256];
  4. private final int keylen;
  5.  
  6. public RC4(final byte[] key) {
  7. if (key.length < 1 || key.length > 256) {
  8. throw new IllegalArgumentException(
  9. "key must be between 1 and 256 bytes");
  10. } else {
  11. keylen = key.length;
  12. for (int i = 0; i < 256; i++) {
  13. S[i] = (byte) i;
  14. T[i] = key[i % keylen];
  15. }
  16. int j = 0;
  17. for (int i = 0; i < 256; i++) {
  18. j = (j + S[i] + T[i]) & 0xFF;
  19. byte temp = S[i];
  20. S[i] = S[j];
  21. S[j] = temp;
  22. }
  23. }
  24. }
  25.  
  26. public byte[] encrypt(final byte[] plaintext) {
  27. final byte[] ciphertext = new byte[plaintext.length];
  28. int i = 0, j = 0, k, t;
  29. for (int counter = 0; counter < plaintext.length; counter++) {
  30. i = (i + 1) & 0xFF;
  31. j = (j + S[i]) & 0xFF;
  32. byte temp = S[i];
  33. S[i] = S[j];
  34. S[j] = temp;
  35. t = (S[i] + S[j]) & 0xFF;
  36. k = S[t];
  37. ciphertext[counter] = (byte) (plaintext[counter] ^ k);
  38. }
  39. return ciphertext;
  40. }
  41.  
  42. public byte[] decrypt(final byte[] ciphertext) {
  43. return encrypt(ciphertext);
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement