Finally block is optional??

I want to know if finally block is optional? I tested this myself, and
the following yield the same output.
void f()
     try
     { //code1
     catch()
     finally
     { //code2
void f()
     try
     { //code1
     catch()
     //code2
please advise. thanks!!

I'm not sure what you're asking, and your sample code tells us almost nothing, but I'll take a guess.
You're thinking finally doesn't do anything, because you can just put the code after the catch block, right?
Here's some more realistic code: void foo() throws IOException {
    InputStream ins = null;
    try {
        Bar bar = new Bar(); // this might throw BarException
        ins = bar.getAnInputStream();
        ins.read(); // etc.
        // do stuff with what we read from ins
    catch (BarException exc) {
        // log, handle, whatever
    finally {
        // cleanup, for example ins.close();
    // OR we could cleanup here, you think, right?
} If the try block completes without any problems, or if a BarException is thrown and we don't rethrow anything from the catch block, then, yes, you could put the cleanup after the finally block.
However, what happens if bar.getAnInputStream() returns null? Or if there's an IOException creating or reading the stream? In that case, we jump out of our try block as soon as the exception occurs--the IOException or the NPE if we try to call read() on a null stream reference.
In this case the try block stops what it's doing and control passes to the finally block, after which we leave the method (well, leave the try statement for the next enclosing try, but there isn't one in this method, so we leave the method).
If we throw an uncaught exception (anything other than IOE, in this example) or even if we call return from inside the try block, the finally block will always be executed. The code following the finally block won't be executed in these cases.
¶

Similar Messages

  • 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.

  • How finally block can be evaded??

    i want to write a finally block but don't want to execute it.
    plz dont suggest application.exit(). i want to continue with my program
    plz answer

    I want to write a finally block but don't want to execute it.You have several options.
    - don't enter into the try block associated with your finally block
    - embed the content of the finally block with "if (false) { ... }" - well the finally block is executed, but the contents of the if block is not
    - throw an exception right at the start of the finally block - almost the same as above
    - investigate if this is of any use for your objective: "An application should not normally try to catch ThreadDeath unless it must do some extraordinary cleanup operation (note that the throwing of ThreadDeath causes finally clauses of try statements to be executed before the thread officially dies). If a catch clause catches a ThreadDeath object, it is important to rethrow the object so that the thread actually dies." from: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#stop()

  • 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

  • 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)

  • How to block delete option in va01 , va02, va03

    hi,
    i like to know how to block delete option in va01 , va02, va03.  I need to block the delete option in the menu to delete the sales order by the user.
    Please reply ASAP.
    <removed_by_moderator>
    Please read the "Rules of Engagement"
    thanks in Advance,
    With best regards,
    sathies
    Edited by: Juan Reyes on Jul 29, 2008 1:05 PM

    Hi,
    Do a user trace in st01 for that transaction and find which auth object it is refering to and the auth value then maintain the values accordingly.
    Regards,
    Vamshi.

  • Block HTTP Options request in DBMS_EPG

    We are having some trouble opening HTML pages from Office tools in combination with the Embedded PL/SQL Gateway on a Oracle 11g database.
    When we open a public Apex page from word or Excel it will prompt for XDB username / password.
    We open the page like this: http://epg-host:8080/apex/f?p=111:1
    When we open the same page from the same Apex application using the Oracle HTTP Server instead of the Embedded PL/SQL Gateway, Word and Excel won't prompt for a username and password.
    I used Wireshark to see the difference in HTTP traffic. Microsoft Office will do a HTTP Options request on the "directory" of the page (for the url http://epg-host:8080/apex) before opening the page. The HTTP Options request results Error 401 Unauthorized, that’s why Word/Excel ask the user to login.
    With a HTTP Send Tool I have send the Options Request to the Embedded PL/SQL Gateway and to the Oracle HTTP Server, these are the different responses:
    Options for http://epg-host:8080/apex/
    The remote server returned an error: (401) Unauthorized.
    MS-Author-Via     DAV
    DAV     1,2,<http://www.oracle.com/xdb/webdav/props>
    Content-Length     147
    Content-Type     text/html; charset=UTF-8
    Date     Thu, 10 Nov 2011 10:05:56 GMT
    Server     Oracle XML DB/Oracle Database
    WWW-Authenticate     Basic realm="XDB"
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <HTML><HEAD>
    <TITLE>401 Unauthorized</TITLE>
    </HEAD><BODY><H1>Unauthorized</H1>
    </BODY></HTML>Options for http://apache-host:7778/apex/
    The remote server returned an error: (501) Not Implemented.
    Allow     
    Connection     close
    Content-Length     252
    Content-Type     text/html; charset=iso-8859-1
    Date     Thu, 10 Nov 2011 10:15:44 GMT
    Server     Oracle-Application-Server-11g
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html><head>
    <title>501 Method Not Implemented</title>
    </head><body>
    <h1>Method Not Implemented</h1>
    <p>The server does not support the functionality required to fulfil the request.</p>
    </body></html>I do not really understand why the Options Request results in Unauthorized. I would like to change the behavior of the Embedded PL/SQL Gateway so that it does not throw the "Unauthorized" error. Any other error would be good, but Unauthorized results in a Login prompt.
    Does anyone know how to configure the Embedded PL/SQL Gateway so it will not result in the unauthorized error? It doesn’t matter if I have to block the Options requests or grant extra authorization.

    Thanks for your reply. When we open the page in the browser we do not get the Login-prompt, the allow-repository-anonymous-access is already set to true.
    The login-prompt only occurs when we open the page from Word/Excel, that's when the HTTP-Options request is send.
    Opening an Apex page in the browser only results in a HTTP-Get request, Word/Excel will send HTTP-Options followed by the HTTP-Get request.

  • 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,

Maybe you are looking for

  • Playing Music in iTunes Not Working

    I can select a song to be played and when the end of the song is reached it simply stops playing music. If I hit 'next' the current song being played pauses. I have shuffle on. Any ideas out there on how to fix this??

  • Finder sees a shared volume, but cannot mount it

    I have a problem with a G5 that is on a network with a Mini and a G4, both set to up for Sharing. The Mini is also a print server. (1) The G5 cannot log onto either the Mini or the G5. The G5 Finder sees and identifies both in Server Browse. It just

  • X-FI AUDIO CONSOLE WILL NOT LAUNCH

    have ran x-fi card fine for 3 months and after re-installing it after moving it for new graphics card the audio console will not launch ! I get the message device not on this computer even though its working fine i just cannot launch the console to a

  • Print document titles in folder

    I have a folder full of recipes, 500 of them, and I want to just print the titles out. How?

  • Advantages and disadvantages of UML

    Hi I wonder if u guys can help, I am interested in learning about modelling in general and I am trying to find information on the advantages and disadvantages of UML as a modelling language compared to other modelling techniques. I have only found sm