I'm looking for a simple solution: a way to encrypt a string into a
alphanumeric string, and can be decrypted back to its original form,
using a string as the key, say 'password123', any idea how to achieve
this? Thanks.
I'm not seeing a good answer to this. In particular, the
SecretKeyFactory.getInstance( "ARCFOUR" ) method returns an error. I
don't see a simple way to use RC4 without this call succeeding. Anyone
got a solution?
Anyway, to the OP, check out the code below. It will at least get you
going. Sorry for the lack of Javadoc comments, I just had this laying
around on the hard drive. You can compare this code to the description
of RC4 at Wikipedia. It's the exact same algorithm. Note the test vectors.
<
http://en.wikipedia.org/wiki/RC4>
package local;
/**
COPYRIGHT 2009 Brenden Towey
This code is donated to the public domain but is unsupported and has no
warranty whatsoever. Use at your own risk.
*
* @author Brenden
*/
public class Rc4
{
private byte[] state = new byte[256];
int x, y;
public Rc4( byte[] key )
{
// if( key.length<5||key.length>16 )
// {
// throw new IllegalArgumentException( "Key: "+key+
// " must be between 40 and 128 bits. (key length is "+
// key.length+".)" );
// }
for( int i = 0; i < state.length; i++ ) {
state
= (byte) i;
}
for( int i = 0; i < state.length; i++ ) {
x = (x + key[i % key.length] + state) & 0xFF;
byte swap = state;
state = state[x];
state[x] = swap;
}
x = 0;
}
public byte[] crypt( byte[] input )
{
byte[] output = new byte[input.length];
for( int i = 0; i < input.length; i++ ) {
x = (x + 1) % 256;
y = (state[x] + y) & 0xFF;
byte swap = state[x];
state[x] = state[y];
state[y] = swap;
byte r = state[(state[x] + state[y]) & 0xFF];
output = (byte) (input ^ r);
}
return output;
}
public static void main( final String... args )
{
String[][] testVectors = {{"Key", "Plaintext"},
{"Wiki", "pedia"}, {"Secret", "Attack at dawn"}
};
for( String[] s : testVectors ) {
System.out.printf( "RC4( \"%s\", \"%s\" ) == ", s[0], s[1] );
System.out.println( hexString( new Rc4( s[0].getBytes()
).crypt( s[1].
getBytes() ) ) );
}
}
private static String hexString( byte[] bytes )
{
StringBuilder sb = new StringBuilder( bytes.length *2 );
for( int i = 0; i < bytes.length; i++ ) {
sb.append( String.format( "%02X", bytes ));
}
return sb.toString();
// return local.utils.ArrayUtils.toFormattedString( "%02X",
//bytes, null );
}
}