Tuesday, June 10, 2008

Simple java code for AES Encryption

import java.io.*;
import java.security.*;
import javax.crypto.*;

public class MakeEncrypt {

public static void main(String args[]) {
if(args.length<2) {
System.out.println("Usage: MakeEncrypt plaintext ciphertext");
return;
}

try {
//Generate a key
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
generator.init(192);
Key encryptionKey = generator.generateKey();
System.out.println("key : " + Utils.toHex(encryptionKey.getEncoded()));

// Open input and out fileencryption pass
FileInputStream fis = new FileInputStream(args[0]);
DataInputStream fdata=new DataInputStream(fis);
FileOutputStream fos = new FileOutputStream(args[1]);

// init encryption
cipher.init(Cipher.ENCRYPT_MODE,encryptionKey);
CipherOutputStream cOut = new CipherOutputStream(fos,cipher);
DataOutputStream dout = new DataOutputStream(cOut);

String s;
while ((s=fdata.readLine())!=null) {
dout.writeBytes(s);
}

// Save keys and IV
FileOutputStream keyfile = new FileOutputStream("keys");
ObjectOutputStream keyout = new ObjectOutputStream(keyfile);
keyout.writeObject(new String(cipher.getIV()));
keyout.writeObject(new String(encryptionKey.getEncoded()));
System.out.println("Encrypted!");

} catch (Exception e) {
System.out.println(e);
}
}
}