Modify the code below so that it can encrypt the following message:
Cryptography is a method of protecting information and communications through the use of codes so that only those for whom the information is intended can read and process it.
Instead of using stream length 256, we will use length 26. When encrypting, let A = 0 to Z = 25 (hence CODES = [2 14 3 4 18]). Ignore spaces and punctuations and put the message in groups of five letters.
public class RC4 {
private final byte[] S = new byte[256];
private final byte[] T = new byte[256];
private final int keylen;
public RC4(final byte[] key) {
if (key.length < 1 || key.length > 256) {
throw new IllegalArgumentException(
"key must be between 1 and 256 bytes");
} else {
keylen = key.length;
for (int i = 0; i < 256; i++) {
S[i] = (byte) i;
T[i] = key[i % keylen];
}
int j = 0;
byte tmp;
for (int i = 0; i < 256; i++) {
j = (j + S[i] + T[i]) & 0xFF;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
}
}
}
public byte[] encrypt(final byte[] plaintext) {
final byte[] ciphertext = new byte[plaintext.length];
int i = 0, j = 0, k, t;
byte tmp;
for (int counter = 0; counter < plaintext.length; counter++)
{
i = (i + 1) & 0xFF;
j = (j + S[i]) & 0xFF;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
t = (S[i] + S[j]) & 0xFF;
k = S[t];
ciphertext[counter] = (byte) (plaintext[counter] ^ k);
}
return ciphertext;
}
public byte[] decrypt(final byte[] ciphertext) {
return encrypt(ciphertext);
}
}
Here is the required modified code:-
public class RC4
{
private final byte[] S = new byte[26];
private final byte[] T = new byte[26];
private final int keylen;
public RC4(final byte[] key) {
if (key.length < 1 || key.length > 26) {
throw new IllegalArgumentException(
"key must be between 1 and 26 bytes");
} else {
keylen = key.length;
for (int i = 0; i < 26; i++) {
S[i] = (byte) i;
T[i] = key[i % keylen];
}
int j = 0;
byte tmp;
for (int i = 0; i < 26; i++) {
j = (j + S[i] + T[i]) & 0xF;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
}
}
}
public byte[] encrypt(final byte[] plaintext) {
final byte[] ciphertext = new byte[plaintext.length];
int i = 0, j = 0, k, t;
byte tmp;
for (int counter = 0; counter < plaintext.length; counter++)
{
i = (i + 1) & 0xF;
j = (j + S[i]) & 0xF;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
t = (S[i] + S[j]) & 0xF;
k = S[t];
ciphertext[counter] = (byte) (plaintext[counter] ^ k);
}
return ciphertext;
}
public byte[] decrypt(final byte[] ciphertext) {
return encrypt(ciphertext);
}
}
Get Answers For Free
Most questions answered within 1 hours.