Skip to content

Instantly share code, notes, and snippets.

@mythosil
Created October 25, 2011 17:16
Show Gist options
  • Save mythosil/1313541 to your computer and use it in GitHub Desktop.
Save mythosil/1313541 to your computer and use it in GitHub Desktop.
encryption and decryption by AES-CBC (Java)
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
class CryptAES {
static final String cipher_type = "AES/CBC/PKCS5Padding";
public static void main(String[] args) {
String key = args[0];
String iv = args[1];
String data = args[2];
byte[] enc = encode(key, iv, data.getBytes());
byte[] dec = decode(key, iv, enc);
for (int i = 0; i < enc.length; i++) {
System.out.printf("%02x", enc[i]);
}
System.out.println();
System.out.println(new String(dec));
}
public static byte[] encode(String skey, String iv, byte[] data) {
return process(Cipher.ENCRYPT_MODE, skey, iv, data);
}
public static byte[] decode(String skey, String iv, byte[] data) {
return process(Cipher.DECRYPT_MODE, skey, iv, data);
}
private static byte[] process(int mode, String skey, String iv, byte[] data) {
SecretKeySpec key = new SecretKeySpec(skey.getBytes(), "AES");
AlgorithmParameterSpec param = new IvParameterSpec(iv.getBytes());
try {
Cipher cipher = Cipher.getInstance(cipher_type);
cipher.init(mode, key, param);
return cipher.doFinal(data);
} catch (Exception e) {
System.err.println(e.getMessage());
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment