Hi all, i'm doing a AES encryption with a library found on sunjava.

There is a small problem i hit while making a test.

Firstly i used "nv3456789123456o" as my key to encrypt.

However, for testing purpose, i'm trying to use a different key to decrypt the message to see what happpens. However, when i used a different key, i hit an exception,

javax.crypto.BadPaddingException: Given final block not properly padded.

Decrypting my message with the correct key works. Can someone help?

I need this as, in future my programme is supposed to decrypt a message with the given key, if its wrong, the program will just display that the wrong key is used and program for the new key again.

Hope someone can help.

Thank you!

/**
 * @(#)AES.java
 *
 *
 * @author
 * @version 1.00 2010/5/27
 */

import java.util.*;
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.math.*;

public class AES {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)throws Exception {

    	String key = "nv3456789123456o";
    	String pText = "Hello";

		String combine = pText + " "+"test";
    	String eText ="";
		String dText ="";

    	eText = encrypt(combine,key);

    	System.out.println("Encrypted text is "+eText);

    	dText = decrypt(eText,"1234567891234560");

		System.out.println("decrypted text is "+dText);

    }


    	/********************************************************************************
	/*																				*
	/*					The algorithm used in this system is AES.  				    *
	/*			The original version of the algorithm is found in the link below:   *
	/*		http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html*
	/*																				*
	/*******************************************************************************/

	 //to convert hexString back to bytearray
	 /*add padding to the block if last block is not enough*/
     public static byte[] hexToByteArray(String hexString)
     {
		BigInteger bi = new BigInteger(hexString,16); //base 16
		byte[] bytes = bi.toByteArray();
		byte[] checkedBytes = null;

		//remove the added 0 in the front due to padding.
		if(bytes[0]==0)
		{
			checkedBytes = new byte[bytes.length-1];
			for(int i=1;i<bytes.length;i++)
			{
				checkedBytes[i-1] = bytes[i];
			}
		}
		else
		{
			checkedBytes = bytes;
		}
		return checkedBytes;
     }

	public static String asHex (byte buf[]) {
      StringBuffer strbuf = new StringBuffer(buf.length * 2);
      int i;

      for (i = 0; i < buf.length; i++) {
       if (((int) buf[i] & 0xff) < 0x10)
	    strbuf.append("0");

       strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
      }

      return strbuf.toString();
     }

	 public static String encrypt(String plaintext, String keystr)throws Exception{
	 	byte[] key = keystr.getBytes();
	 	SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

	 	// Instantiate the cipher
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

	 	byte[] encrypted = cipher.doFinal(plaintext.getBytes());

	 	String ciphertext;
	 	ciphertext = asHex(encrypted);
	 	return ciphertext;

	 }

	 public static String decrypt(String ciphertext, String keystr) throws Exception {

	 	byte[] key = keystr.getBytes();
	 	SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

	 	// Instantiate the cipher
        Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);

	 	byte[] original = cipher.doFinal(hexToByteArray(ciphertext));

	 	String plaintext;
	 	plaintext = new String(original);
	 	return plaintext;
	 }

}

says it all really, the key is not just invalid, it's not even recognised as a possible key.

Hmm, but how do i work around with this? Since i've to take a given key and decrypt. If the key is wrong, i should prompt the user that key is wrong and message cannot be decrypted

catch the exception and handle it :)

hmm.. i'm still kinda noob to java. can give me a heads up how to catch this exception...

is it something like this?

catch (exception javax.crypto.BadPaddingException)
{
     System.out.println("Wrong Key given!");
}

not quite the correct syntax, but you get the idea.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.