[java]代码库
import java.util.Scanner;
class Test{
public static void main(String[] args)
{
Scanner ss = new Scanner(System.in);
String key = "1";//密钥
String data = "abc";//数据
String str = RC4(data, key);//加密
String str2 = RC4(str, key);//解密
System.out.printf("加密后:%s \\\\n", str);//打印加密结果
System.out.printf("解密后:%s \\\\n", str2);//打印解密结果
ss.nextLine();
}
//初始化
public static int[] RC4_INIT(String key)
{
byte[] keys = key.getBytes();
int[] sbox = new int[256];
int j = 0;
int[] k = new int[256];
for(int i = 0; i < 256; i++)
{
sbox[i] = i;
k[i] = keys[i % keys.length];
}
for(int i = 0; i < 256; i++)
{
j = (j + sbox[i] + k[i]) % 256;
int tmp = sbox[i];
sbox[i] = sbox[j];
sbox[j] = tmp;
}
return sbox;
}
public static String RC4(String data, String key)
{
byte[] datas = data.getBytes();//会把不可识别字节转换成0x3f
int[] s = RC4_INIT(key);
System.out.println("数据入口:");for(int i = 0; i < datas.length ;i ++) System.out.printf("0x%-3h ", datas[i]);System.out.println();
int x = 0,y = 0,t = 0;
for(int i = 0; i < datas.length; i++){
x = (x + 1) % 256;
y = (y + s[x]) % 256;
int tmp = s[x];
s[x] = s[y];
s[y] = tmp;
t = (s[x] + s[y]) % 256;
datas[i] = (byte)(datas[i] ^ s[t] );
}
System.out.println("加解密后:");for(int i = 0; i < datas.length ;i ++) System.out.printf("0x%-3h ", (int)datas[i]);System.out.println();
String result = "";
try {result = new String(datas,0,datas.length,"GBK");} catch (Exception e1) {}//会把不可识别字节转换成0x3f
return result;
}
}//源代码片段来自云代码http://yuncode.net