I am trying to write a code for encryption and decryption input text with RC4
in Java. Does anyone know how to fix it?
My code:
import java.util.Arrays;
public class RC4 {
private static final int SBOX_LEN = 256;
private static final int MIN_KEY_LEN = 5;
private byte[] key = new byte[SBOX_LEN - 1];
private int[] sbox = new int[SBOX_LEN];
public RC4() {
initialize();
}
public RC4(String key) {
this();
setKey(key);
}
public static void main(String[] args) {
RC4 rc4 = new RC4();
byte[] cipherText = rc4.encryptMessage(args[0], args[1]);
System.out.println(Arrays.toString(cipherText));
String plainText = rc4.decryptMessage(cipherText, args[1]);
System.out.println(plainText);
}
private void initialize() {
Arrays.fill(key, (byte) 0);
Arrays.fill(sbox, 0);
}
public byte[] encryptMessage(String message, String key) {
initialize();
setKey(key);
byte[] crypt = crypt(message.getBytes());
initialize();
return crypt;
}
public String decryptMessage(byte[] message, String key) {
initialize();
setKey(key);
byte[] msg = crypt(message);
initialize();
return new String(msg);
}
public byte[] crypt(final byte[] msg) {
sbox = initializeSBox(key);
byte[] code = new byte[msg.length];
int i = 0;
int j = 0;
for (int n = 0; n < msg.length; n++) {
i = (i + 1) % SBOX_LEN;
j = (j + sbox[i]) % SBOX_LEN;
swap(i, j, sbox);
int rand = sbox[(sbox[i] + sbox[j]) % SBOX_LEN];
code[n] = (byte) (rand ^ msg[n]);
}
return code;
}
private int[] initializeSBox(byte[] key) {
int[] sbox = new int[SBOX_LEN];
int j = 0;
for (int i = 0; i < SBOX_LEN; i++) {
sbox[i] = i;
}
for (int i = 0; i < SBOX_LEN; i++) {
j = ((j + sbox[i] + (key[i % key.length])) & 0xFF) % SBOX_LEN;
swap(i, j, sbox);
}
return sbox;
}
private void swap(int i, int j, int[] sbox) {
int temp = sbox[i];
sbox[i] = sbox[j];
sbox[j] = temp;
}
public void setKey(String key) {
if (!((key.length() >= MIN_KEY_LEN) && (key.length() < SBOX_LEN))) {
throw new RuntimeException(String.format("Key length must be between %d and %d", MIN_KEY_LEN, SBOX_LEN - 1));
}
this.key = key.getBytes();
}
}