Skip to content

Instantly share code, notes, and snippets.

@muralidharan-rade
Created December 12, 2019 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muralidharan-rade/2f959b50b0a70ae60c1d41e671149f82 to your computer and use it in GitHub Desktop.
Save muralidharan-rade/2f959b50b0a70ae60c1d41e671149f82 to your computer and use it in GitHub Desktop.
RC4 encryption and HEX output
package com.rade;
public class RC4 {
public static void main(String arg[]) {
String cipher = "jack and jill";
String key = "hill";
int outputList[] = new int[cipher.length()];
String[] hexes = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
String output = new String();
int i = 0;
int a = 0;
int b = 0;
int j = 0;
int sbox[] = new int[256];
int mykey[] = new int[256];
// Convert cipher to an array of character codes
int mtxt[] = new int[cipher.length()];
for (i = 0; i < cipher.length(); i++) {
mtxt[i] = (int) cipher.charAt(i);
}
// Convert key to an array of character codes
int mkey[] = new int[key.length()];
for (i = 0; i < key.length(); i++) {
mkey[i] = (int) key.charAt(i);
}
System.out.println("mkey*****************8 \n");
for(int yy : mkey) {
System.out.println(yy + " ");
}
// Initialize Key
int tempSwap;
int intLength = mkey.length;
for (a = 0; a < 256; a++) {
mykey[a] = mkey[(a % intLength)];
sbox[a] = a;
}
for (a = 0; a < 256; a++) {
b = (b + sbox[a] + mykey[a]) % 256;
tempSwap = sbox[a];
sbox[a] = sbox[b];
sbox[b] = tempSwap;
}
System.out.println("sbox*****************8 \n");
for(int zz : sbox) {
System.out.println(zz + " ");
}
// Do RC4 Encryption
i = 0;
j = 0;
int k;
int temp;
int cipherby;
for (a = 0; a < mtxt.length; a++) {
i = (i + 1) % 256;
j = (j + sbox[i]) % 256;
temp = sbox[i];
sbox[i] = sbox[j];
sbox[j] = temp;
int idx = (sbox[i] + sbox[j]) % 256;
k = sbox[idx];
cipherby = mtxt[a] ^ k;
outputList[a] = cipherby;
}
System.out.println("output list *****************8 \n");
for(int ii : outputList) {
System.out.println(ii + " ");
}
// Convert string to hex
for (i = 0; i < outputList.length; i++) {
output = output + hexes[outputList[i] >> 4] + hexes[outputList[i] & 0xf];
}
System.out.println("output :: " + output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment