Doubt in a Finally block ?

ques 1 :: public class Main {
   public String test() throws Exception
       try
           throw new Exception();
       catch(Exception e)
            throw new Exception();
       finally
    public static void main(String[] args) {
          try{
       new Main().test();
           catch(Exception e)
              e.printStackTrace();
    }According to sun documentation ,a method whose return type is String,int,.. must have return statement otherwise compiler will show an error.But according to this program it will not show any compiler error.Can you please suggest or explain me how this program is compiling.
I have fair idea, that when you throw any exception and after that if u give return statement then it will say its not reachable.
ques 2::
   public String test() throws Exception
       try
           throw new Exception();
       catch(Exception e)
            throw new Exception();
       finally
  return "abc";
    }Again am using same method but here am just returning an value. I want to know what will happen to that new Exception() object which we are throwing at catch block.Since its returning value as "abc".
If you just comment that return statement then it will throw Exception.
Please clarify this also.

My first recommendation is that you build an experiment and see how it behaves. That way you will know without a doubt what to expect based on your coding style. I'm not in any way saying that the behavior is in any way different from what the documentation illustrates, only that if you build a test you'll know for sure. Otherwise, you'll know what we told you and what the documentation says.
Puckstopper's rules #6 - It is preferred to have a single return from any given method. The exception to this rule is if you reach a point in the code that is non-exceptional but creates a condition where the rest of the method should not execute. (There is another rule that relates to this condition that says that in this case the functionality should really be divided because it is clearly overly complex.)
That leads us to a basic code pattern.
int retVal = 0 ; // Initialize to a neutral condition or the default condition
try{
    // Do some stuff that might cause an exception to be thrown
    retVal = RESOLUTION_STATE
// Be specific about exceptions
catch(Exception e){
    // Do something to handle the exception in a graceful and tidy manner.
    // Code that simply barfs the stack trace will incur the wrath of the Exception Gods
finally{
    // Do anything relating to the code in the try and only in the try that must happen no matter what
return retVal ;This does not address the question of whether the exception(s) can or should be handled here. Only a cohesive way of dealing with the try/catch/finally construct and returning from a method.
PS.

Similar Messages

  • PBE; final block not properly padded help!

    Hi there,
    I'm having problems decrypting passwords using password based encryption (PBE), throwing me a "final block not properly padded" exception.
    The passwords are also encrypted uses PBE in a seperate class called the PasswordEncryption. The code necessary to generate the Cipher is in a seperate method which is passed a String to determined if it would be initialized in "encrypt" or "decrypt" mode.
    The class where the passwords are decrypted, UserManager, is passed the encrypted passwords as a String. It calls the PasswordEncryption class gets getcipher() to get the Cipher, and then decrypts the password. The data is read from the database by another class which reads database info, and passed in as a string to the decrypting class. The decrypting class converts the string to a byte[].
    Below I have the UserManager class and PasswordEncryption class:
    public class UserManager
    implements SecurityServerInterface, PETComponent {
    public UserManager() {
    private static String decryptPassword(String asPassword) throws
    SecurityException {
    PasswordEncryption passwordEncryption = new PasswordEncryption();
    Cipher pbeCipher = passwordEncryption.getCipher("decrypt");
    String clearText = new String();
    byte[] encryptedPassword = asPassword.getBytes();
    try {
    //This is where decryption failed! Given final block not properly padded
    byte[] cipherText = pbeCipher.doFinal(encryptedPassword);
    System.out.println(cipherText);
    System.out.println("test cipher text");
    clearText = new String(cipherText);
    System.out.println("original:" + asPassword);
    System.out.println("decrypted:" + clearText);
    catch (IllegalBlockSizeException e) {
    System.out.println(e.getMessage());
    String illegalBlock = e.getMessage();
    throw new SecurityException(illegalBlock);
    catch (BadPaddingException e) {
    System.out.println(e.getMessage());
    String badPadding = e.getMessage();
    throw new SecurityException(badPadding);
    catch(Exception e) {
    System.out.println(e.getMessage());
    String exception = e.getMessage();
    throw new SecurityException(exception);
    System.out.println(clearText);
    return clearText;
    public class PasswordEncryption {
    public static void main(String[] args) throws PETDBException,
    SecurityEncryptionException {
    PasswordEncryption encryptor = new PasswordEncryption();
    ArrayList mainList = encryptor.getAllPasswords();
    mainList = encryptor.encryptAllPasswords(mainList);
    encryptor.updateAllPasswords(mainList);
    public PasswordEncryption() {
    //Get passwords from the user table of the database, e.g, loginName and passwords
    private ArrayList getAllPasswords() throws PETDBException {
    ArrayList passwordList = new ArrayList();
    DBConnection.setConnection("jdbc:mysql://localhost/Mysql/data/pet?user=root&password=");
    DBConnection dbCon = DBConnection.createConnection();
    Connection con = dbCon.getConnection();
    System.out.println(con);
    try {
    String allPasswordQuery = " SELECT " + DBColumns.USPASSWD.trim() + " , " +
    DBColumns.USLOGINNAME.trim() + " from " + DBColumns.USER;
    Statement stmt = con.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery(allPasswordQuery);
    if (rs.isFirst()) {
    throw new PETDBException("No password found in the database.");
    while (rs.next()) {
    UserDO loUserDO = new UserDO();
    loUserDO.setPassword(rs.getString(DBColumns.USPASSWD));
    loUserDO.setLoginName(rs.getString(DBColumns.USLOGINNAME));
    passwordList.add(loUserDO);
    catch (SQLException sql) {
    String sqlError = sql.getMessage();
    throw new PETDBException(sqlError);
    return passwordList;
    private ArrayList encryptAllPasswords(ArrayList aoPasswordList) throws
    SecurityEncryptionException {
    // Encrypt the password
    Cipher pbeCipher = getCipher("encrypt");
    Iterator passwordIterator = aoPasswordList.iterator();
    UserDO loUserDO = new UserDO();
    try {
    while (passwordIterator.hasNext()) {
    loUserDO = (UserDO) passwordIterator.next();
    String lsPassword = loUserDO.getPassword();
    byte[] clearTextPassword = lsPassword.getBytes();
    byte[] cipherText = pbeCipher.doFinal(clearTextPassword);
    String cipherString = new String(cipherText);
    loUserDO.setPassword(cipherString);
    System.out.println(cipherString);
    catch (IllegalBlockSizeException e) {
    throw new SecurityException("Can't encrypt password, illegal block size");
    catch (BadPaddingException e) {
    throw new SecurityException("Can't encrypt password, bad padding");
    System.out.println(aoPasswordList);
    return aoPasswordList;
    public Cipher getCipher(String mode) {
    PBEKeySpec pbeKeySpec;
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Salt
    byte[] salt = {
    (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
    (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
    // Iteration count
    int count = 20;
    // Create PBE parameter set & a SecretKey
    pbeParamSpec = new PBEParameterSpec(salt, count);
    SecretKey pbeKey;
    // Use our own encryption password.
    // Collect the password as char array and convert
    // it into a SecretKey object, using a PBE key
    // factory.
    char[] password = new String("cmuw-team5").toCharArray();
    pbeKeySpec = new PBEKeySpec(password);
    try {
    keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    pbeKey = keyFac.generateSecret(pbeKeySpec);
    catch (NoSuchAlgorithmException e) {
    throw new SecurityException("Can't collect password as a char array");
    catch (InvalidKeySpecException e) {
    throw new SecurityException("Can't convert password into a SecretKey Object");
    // Create PBE Cipher
    Cipher pbeCipher;
    try {
    pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    catch(NoSuchAlgorithmException e) {
    throw new SecurityException("Can't create a PBE Cipher, no such algorithm");
    catch(NoSuchPaddingException e) {
    throw new SecurityException("Can't create a PBE Cipher, no such padding");
    // Initialize PBE Cipher with key and parameters
    if (mode == "encrypt") {
    try {
    pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
    catch(InvalidKeyException e) {
    throw new SecurityException("Can't initialize PBE Cipher with key");
    catch(InvalidAlgorithmParameterException e) {
    throw new SecurityException("Can't initialize PBE Cipher with parameters");
    if (mode == "decrypt") {
    try {
    pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
    catch(InvalidKeyException e) {
    throw new SecurityException("Can't initialize PBE Cipher with key");
    catch(InvalidAlgorithmParameterException e) {
    throw new SecurityException("Can't initialize PBE Cipher with parameters");
    return pbeCipher;
    //Get encrypted passwords out of the ArrayList and update the database
    private void updateAllPasswords(ArrayList aoUpdatePasswordList) throws
    PETDBException {
    DataService dataService = new DataService();
    Iterator getEncryptPassword = aoUpdatePasswordList.iterator();
    String lsUpdatePassword = new String();
    String lsUserName = new String();
    Statement stmt;
    DBConnection dbCon = DBConnection.createConnection();
    Connection con = dbCon.getConnection();
    try {
    stmt = con.createStatement();
    System.out.println(stmt);
    catch (SQLException sql) {
    String sqlError = sql.getMessage();
    System.out.println(sqlError);
    throw new PETDBException(sqlError);
    while (getEncryptPassword.hasNext()) {
    UserDO loUser = (UserDO) getEncryptPassword.next();
    lsUpdatePassword = loUser.getPassword();
    lsUserName = loUser.getLoginName();
    String allUpdatePassword = " UPDATE " + DBColumns.USER + " SET " +
    DBColumns.USPASSWD + " = " + "'" + lsUpdatePassword + "'" + " WHERE "
    + DBColumns.USLOGINNAME + " = " + "'" + lsUserName + "'";
    System.out.println(allUpdatePassword);
    try {
    int returnValue = stmt.executeUpdate(allUpdatePassword);
    System.out.println(returnValue);
    catch (SQLException sql) {
    String sqlError = sql.getMessage();
    throw new PETDBException(sqlError);
    try {
    con.commit();
    con.close();
    catch (SQLException sql) {
    String sqlError = sql.getMessage();
    throw new PETDBException(sqlError);

    Thanks for the prompt response! I got this example
    from the Sun Java cryptography extensions web page at:
    http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/
    CERefGuide.html#PBEExThe code I'm pointing out did not come from there. Nowhere in Sun's examples do you see them creating Strings directly from ciphertext. (Which is good, because if you did, their examples wouldn't work). To give some more context on where the problem is:private ArrayList encryptAllPasswords(ArrayList aoPasswordList) throws SecurityEncryptionException {
      // Encrypt the password
      Cipher pbeCipher = getCipher("encrypt");
      Iterator passwordIterator = aoPasswordList.iterator();
      UserDO loUserDO = new UserDO();
      try {
        while (passwordIterator.hasNext()) {
          loUserDO = (UserDO) passwordIterator.next();
          String lsPassword = loUserDO.getPassword();
          byte[] clearTextPassword = lsPassword.getBytes();
          byte[] cipherText = pbeCipher.doFinal(clearTextPassword);
          // DOING THE FOLLOWING TO CIPHERTEXT TURNS IT INTO GARBAGE!
          String cipherString = new String(cipherText);
          loUserDO.setPassword(cipherString);
          System.out.println(cipherString);
      } catch (IllegalBlockSizeException e) {
        throw new SecurityException("Can't encrypt password, illegal block size");
      } catch (BadPaddingException e) {
        throw new SecurityException("Can't encrypt password, bad padding");
      System.out.println(aoPasswordList);
      return aoPasswordList;
    }(Note: Please use the [ code ] tags when you post code - it makes it MUCH easier to figure out what you're doing.)
    Also, my decryption code in the UserManager class does
    work for two out of 8 users....I can't really figure
    out why it's working for Only 2 users, and not the
    rests. It's possible that the ciphertext is successfully string-able in those two cases (although I doubt it). But I can absolutely guarantee to you that trying to treat ciphertext as a String will turn your ciphertext into grabage, and that will result in a BadPaddingException when you decrypt. You need to stop doing that.
    If you need to treat ciphertext or keys as Strings, the right way to do it is to Base64-encode the byte[] into a String, and then Base64-decode when you want to decrypt.
    Grant

  • BadPaddingException: Given final block not propertly padded -- Help Please

    I keep getting --Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded.       
    I know the problem lies with me writing to the encrypted text file or at some point when I'm actually reading it. Here's the code of these points......
    ciph.init(Cipher.ENCRYPT_MODE, skeySpec);
    /* The encryption begins */
    byte[] textBytesEncrypted = ciph.doFinal(textBytes);
    String bText = Base64.encodeBytes(textBytesEncrypted);
    // pw is a PrintWriter, I've also tried to use a FileOutputStream object
    // and write the entire byte array to a data file (without converting to
    // a String -- but that also resulted with the same exception being
    // thrown
    pw.write(bText);
    pw.close();
    public void decryptFile()
    throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
    IllegalBlockSizeException, BadPaddingException
    /* These lines will be writing and reading to the files */
    FileInputStream in = new FileInputStream(new File("C://outfile.txt"));
    PrintWriter pw = new PrintWriter(new File("C://outfile3.txt"));
    boolean done = false;
    int i = 0;
    ArrayList<Byte> bytearr = new ArrayList<Byte>();
    /* This loop places each of the bytes into an Array List, I'm using this because of the
    automatic resizing */
    while(!done)
    int next = in.read();
    if(next == -1) done = true;
    else{
    bytearr.add(i, (byte)next);
    i++;
    /* This variable retrieves the size of the array list in which the array will be set to */
    int length = bytearr.size();
    byte[] textBytes = new byte[length];
    /* This loop will move the Array List of bytes into the above array of bytes for future use */
    for(int j=0; j<length; j++)
    textBytes[j] = bytearr.get(j);
    ciph.init(Cipher.DECRYPT_MODE, skeySpec);
    /* The encryption begins */
    byte[] textBytesEncrypted = ciph.doFinal(textBytes);
    String text= new String(textBytesEncrypted);
    pw.write(text);
    in.close();
    pw.close();
    Any help would be greatly appreciated.

    You have not really supplied enough code to say exactly what is wrong BUT I would bet it is because you are treating files as containing chars and lines instead of just bytes.
    My suggestion - read the input files as bytes and encrypt/decrypt using CipherInputStream.

  • Possible to determine exception thrown in a finally block?

    I believe the answer to this is 'no', but I thought I would ask just to confirm.
    If an exception is thrown in a try block, is there a way in the finally block to determine what exception was thrown? I tried using Throwable#fillinStackTrace and Thread#getStackTrace and did not get anywhere. I did see other methods like Thread#getAllStackTraces and perhaps going up to a parent ThreadGroup and inspecting other child Thread instances, but at least in my debugger, I did not see anything useful.
    The basic idea I am trying to achieve is to detect if an exception is thrown in the try, if yes, chain any exception thrown in the finally block to the original exception. I know I can do this on a case-by-case basis by storing the exception caught and then manually chaining it in the finally block. I was looking for something more generic/applicable to all finally blocks.
    Thanks.
    - Saish

    Thanks JSchell, have done that many times in the past.
    I was looking for a more generic (not generics) solution to the problem. So that an error handler could be written to automatically chain exceptions thrown in the finally clause (granted, one still needs to invoke the error handler). My hope was the stack in the finally clause would look different if an exception was thrown in the try block versus none at all.
    - Saish

  • Return in finally block hides exception in catch block

    Hi,
    if the line marked with "!!!" is commented out, the re-thrown exception is not seen by the caller (because of the return in the finally block). If the line is commented in, it works as I would expect. Is this is bug or a feature? I assume the return removes the call to troubleMaker() from the call stack - including the associated exception...
    Christian Treber
    [email protected]
    public class ExceptionDemo extends TestCase
    public void testException()
    String lResult = "[not set]";
    try
    lResult = troubleMaker();
    System.out.println("No exception from troubleMaker()");
    } catch(Exception e)
    System.out.println("Caught an exception from troubleMaker(): " + e);
    System.out.println("Result: " + lResult);
    public String troubleMaker()
    boolean lErrorP = false;
    try
    if(6 > 5)
    throw new RuntimeException("Initial exception");
    return "normal";
    } catch (RuntimeException e)
    System.out.println("Caught runtime exception " + e);
    lErrorP = true;
    throw new RuntimeException("Exception within catch");
    } finally
    System.out.println("Finally! Error: " + lErrorP);
    if(!lErrorP)
    return "finally";

    This is specified in the Java Language Specification, section 14.19.2 .
    -- quote
    If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    * If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:
    o If the catch block completes normally, then the finally block is executed. Then there is a choice:
    + If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
    -- end quote
    "completing abruptly" (in this instance) means a throw or a return, as specified in section 14.1
    Ok? It's not a bug, it's the defined behaviour of the language. And when you think about it, this behaviour gives you the option to do what you want in your finally block.

  • About the finally block of the try catch.

    I know that finally block contains the code that will be executed in any condition of the try catch.
    However, I think it is unneccessary, since the stack after the try catch stack will be executed any way.
    Any one can help?
    for example
    try{
    System.in.read();
    catch(Exception e){}
    finally
    { System.out.println("does this matter?");}and
    try{
    System.in.read();
    catch(Exception e){}
    System.out.println("does this matter?");

    However, I think it is unneccessary, since the stackafter the try catch
    stack will be executed any way.That does assume that you catch and handle the error
    appropriately.
    Of course this is valid as well, and demonstrates
    when you would WANT a finally clause.
    Connection con = null;
    Statement stmt = null;
    try{
    con  = Database.getConnection();
    stmt = con.createStatement("Select * from dual");
    // maybe something throws an exception here?
    finally{
    if (stmt != null){
    stmt.close();
    if (con != null){
    con.close();
    The finally block here might throw a null pointer exception itself use
    null!=stmt null!=stmt

  • Prb in using finally block......please help.

    hi currently i am facing this problem when i tried using finally block. after recompile, it gave me a warning message or should i said is an error message. My error statement is as below,
    C:\EKP\web\WEB-INF\classes\com\tms\report\model\ReportModule.java:393: warning: finally clause cannot complete normally
    ^
    Note: C:\EKP\web\WEB-INF\classes\com\tms\report\model\ReportModule.java uses or overrides a deprecated API.
    Note: Recompile with -deprecation for details.
    1 warning
    my code is as below,
    try
    service.deleteJobTask( task );
    service.scheduleJob( task, schedule );
    success = true;
    catch( SchedulingException e )
    Log.getLog( getClass() ).error( e.getMessage(), e );
    finally
    return success;
    Please help me. Thank you very much
    Regards.

    Ditch the return statement in your finally clause and move it to the end of the try block in stead. The whole idea behind finally is that it is always executed even after you return from the method, you don't add a return statement to your finally.
    In your case you don't need a finally clause, you only add calls to it that MUST be executed, such as freeing up resources.

  • How to properly use finally block

    I am writing a try-catch-finally block and I don't think it is written properly. I am using a BufferedReader and BufferedWriter like this:
    BufferedReader myInput = null;
    BufferedWriter myOutput = null;
    try
        myInput = new BufferedReader(new FileReader(inputFile));
        myOutput = new BufferedWriter(new FileWriter(outputFile));
        // do stuff here
    catch (IOException e)
        e.printStackTrace();
    finally
        myInput.close();
        myOutput.close();
    }Now the whole point of the finally block is that it gets executed no matter what, so I want to make sure that the input and output file get closed even if there is an exception thrown. However, when I try to compile this code it doesn't work because it complains that there are unhandled exceptions in the finally block.
    What am I doing wrong here? If I have to put yet another try block inside of the finally block...doesn't that defeat the whole purpose of the finally block?

    gamblor01 wrote:
    I am writing a try-catch-finally block and I don't think it is written properly. I am using a BufferedReader and BufferedWriter like this:
    BufferedReader myInput = null;
    BufferedWriter myOutput = null;
    try
    myInput = new BufferedReader(new FileReader(inputFile));
    myOutput = new BufferedWriter(new FileWriter(outputFile));
    // do stuff here
    catch (IOException e)
    e.printStackTrace();
    finally
    myInput.close();
    myOutput.close();
    }Now the whole point of the finally block is that it gets executed no matter what, so I want to make sure that the input and output file get closed even if there is an exception thrown. However, when I try to compile this code it doesn't work because it complains that there are unhandled exceptions in the finally block.
    What am I doing wrong here? If I have to put yet another try block inside of the finally block...doesn't that defeat the whole purpose of the finally block?You should also check myInput and myOutput references to make sure they are not null. If your first exception occurs during instantiation of your FileReader, for example, then myInput and myInput will both be null, causing a NullPointerException when you attempt to close them. Better to do something like:
    finally
      if ( myInput != null )
        myInput.close();
      if ( myOutput != null )
        myOutput .close();
    }� {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Finally block not executed!

    Hello,
    I have something strange with the code below:
    the try block of the method B throw a nullPointerException. This exception isn't catched by the catch block of the method B but by the catch block of method A. That's OK.
    The strange thing is that the finally block of the method B is not executed!
    Why??
    Is someone has an idea?
    Thanks
    Sylvain
    method A {
    try {
    B();
    } catch (Throwable e) {
    method B {
    try {
    } catch (oneClassException t) {
    } finally {
    }

    This code also works as expected.
    public class A {
      public A() {
        try {
          new B().createError();
        } catch (Exception e) {
          System.out.println("Exception caught in A: " + e.getClass().getName());
        } finally {
          System.out.println("Finally in A called");
      public static void main(String[] args) {
        new A();
    public class B {
      public void createError() throws Exception {
        try {
          int[] a = null;
          a[1] = 12;
        } catch (Exception e) {
          System.out.println("Caught an exception in B : " + e.getClass().getName());
          throw(e);
        } finally {
          System.out.println("Finally in B called");
    Output:
    Caught an exception in B : java.lang.NullPointerException
    Finally in B called
    Exception caught in A: java.lang.NullPointerException
    Finally in A called
    Java version:
    java version "1.4.1_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)
    Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)

  • Seeing a lot of ERROR - could not decrypt password Given final block not...

    What cause these error messages in DPS 6.x?
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:55 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:56 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:56 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:56 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:56 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:56 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:56 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:56 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:56 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded
    [18/Apr/2009:23:05:57 -0400] - CONFIG - ERROR - could not decrypt password Given final block not properly padded

    You have copied a DPS configuration (conf.ldif) from one instance to another one.
    Passwords are encrypted in the conf.ldif with an instance-specific key.
    2 ways to address the problem:
    - either
    stop the proxy, manually edit the conf.ldif and replace encrypted values (prefixed by {3DES})
    with the value in clear.
    DPS will encrypt them again during next startup.
    - or
    copy the dps keystore files (in alias if I remember well) to the target dps instance as the keystore
    contains the encryption key.

  • AES -javax.crypto.BadPaddingException: Given final block notproperly padded

    I have an Encrypt Util class to encrypt and decrypt CLOB content in the database(Oracle). During encryption there is no error/exception thrown., But while decryption it throws the exception javax.crypto.BadPaddingException: Given final block notproperly padded.
    The error is thrown only for selected records, not for all. For most of them it works fine. I use 256 bit AES Encryption.The sequence of steps to generate and retrieve the key is as follows:
    (Generating and Storing the Key)
    Generate original Key Using JCE --> Then XOR it with a known String (Key) --> Write to a file in DB Server (Solaris 10) using a Stored Procedure.
    (Retrieving the Key)
    Read the key file using s Stored Procedure --> XOR it with known String(Key) --> Retrieve the original Key
    The decryption works fine for most of the records (70%) but failing 30% of the time. There is no exception in the way the encrypted content gets stored in the db
    The key is generated as a one time step in the application and stored in the file. It is retrieved and cached in the application once, everytime the appserver is restarted.
    Could someone pls. help?
    Attaching below (1) code snippet for generating the key and (2) The code snipped to retrieve the key (3) the class which does the encryption and decryption of data
    (1) code snippet for generating the key
    String xorRefKey = "*&^%$#@!AiMsKey!*&^%$#@!AiMsKey!";
    KeyGenerator kg = KeyGenerator.getInstance("AES");
                kg.init(256);
                String initialKey = new String (kg.generateKey().getEncoded());
             char[] refArr =  xorRefKey.toCharArray();
              char[] initKeyArr = initialKey.toCharArray();
                char[] finalKeyArr = new char[refArr.length];
                 for(int i=0;i<initKeyArr.length;i++){
                     finalKeyArr= (char)(initKeyArr[i] ^ refArr[i]);
    String finalKey = new String(finalKeyArr);----------------------
    (2) The code snipped to retrieve the keyString xorRefKey = "*&^%$#@!AiMsKey!*&^%$#@!AiMsKey!";
    char[] refArr = xorRefKey.toCharArray();
    //initialKey is the key read from the file using a db call
    char[] initKeyArr = initialKey.toCharArray();
    char[] finalKeyArr = new char[refArr.length];
    for(int i=0;i<initKeyArr.length;i++){
    finalKeyArr[i]= (char)(initKeyArr[i] ^ refArr[i]);
    String finalKey= new String(finalKeyArr);
    Class to encrypt/decrypt
    (3) EncryptUtil classpublic class EncryptUtil {
    private static SecretKeySpec skeySpec = null;
    private static final String encryptionAlgorithm = "AES";
    private static IGOLogger logger = IGOLogger.getInstance(IGOLogger.ENCRYPTION);
    private static final String UNICODE_FORMAT = "UTF8";
    private Cipher cipher = null;
    public EncryptUtil(String key){
    String lFuncName = "EncryptUtil :: EncryptUtil(): ";
    try{
    cipher = Cipher.getInstance(encryptionAlgorithm);
    skeySpec = new SecretKeySpec(key.getBytes(), encryptionAlgorithm);
    } catch (NoSuchAlgorithmException e) {
    logger.error(lFuncName + "No Such Algorithm Error while creating Cipher and KeySpec ",e);
    } catch (NoSuchPaddingException e) {
    logger.error(lFuncName + "No Such Padding Error while creating Cipher and KeySpec ",e);
    * Encrypts the data based on the key and algorithm
    * @param data
    * @return encrypted data
    public String encrypt(String data){
    String lFuncName = "EncryptUil :: encrypt(): ";
    byte[] encryptedData = null;
    String encryptedFinal = "";
    try{
    if(data!=null && data.length()>0){
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec,cipher.getParameters());
    encryptedData = (cipher.doFinal(data.getBytes(UNICODE_FORMAT)));
    encryptedFinal = new BASE64Encoder().encode(encryptedData);
    } catch (InvalidKeyException e) {
    logger.error(lFuncName + "Invalid Key Error while Encrypting Data ",e);
    } catch (BadPaddingException e) {
    logger.error(lFuncName + "Bad Padding Error while Encrypting Data ",e);
    } catch (IllegalBlockSizeException e) {
    logger.error(lFuncName + " Illegal Block Size Error while Encrypting Data ",e);
    } catch (InvalidAlgorithmParameterException e) {
    logger.error(lFuncName + " Invalid Alogirthm Parameter Error while Encrypting Data ",e);
    } catch (UnsupportedEncodingException e) {
    logger.error(lFuncName + " Unsupported Encoding Exception Error while Encrypting Data ",e);
    }catch(Exception e){
    logger.error(lFuncName + " Error while Encrypting Data ",e);
    return encryptedFinal;
    * Decrypts the encrypted data based on the key and algorithm
    * @param data
    * @return
    public String decrypt (String data){
    String lFuncName = "EncryptUil :: decrypt(): ";
    byte[] decrypted = null;
    byte[] decryptedFinal = null;
    String decryptedData = "";
    try{
    if(data!=null && data.length()>0){
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    decrypted = new BASE64Decoder().decodeBuffer(data);
    decryptedFinal = (cipher.doFinal(decrypted));
    decryptedData = this.bytes2String(decryptedFinal);
    } catch (InvalidKeyException e) {
    logger.error(lFuncName + "Invalid Key Error while Decrypting Data ",e);
    } catch (BadPaddingException e) {
    logger.error(lFuncName + "Bad Padding Error while Decrypting Data ",e);
    } catch (IllegalBlockSizeException e) {
    logger.error(lFuncName + " Illegal Block Size Error while Decrypting Data ",e);
    } catch (IOException e) {
    logger.error(lFuncName + " IO Exception while Decrypting Data ",e);
    }catch (Exception e){
    logger.error(lFuncName + " Error while Decrypting Data ",e);
    return decryptedData;
    private String bytes2String( byte[] bytes )
              StringBuffer stringBuffer = new StringBuffer();
              for (int i = 0; i < bytes.length; i++)
                   stringBuffer.append( (char) bytes[i] );
              return stringBuffer.toString();
    }The EncryptUtil is invoked as follows:EncryptUtil encryptUtil = new EncryptUtil("finalKey retrieved when application starts");
    encryptUtil.encrypt(unencryptedData);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    shannara wrote:
    thanks for your reply.
    I am sorry but I am not able to get you exactly. Every time I invoke the Utility class, I do a
    EncryptUtil eUtil = new EncryptUtil() Good. You seem to be using it in a thread safe manner since you create a new instance each time you need to use one.
    >
    and then invoke the decrypt() or encrypt() method, which gets the key from the cache (it is a read only object, so no problems of concurrent modification or any thing of that sort). And also these methods are called from a normal java class only, which inturn may be called from a jsp/servlet, but no scenarios of any concurrent access as such, so based on what you said, I am not able to figure out where exactly the thread safety could come as an issue.Each instance of a jsp or servlet can be being processed by many threads at the same time. Your statement above hints at a possible lack of understand on this point though I could be just reading it wrong. It indicates to me that your problem may be nothing to do with the encryption and everything to do with 'concurrent access' .
    Make sure you have no instance variables or class variables in your jsp(s) and servlet(s).
    Edit: The more I think about this the more I believe you have a thread safety problem in the code that reads the key. I would concentrate on that.
    Edited by: sabre150 on Dec 18, 2007 10:10 AM

  • Given final block not properly not padded.....when given wrong password....

    hi..........sir
    when i am executing the following code..with wrong password....i am getting the BadPaddingException:Given final block not properly padded............
    plz help me to solve this one with the solution.
    I am doing my final project .....i am implementing an security protocol....
    here is thecode...
    String pw=JOptionPane.showInputDialog("enter the password string");
    byte[] pwb=new byte[pw.getBytes().length];
    pwb=pw.getBytes();
    String msg=JOptionPane.showInputDialog(null,"enter the message");
    byte[] msgb=new byte[msg.getBytes().length];
    msgb=msg.getBytes();
    try
    PBEKeySpec ks=new PBEKeySpec(pw.toCharArray());
    SecretKeyFactory skf= SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey ky=skf.generateSecret(ks);
    MessageDigest md=MessageDigest.getInstance("MD5");
    md.update("srikrishna".getBytes());byte[] digest=md.digest();
    byte salt[]=new byte[8];
    for(int i=0;i<8;i++)
         salt=digest[i];
    PBEParameterSpec ps=new PBEParameterSpec(salt,20);
    Cipher cf=Cipher.getInstance("PBEWithMD5AndDES");
    cf.init(Cipher.ENCRYPT_MODE,ky,ps);
    byte[]thCp=cf.doFinal(msgb);
    for(int i=0;i<thCp.length;i++)
         System.out.print((char)thCp[i]);
    System.out.println("\n\n");
    String pwbs=JOptionPane.showInputDialog("enter the password string");
    byte[] pwbsb=new byte[pwbs.getBytes().length];
    pwbsb=pwbs.getBytes();
    PBEKeySpec ks1=new PBEKeySpec(pwbs.toCharArray());
    SecretKeyFactory skf1= SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey ky1=skf1.generateSecret(ks1);
    MessageDigest md1=MessageDigest.getInstance("MD5");
    md1.update("srikrishna".getBytes());byte[] digest1=md1.digest();
    byte salt1[]=new byte[8];
    for(int i=0;i<8;i++)
         salt1[i]=digest1[i];
    PBEParameterSpec ps1=new PBEParameterSpec(salt1,20);
    Cipher cf1=Cipher.getInstance("PBEWithMD5AndDES");
    cf1.init(Cipher.DECRYPT_MODE, ky1,ps1);
    byte[]thPt=cf1.doFinal(thCp);
    for(int i=0;i<thPt.length;i++)
         System.out.print((char)thPt[i]);
    catch(Exception e)
         e.printStackTrace();
    Thanks in Advance.............
    Edited by: hareksna on Jan 12, 2009 4:36 PM

    hareksna wrote:
    sir, thanks for reply.........
    I understood .....
    sorry if am asking u once again.......
    for every encrypted data there will be an corresponding decrypted data.........even with the different key.....it shud produce some decrypted bytes.(even diff from plain text)......naa.....i.e it should produce the wrong plain text.......The encyption process -
    cleartext (adding padding) padded cleartext (encrypting) ciphertext.
    The decryption process -
    ciphertext (decrypting) padded cleartext (remove padding) cleartext.
    Even though it would be gibberish when the wrong key is used, you seem to want access to the 'padded cleartext' but using your code you do not have access to it. You could emulate the PBE process and get access to the 'padded cleartext' but what would be the point. You would just have gibberish when using the wrong key.
    but y the exception......
    ok ......and also tell me y this BPE is actually happens and how to avoid that when we use some padding.....
    plz tell me the reason.............Start by reading "Applied Cryptography"by Bruce Schneier and then "Practical Cryptography" by Ferguson and Schneier.
    >
    so finally .........
    u r saying that i need to catch the BPE and should inform client that he entered wrong password........
    so i have to end up in the second step itself.....
    is there any other way to perfom this one?......if there, plz let me know....if any alternative.....As I said earlier, the alternative is to emulate the PBE process yourself but what would be the point. You would just end up with gibberish if you use the wrong password.
    P.S. You won't always get a bad padding exception if you use the wrong password. About 1in 256 you will just get gibberish as the result without the exception.
    P.P.S. Your keyboard seems to have a problem with it's '.' key. In your place I would get it fixed because the perpetual '......' annoys the hell out of many people who respond to these forums.
    P.P.P.S. Your 'caps' key seems to be intermittently broken. Please get if fixed.
    P.P.P.P.S. You should turn off your computer's SMS mode. Using 'u' instead of 'you' makes your posts very difficult to read and it annoys the hell out of many people who respond to these forums.

  • Unexpected Expection in perform:  Given final block not properly padded

    Hi folks,
    I am trying to encrypt some data and passing through the url and getting it back and decrypting it. But it's working every time and some times it's giving the below exception.
    Unexpected Expection in perform: Given final block not properly padded
    javax.crypto.BadPaddingException: Given final block not properly padded
    Here is the code i am using to encrypt and decrypt it..
    SecretKey key = EncryptDecrypt.getHardCodedKey();
    String encriptedCSID = EncryptDecrypt.encryptString(key, Integer.toString(customerId));
    String encriptedAgreementId = EncryptDecrypt.encryptString(key, Integer.toString(agreementId));
                        Here are the other methods tooo
    public static String encryptString(SecretKey key, String input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
             Cipher cipher = Cipher.getInstance("DESede");
             cipher.init(Cipher.ENCRYPT_MODE, key);
             byte[] inputBytes = input.getBytes();
             byte[] encryptedBytes= cipher.doFinal(inputBytes);
             String encryptedString = new sun.misc.BASE64Encoder().encode(encryptedBytes);
             return URLEncoder.encode(encryptedString, "UTF-8");
             //return encryptedString;
    public static String decryptString(SecretKey key, String encryptedString) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
              // TODO Auto-generated method stub
              String ka = URLDecoder.decode(encryptedString, "UTF-8");
              byte[] encryptedBytes = new sun.misc.BASE64Decoder().decodeBuffer(ka);
              Cipher cipher = Cipher.getInstance("DESede");
              cipher.init(Cipher.DECRYPT_MODE, key);
              byte[] recoveredBytes = cipher.doFinal(encryptedBytes);
              String recoveredString = new String(recoveredBytes);
              return recoveredString;
    public static SecretKey getHardCodedKey() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
             byte[] keyBytes = { 37, -51, -14, -113, -2, 124, -50, -125, -2, 118, 28, 94, -45, -3, -125, 22, 93, 81, 91, -53, 124, 28, 31, 127 };
              DESedeKeySpec keySpec = new DESedeKeySpec(keyBytes);
              SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
              SecretKey key = keyFactory.generateSecret(keySpec);
              return key;
    SecretKey key = EncryptDecrypt.getHardCodedKey();
                        String decryptedCustomerID = EncryptDecrypt.decryptString(key, customerId);
                        String decryptedAgreementId = EncryptDecrypt.decryptString(key, agreementId);Could you please help me .. i didn't see any problem with it. some time it's giving problem and rest of the time it's working good.
    Thanks,

    I am trying to use the Hex encoding. So when ran it as a java application which is working fine. And whn i incorporated the same in my code and deployed the ear.. i am getting this exception.
    And i have included the jar file in the ear. I didn't understand wht's happeining.. any help?
    4 gov.ed.telework.delegate.TeleworkDelegate - got RemoteException RemoteException occurred in server thread; nested exception is:
         java.rmi.RemoteException: ; nested exception is:
         java.lang.NoClassDefFoundError: org.apache.commons.codec.binary.Hex
    10/09 12:12:49 execute 100 WebContainer : 4 gov.ed.telework.ui.EmpTeleworkAgreementAction - Unexpected Expection: Exception occurred.. Here is the modified code.
    public static String encryptString(SecretKey key, String input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
             Cipher cipher = Cipher.getInstance("DESede");
             cipher.init(Cipher.ENCRYPT_MODE, key);
             //byte[] inputBytes = input.getBytes();
             byte[] inputBytes = input.getBytes("UTF-8");
             byte[] encryptedBytes= cipher.doFinal(inputBytes);
             //String encryptedString = new sun.misc.BASE64Encoder().encode(encryptedBytes);
             String abc = org.apache.commons.codec.binary.Hex.encodeHexString(encryptedBytes);
             return abc;
             //return URLEncoder.encode(encryptedString, "UTF-8");
             //return encryptedString;
    public static String decryptString(SecretKey key, String encryptedString) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, DecoderException {
              // TODO Auto-generated method stub
             byte  abc[] = org.apache.commons.codec.binary.Hex.decodeHex(encryptedString.toCharArray());
             //String ka = URLDecoder.decode(encryptedString, "UTF-8");
              //byte[] encryptedBytes = new sun.misc.BASE64Decoder().decodeBuffer(ka);
              Cipher cipher = Cipher.getInstance("DESede");
              cipher.init(Cipher.DECRYPT_MODE, key);
              //byte[] recoveredBytes = cipher.doFinal(encryptedBytes);
              byte[] recoveredBytes = cipher.doFinal(abc);
              //String recoveredString = new String(recoveredBytes);
              String recoveredString = new String(recoveredBytes,"UTF-8");
              return recoveredString;
         }Thanks,

  • Exception: Given final block not properly padded

    Hi,
    I generated an password encrypted RSA private key using the following openssl command.
    openssl pkcs8 -topk8 -in private.pem -outform DER -out private.der -v2 des3
    I am using the following piece of code to decrypt private.der using a password entered by the user.
    For now, I assume that the password is of 24 bytes long.
    1. The following method throws an exception saying "Given final block not properly padded."
    How can I fix it?
    2. Since private.der is created by openssl, I didn't provide salt and iv paramters.
    Are they embedded in the file itself?
    Does the objects in the following method takes care of them automatically?
    Thanks.
    public byte[] readDES3EncryptedPrivateKey2(final String password,
                                                final String privateKeyFilePath)
    throws Exception
            File privateKeyFile = new File(privateKeyFilePath);
            byte[] encryptedPrivateKey = FileUtils.readFileToByteArray(privateKeyFile);
            final byte[] passwordInBytes = password.getBytes("UTF-8");
            DESedeKeySpec keySpec = new DESedeKeySpec(passwordInBytes);
            SecretKey key = SecretKeyFactory.getInstance(DES3).generateSecret(keySpec);
            javax.crypto.EncryptedPrivateKeyInfo epki = new javax.crypto.EncryptedPrivateKeyInfo(
                    encryptedPrivateKey);
            AlgorithmParameters ap = epki.getAlgParameters();
            des3Cipher.init(Cipher.DECRYPT_MODE, key, ap);
            // Error: Given final block not properly padded
            return des3Cipher.doFinal(epki.getEncryptedData());
        }

    I've run into similar things. Have you tried padding the data you are trying decrypt to the block size of DES3?

  • Given final block not properly padded

    I am working on an application that sends encrypted data over the network using Blowfish. I developed a simple server and client to test and I getting this error when I try to decrypt the cypher in the server. Here is what I do:
    This happens on the client side:
    I encrypt my message with this method
    public byte[] encryptedMessage() throws Exception{
            KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
            keyGenerator.init(128);     
            Key key = keyGenerator.generateKey();
            Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plaintext = getMessage().getBytes("UTF8");
            byte[] ciphertext = cipher.doFinal(plaintext);
            return ciphertext;
        }Then send it to the server like this:
    //get my cypher from the method shown before
    cipher = mc.encryptedMessage();
    //put the cypher in this simple object          
    InformationShared cipherToSend = new InformationShared(cipher.length);
    cipherToSend.setMessage(cipher);
    //Send it accross through the network
    Socket socket =  new Socket("127.0.0.1",8085);
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    out.writeObject(cipherToSend);This is what happens in the server side:
    //Get the incoming object
    ObjectInputStream in = new ObjectInputStream( incoming.getInputStream() );
    //downcast the object
    InformationShared cipherIn = (InformationShared)in.readObject();
    //decypher the message  in the decypher method             
    String result = decypher(cipherIn.getMessage());
    //This is the decipher method
    public String decypher(byte cipherIn[]) throws Exception{
               KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
               keyGenerator.init(128);     // need to initialize with the keysize
               Key key = keyGenerator.generateKey();
               Cipher ciph = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
               ciph.init(Cipher.DECRYPT_MODE, key);
               // Perform the decryption
               byte[] decryptedText = ciph.doFinal(cipherIn);
               String output = new String(decryptedText,"UTF8");;
               return output;
            }The error happens in the decypher method in this line:
    byte[] decryptedText = ciph.doFinal(cipherIn);Thanks for any help!

    Hi
    I am woriking on an web application that send Encrypted data over the network and stores into the databse.After that I want to retrieve that data from database then I want decrypt it by using DES.
    After Encryting It is storing properly into the database but while retriving from database and want to decrypt it the It is giving exception like "javax.crypto.BadPaddingException: Given final block not properly padded"
    For Encryption I am using one bean class tha are
    package EncryptBean;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.*;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    import java.security.InvalidAlgorithmParameterException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    import javax.crypto.*;
    public class DesEncrypterBean {
    Cipher ecipher;
    Cipher dcipher;
    public DesEncrypterBean(SecretKey key) {
    try {
    ecipher = Cipher.getInstance("DES");
    dcipher = Cipher.getInstance("DES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch(javax.crypto.NoSuchPaddingException e)
         {System.out.println("NoSuchPaddingException : "+e);     
                } catch (java.security.NoSuchAlgorithmException e)
    {System.out.println("NoSuchAlgorithmException : "+e);     
                } catch (java.security.InvalidKeyException e)
    {System.out.println("InvalidKeyException : "+e); }
    public String encrypt(String str) {
    try {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");
    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);
    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
    } catch (javax.crypto.BadPaddingException e) {
    System.out.println("encrypt BadPaddingException : "+e);
    } catch (IllegalBlockSizeException e) {
    System.out.println(" encrypt IllegalBlockSizeException : "+e);
    } catch (UnsupportedEncodingException e) {
    System.out.println("encrypt UnsupportedEncodingException : "+e);
    } catch (java.io.IOException e) {
    System.out.println("encrypt IOException : "+e);
    } return null;
    public String decrypt(String str) {
    try {
    // Decode base64 to get bytes
    // byte[] utf8 = str.getBytes("UTF8");
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    // Decrypt
    byte[] utf8 = dcipher.doFinal(dec);
    // Decode using utf-8
    return new String(utf8, "UTF8");
    } catch (javax.crypto.BadPaddingException e)
         {System.out.println("encrypt BadPaddingException : "+e);
                } catch (IllegalBlockSizeException e) {
    System.out.println("encrypt IllegalBlockSizeException : "+e);
    } catch (UnsupportedEncodingException e) {
    System.out.println("encrypt UnsupportedEncodingException : "+e);
    }catch (java.io.IOException e) {
    System.out.println("encrypt IOException : "+e);
    return null;
    ** By using bellow screen I am retrieving the data from screen and encrypting it and sended to the database I is working properly
    import EncryptBean.DesEncrypterBean;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.*;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    import java.security.InvalidAlgorithmParameterException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import sun.misc.BASE64Encoder;
    import javax.crypto.*;
    public class Secure_Encrypt extends HttpServlet
              Connection con=null;
              Statement stmt=null;
              Cipher ecipher;
    Cipher dcipher;
              String uname=null,pwd=null;
              ServletOutputStream sos;
              SecretKey key=null;
    public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException
    uname=req.getParameter("username");               pwd=req.getParameter("password");
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:GMT","sa","iqm");
    stmt=con.createStatement();
    sos=res.getOutputStream();
    // Generate a temporary key. In practice, you would save this key.
    // See also e464 Encrypting with DES Using a Pass Phrase.
    key = KeyGenerator.getInstance("DES").generateKey();
    // Create encrypter/decrypter class
    DesEncrypterBean encrypter = new DesEncrypterBean(key);
    // Encrypt
    String encrypted = encrypter.encrypt(uname);
    System.out.println("Don't tell anybody! "+encrypted);
    stmt.execute("insert into Admin(UserName,Passward) values('"+encrypted+"','"+encrypted+"')");
    System.out.println("......record saved");
    sos.println("Record Saved : "+encrypted);
    catch(Exception e)
    {System.out.println("Exception in login" +e);}
    In above Programe Woking Properly
    ** Bellow programe using for retrieving data from database.After retrieving data I want Decrypt it but not working properly
    import EncryptBean.DesEncrypterBean;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.*;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    import java.security.InvalidAlgorithmParameterException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import sun.misc.BASE64Encoder;
    import javax.crypto.*;
    public class Secure extends HttpServlet
              Connection con=null;
              Statement stmt=null;
              Cipher ecipher;
    Cipher dcipher;
              String uname=null,pwd=null;
              ServletOutputStream sos;
              SecretKey key=null;
    public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException
    try
    {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:GMT","sa","iqm");
    stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery("select UserName,Passward from Admin");
    while(rs.next())
         uname=rs.getString(1);
         pwd=rs.getString(2);
    sos=res.getOutputStream();
    // Generate a temporary key. In practice, you would save this key.
    // See also e464 Encrypting with DES Using a Pass Phrase.
    key = KeyGenerator.getInstance("DES").generateKey();
    // Create encrypter/decrypter class
    DesEncrypterBean encrypter = new DesEncrypterBean(key);
    // Decrypt
    uname=uname.trim();
    String decrypted = encrypter.decrypt(uname);
    System.out.println("Original message is! "+decrypted);
    }catch(Exception e)
    {System.out.println("Exception in login" +e);
    In above Programe giving Exception " javax.crypto.BadPaddingException: Given final block not properly padded"
    Please analyze my application and send me suitable solution for decryption
    one more thing When I encrypting that time KeyGenerator generating one key.same as when I Decrypting that time also KeyGenerator generating one key but both are not same.
    How can we generate both key are same

Maybe you are looking for

  • Trying To Understand Display List In AS3

    I have FLA 01. I create a loader in FLA 01. I use the loader to load SWF 02 and when the load is complete add SWF 02 to the stage and place it in a movie clip. So far, so good. SWF 02 is a rather complicated file. It dynamically creates in ActionScri

  • New in NW04s: FL069 TABLES parameters are obsolete (in function modules)

    Can somebody explain what is the fundamental reason for this behaviour in NW04s? In Netweaver 2004s system (like ERP2005 ) you get a warning message in SE37: FL069 TABLES parameters are obsolete! when defining quite ordinary tables parameter using LI

  • [OBIEE 11g]Can "Static Text" use parameter like "Narrative"?

    We need to add some notes to a report and need get text from one column of result. I know we can use @1 to get the 1st column in Narrative, but in Static Text it fails. Does Static Text support that? We need this because in 11g, "HTML markup" broken

  • How I can return the replication groups to be in the normal state again?

    Hi All, can anybody help me on the following issue: after executing "*exec dbms_repcat.suspend_master_activity(gname=>'RG_EARMS');*" I got the following and it rejected to resume the replication again: SQL>select job, what from dba_jobs where what li

  • Permissions problems in panther?

    Hi - I am having an odd problem at work. We have 2 eMacs for the kids to use for the film club (which is going very well, BTW), and I also have some freeware and shareware games on these, as well as office and a few other programs. Here's the problem