Re: Simple encryption/decryption
Seems to work:
package fubar;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Encryption {
Cipher rc4;
SecretKey rc4Key;
public Encryption( String password )
throws NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeySpecException,
InvalidKeyException
{
rc4 = Cipher.getInstance( "RC4" );
rc4Key = new SecretKeySpec( password.getBytes(), "RC4" );
rc4.init( Cipher.ENCRYPT_MODE, rc4Key );
}
public byte[] crypt( byte[] input )
throws IllegalBlockSizeException,
BadPaddingException
{
return rc4.doFinal( input );
}
public static void main ( String... args )
throws Exception
{
// RC4 test vectors from Wikipedia
// Only "Secret" is long enough to supply the required
// 40 bits.
String [][] testVectors = { { "Secret", "Attack at dawn"} };
for( String[] s : testVectors ) {
Encryption encryption = new Encryption( s[0] );
System.out.println( hexBytes( encryption.crypt(
s[1].getBytes() ) ) );
}
}
private static String hexBytes( byte[] bytes ) {
StringBuilder sb = new StringBuilder( bytes.length *2 );
for( int i = 0; i < bytes.length; i++ ) {
sb.append( String.format( "%02X", bytes[i] ) );
}
return sb.toString();
}
}