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);
}
}
}

4 comments:

Jyoti said...

Currently, I am using Triple DES algo for the encryption and would like to move to AES 256 bit encryption. What should I take in consideration when doing this? And how to do the same.?

meltonice said...

thaks for the information
jasa pembuatan website

Durga Chinni said...

AES Encryption is nice can u give decryption code please?

Amber Salm said...

Thank you for the complete java code. I have been implementing the same but the my code is not working properly. I will take help from this post.
digital signatures