AES Encryption using JCE
I have taken the program for AES encrytion and decryption from the site
"http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html"
It is working fine if i haven't change any pat of the program except the input to encrypt. I couldn't able to decrypt data of my own. that is i have to read a file and give that file content as the input for decryption.
String strDataToEncrypt =new String();
String strCipherText =new String();
String strDecryptedText =new String();
try{
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
byte[] byteDataToEncrypt = CardDeatils.getBytes();
byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
strCipherText =new BASE64Encoder().encode(byteCipherText);
System.out.println("Cipher Text generated using AES is " +strCipherText+"\n");
String sFilePath="c://CardDetails.txt";
String sFileContent=null,strToDecrypt="";
byte[] ByteToDecrypt=null;
try{
FileOutputStream fos=new FileOutputStream(sFilePath,true);
BufferedOutputStream bos =new BufferedOutputStream(fos);
DataOutputStream dos =new DataOutputStream(bos);
dos.writeBytes(strCipherText);
dos.close();
bos.close();
fos.close();
}catch (Exception e){
System.err.println("File input error");
}
try{
FileInputStream fstream =new FileInputStream(sFilePath);
BufferedInputStream bis =new BufferedInputStream(fstream);
DataInputStream dis =new DataInputStream(bis);
while (dis.available() !=0){
strToDecrypt=dis.readLine();
System.out.println("The data from file is"+strToDecrypt);
}
System.out.println("The data from file is"+strToDecrypt);
ByteToDecrypt=strToDecrypt.getBytes("utf-8");
aesCipher.init(Cipher.DECRYPT_MODE,secretKey);
byte[] byteDecryptedText = aesCipher.doFinal(ByteToDecrypt);
strDecryptedText =new String(byteDecryptedText);
System.out.println(" Decrypted Text message is " +strDecryptedText);
fstream.close();
bis.close();
dis.close();
}catch (IOException e){
System.err.println("File input error");
}
}
catch (NoSuchAlgorithmException noSuchAlgo){
System.out.println(" No Such Algorithm exists " + noSuchAlgo);
}
catch (NoSuchPaddingException noSuchPad){
System.out.println(" No Such Padding exists " + noSuchPad);
}
catch (InvalidKeyException invalidKey){
System.out.println(" Invalid Key " + invalidKey);
}
catch (BadPaddingException badPadding){
System.out.println(" Bad Padding " + badPadding);
}
catch (IllegalBlockSizeException illegalBlockSize){
System.out.println(" Illegal Block Size " + illegalBlockSize);
}
But if i do as above i'm getting error as "Illegal Block Size javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher".
I don't know how to solve it. please help me on correcting this error.
Message was edited by:
jakuarvim

