package org.stevewinfield.sunrise.util;

public class RC4 {
	 
	public static String rc4(String key, String str) {
		int[] s = new int[256];
		int j = 0;
		int x = 0;
		String res = "";
		
		for (int i = 0; i < 256; i++) {
			s[i] = i;
		}
		
		for (int i = 0; i < 256; i++) {
			j = (j + s[i] + (int)key.charAt(i % key.length())) % 256;
			x = s[i];
			s[i] = s[j];
			s[j] = x;
		}
		j = 0;
		int i = 0;
		for (int y = 0; y < str.length(); y++) {
			i = (i + 1) % 256;
			j = (j + s[i]) % 256;
			x = s[i];
			s[i] = s[j];
			s[j] = x;
			res += Character.toString((char)(str.charAt(y) ^ s[(s[i] + s[j]) % 256]));
		}
		return res;
	}
 
}