Javax.crypto.* problem in WLW

Hi,
I am trying to encrypt a String in WLW 8.1 SP2.
The IDE is not recognizing javax.crypto.* package. When I use the same code and
execute it with TextPad, it works just fine.
FYI, the non-WLS JDK is 1.4.1_01-b01 and WLS uses 1.4.1_05.
What do I need to do to be able to use javax.crypto.* packages in WebLogic? Any
helpis greatly appreciated.
Thanks, Eric

I had to add it manually:(
* Go to application properties (Tools Menu > Application Properties... Menu
Item)
* Under WebLogic Server look for Server classpath additions:
* Click add jar
* Navigate to jdk\jre\lib\jce.jar
* Add the jar file
"Eric J" <[email protected]> wrote in message
news:404e34a9$[email protected]..
>
Hi,
I am trying to encrypt a String in WLW 8.1 SP2.
The IDE is not recognizing javax.crypto.* package. When I use the samecode and
execute it with TextPad, it works just fine.
FYI, the non-WLS JDK is 1.4.1_01-b01 and WLS uses 1.4.1_05.
What do I need to do to be able to use javax.crypto.* packages inWebLogic? Any
helpis greatly appreciated.
Thanks, Eric

Similar Messages

  • Javax.crypto.* and javax.crypto.spec.* problem with MHP receiver

    Hello to everyone, I started to program in MHP 1.0.2 on a MHP receiver and now i'm practicing in encrypting and decrypting. I load from the smart card in the MHP receiver an X509Certificate object (I have it both in byte[] form, called certArray, and X509Certificate object, called "certificate"). What i'd like to do is to :
    1)calculate digest of the certificate (line 1 and 2 of the following code)
    2) encrypt the digest using the same algorithm of the certificate (see line 3 and 4)
    The problem is generated at line 3 : the receiver, probably, doesn't find the class of the algorithm of encrypting. It is important to notice that the instruments to encrypt/decrypt are included in javax.crypto and javax.crypto.spec packages.
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] digest = md.digest(certArray);
    Cipher encrypt = Cipher.getInstance(certificate.getSigAlgName());
    encrypt.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey());
    The error message, in the log file, is the following :
    [0#1:2] java.security.NoSuchAlgorithmException: SHA1withRSA not found
         [0#1:2]      at javax.crypto.Cipher.getInstance(Ljava/lang/String;)Ljavax/crypto/Cipher;(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.encrypt()V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.cardInserted(Lopencard/core/event/CardTerminalEvent;)V(Unknown Source)
         [0#1:2]      at opencard.core.event.EventGenerator.createEventsForPresentCards(Lopencard/core/event/CTListener;)V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.register()V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.startXlet()V(Unknown Source)
         [0#1:2]      at java.lang.reflect.Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.xletStart()Z(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.loop0(Ltv/osmosys/application/AppManager$XletAction;)V(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.run()V(Unknown Source)
         [0#1:2]      at java.lang.Thread.run()V(Unknown Source)
         [0#1:2]      at java.lang.Thread.startup(Z)V(Unknown Source)
    My question(s) is : how can I include javax.crypto and javax.crypto.spec in the Xlet application to upload it onto the MHP receiver?? Is it possibile to do so?
    Eventually, do other libraries exist to use encrypting algorithms, included in MHP? The version I use of MHP is 1.0.2. Thank you! Bye!

    Hello to everyone, I started to program in MHP 1.0.2 on a MHP receiver and now i'm practicing in encrypting and decrypting. I load from the smart card in the MHP receiver an X509Certificate object (I have it both in byte[] form, called certArray, and X509Certificate object, called "certificate"). What i'd like to do is to :
    1)calculate digest of the certificate (line 1 and 2 of the following code)
    2) encrypt the digest using the same algorithm of the certificate (see line 3 and 4)
    The problem is generated at line 3 : the receiver, probably, doesn't find the class of the algorithm of encrypting. It is important to notice that the instruments to encrypt/decrypt are included in javax.crypto and javax.crypto.spec packages.
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] digest = md.digest(certArray);
    Cipher encrypt = Cipher.getInstance(certificate.getSigAlgName());
    encrypt.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey());
    The error message, in the log file, is the following :
    [0#1:2] java.security.NoSuchAlgorithmException: SHA1withRSA not found
         [0#1:2]      at javax.crypto.Cipher.getInstance(Ljava/lang/String;)Ljavax/crypto/Cipher;(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.encrypt()V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.cardInserted(Lopencard/core/event/CardTerminalEvent;)V(Unknown Source)
         [0#1:2]      at opencard.core.event.EventGenerator.createEventsForPresentCards(Lopencard/core/event/CTListener;)V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.register()V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.startXlet()V(Unknown Source)
         [0#1:2]      at java.lang.reflect.Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.xletStart()Z(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.loop0(Ltv/osmosys/application/AppManager$XletAction;)V(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.run()V(Unknown Source)
         [0#1:2]      at java.lang.Thread.run()V(Unknown Source)
         [0#1:2]      at java.lang.Thread.startup(Z)V(Unknown Source)
    My question(s) is : how can I include javax.crypto and javax.crypto.spec in the Xlet application to upload it onto the MHP receiver?? Is it possibile to do so?
    Eventually, do other libraries exist to use encrypting algorithms, included in MHP? The version I use of MHP is 1.0.2. Thank you! Bye!

  • HMAC_SHA1 encryption using javax.crypto.MAC performance problems in SPARC

    Hi, I'm trying to implement a method to synchronize TOTP cards. In case the server clock and the card clock were different. So I generate a lot of TOTP keys in case to compare it with the real key so at the end I get both of the times in the server. That works in x86 (Sunfire x2200) perfectly and does not take a lot of time doing that (like 2 minutes generating 800000 keys). But when I test it on Oracle BM SPARC (T1000 LDOM 1.1) takes I lot of time. I did all kind of profiling stuff but all point to the method of the generation the TOTP in the HMAC_SHA1.
    here is the code (based on JBoss 6 OTP implementation)
    public synchronized static String generateTOTP(String key, String time,  int returnDigits, String crypto) throws GeneralSecurityException {
              String result = null;
              byte[] hash;
              // Using the counter
              // First 8 bytes are for the movingFactor
              // Complaint with base RFC 4226 (HOTP)
              while(time.length() < 16 ) {
                   time = "0" + time;
              // Get the HEX in a Byte[]
              byte[] msg = hexStr2Bytes(time);
              // Adding one byte to get the right conversion
              byte[] k = hexStr2Bytes(key);
              hash = hmac_sha1(crypto, k, msg);
              // put selected bytes into result int
              int offset = hash[hash.length - 1] & 0xf;
              int binary =
                   ((hash[offset] & 0x7f) << 24) |
                   ((hash[offset + 1] & 0xff) << 16) |
                   ((hash[offset + 2] & 0xff) << 8) |
                   (hash[offset + 3] & 0xff);
              int otp = binary % DIGITS_POWER[ returnDigits ];
              result = Integer.toString(otp);
              while (result.length() < returnDigits ) {
                   result = "0" + result;
              return result;
    private static byte[] hmac_sha1(String crypto, byte[] keyBytes, byte[] text) throws GeneralSecurityException {
              Mac hmac;
              hmac = Mac.getInstance(crypto);
              SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
              hmac.init(macKey);
              return hmac.doFinal(text);
    }The release of the version to production is delayed about this. I need help either to use another library or finding the right configuration for the SPARC.
    Thanks in advance to everybody.
    danielfjb

    Well It is the only approach that I came up. It is supposed the code runs max. one time per user in production, that depends in the synchronization between the server clock and the OTP card clock.
    Basically the algorithm takes two consecutive keys (each 30 seconds the password changes) from the user, saving the time (server clock) for each one when the user clicks next. With both keys the server look up at what time (in server clock) the key has been generated. Performing a simple subtraction I can get the difference of times when the user generates the otp and when the server generates it.
    The algorithm simply look up five days ago, and five days further the same key each 30 simulated seconds, and reports the time when it founds an equal key. It's a brute force search, but in this case I really don't know how to do it differently.
    So the problem is in the type of server, because in the x86 runs the synchronization in 3 minutes or less, but in the SPARC takes 30 minutes or maybe more. It should be some native code that has problems with this implementation of javax.crypto.Mac
    Hope I do make my self clear
    Thank you

  • Problem when using javax.crypto.KeyGenerator in netbeans

    This is my IDE information:
    Product Version: NetBeans IDE 6.0.1 (Build 200801291616)
    Java: 1.6.0_03; Java HotSpot(TM) Client VM 1.6.0_03-b05
    System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)
    I am trying to develop a Test jar file. I created some simple jar files and could upload it in mobile.
    Now I want to implement some encryption. For that I started writing codes. But when trying to import javax.crypto.KeyGenerator class, netbeans is showing "cannot find symbol" error. I can use javax.crypto.Cipher/BadPaddingException/IllegalBlockSizeException/NoSuchPaddingException/spec/ShortBuffrException only. If i try to use any other class of javax.crypto, i get an error.
    I am new to mobility.I downloaded netbean mobility package and Installed it.
    Please provide some help.. thank you....

    This is my IDE information:
    Product Version: NetBeans IDE 6.0.1 (Build 200801291616)
    Java: 1.6.0_03; Java HotSpot(TM) Client VM 1.6.0_03-b05
    System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)
    I am trying to develop a Test jar file. I created some simple jar files and could upload it in mobile.
    Now I want to implement some encryption. For that I started writing codes. But when trying to import javax.crypto.KeyGenerator class, netbeans is showing "cannot find symbol" error. I can use javax.crypto.Cipher/BadPaddingException/IllegalBlockSizeException/NoSuchPaddingException/spec/ShortBuffrException only. If i try to use any other class of javax.crypto, i get an error.
    I am new to mobility.I downloaded netbean mobility package and Installed it.
    Please provide some help.. thank you....

  • Unable to Decrypt the data properly using javax.crypto class and SunJCE

    Hello all,
    I am not new to Java but new to this forums
    but and JCE and i wanted to write a program that Encrypts a file and also another program that decrypts it. As far Encryption is concerned i have been successful but When it comes to Decryption things aren't looking bright i have some or the other Problem with it. plz help me out .
    Here is the Code for my Programs
    Encryption
    Code:
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.*;
    import javax.swing.*;
    class MyJCE
    public static void main(String args[])throws Exception
    Provider sunjce = new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sunjce);
    JFileChooser jfc = new JFileChooser();
    int selection= jfc.showOpenDialog(null);
    if(selection==JFileChooser.APPROVE_OPTION)
    FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
    System.out.println("Selected file " + jfc.getSelectedFile());
    try{
    KeyGenerator kg = KeyGenerator.getInstance("DESede");
    SecretKey key= kg.generateKey();
    byte[] mkey=key.getEncoded();
    System.out.println(key);
    SecretKeySpec skey = new SecretKeySpec(mkey, "DESede");
    Cipher cipher=Cipher.getInstance("DESede/ECB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE,skey);
    byte[] data= new byte[fis.available()];
    //reading the file into data byte array
    byte[] result= cipher.update(data);
    byte[] enc= new byte [fis.read(result)];
    System.out.println("Encrypted =" + result);
    File fi= new File("/home/srikar/Encrypted");
    FileOutputStream fos= new FileOutputStream(fi);
    fos.write(enc);
    fos.close();
    byte[] encodedSpeckey = skey.getEncoded();
    FileOutputStream ks= new FileOutputStream("./key.txt");
    ks.write(encodedSpeckey);
    System.out.println("Key written to a file");
    }//try
    catch(Exception ex)
    ex.printStackTrace();
    }//catch
    }This Creates a Encrypted File. and a Encrypted key.txt
    Code:
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.*;
    import javax.swing.*;
    class Decrypt
    public static void main(String[] args)
    try
    JFileChooser jfc = new JFileChooser();
    int selection= jfc.showOpenDialog(null);
    if(selection==JFileChooser.APPROVE_OPTION)
    FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
    System.out.println("Selected file " + jfc.getSelectedFile());
    //Read from the Encrypted Data
    int ll= (int)jfc.getSelectedFile().length();
    byte[] buffer = new byte[ll];
    int bytesRead=fis.read(buffer);
    byte[] data= new byte[bytesRead];
    System.arraycopy(buffer,0,data,0,bytesRead);
    //Read the Cipher Settings
    FileInputStream rkey= new FileInputStream("./key.txt");
    bytesRead = rkey.read(buffer);
    byte[] encodedKeySpec=new byte[bytesRead];
    System.arraycopy(buffer,0,encodedKeySpec,0,bytesRead);
    //Recreate the Secret Symmetric Key
    SecretKeySpec skeySpec= new SecretKeySpec(encodedKeySpec,"DESede");
    //create the cipher for Decrypting
    Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE,skeySpec);
    byte[] decrypted= cipher.update(data);
    FileOutputStream fos= new FileOutputStream("/home/srikar/Decrypted");
    fos.write(decrypted);
    }//if
    }//try
    catch(Exception e)
    e.printStackTrace();
    }//catch
    }//main
    }//classthis Decrypt.java is expected to decrypt the above encrypted file but this simply creates a plaintext file of the same size as the Encrypted file but its contents are unreadable.
    Or I endup with Exceptions like BadPadding or IllegalBlockSize Exception if i use any other Algorithm .
    Please help out
    thanx in advance

    Srikar2871 wrote:
    Well thanx for ur reply but
    As i said there are No issues with ENCRYPTION and am getting an Encrypted file exactly of the same size as that of the original file and NOT as null bytes and Even am able to get a Decrypted file of again the same size of the Encrypted File but this time that data inside is in unreadable format.I ran your code EXACTLY* as posted and the contents of the file when viewed in a Hex editor was
    00 00 00 00 00 00 00 00 00 00 00 00 00 00 00So unless you are running different code to what you have posted, your file will look the same.
    Cheers,
    Shane

  • Javax.crypto missing in my webdynpro project

    Hello
    I am trying to develop application which uses DES crypto function.
    I have an example of code which should work but the problem is with the JCE crypto library it uses.
    In normal java project I can import javax.crypto but in my web dynpro DC component I simply can't.
    Is there any way to add this library?
    Thanks for any help.

    I found the solution myself and it was quiet simple.
    Just open the properties of the project and add external JAR to java build path. The library I was seeking is located in program files/java/jre.../lib and its the jce.jar.
    The other problem I am having with this is that when I try to build the development component, the jce.jar is removed from the build path and the previous error persists. It is strange because when I simply choose rebuild project and then deploy, everything works.

  • 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

  • Javax.crypto reference in NW Dev Studio

    Has anyone encountered and resolved the issue with trying to reference javax.crypto.* as an import with the Netweaver Development Studio? 
    i.e. Add a line like the following to your code:
    Cipher c;
    Then organise imports; and javax.cryto.cipher will be added but not found.
    Thanks,
    Matt

    Simple really - Just needed to add JCE.jar reference to project (wasn't automatically done like the others).  Oh well - now I can debug my provider problem.

  • JMS SAF client cannot forward messages - Caused by: javax.crypto.BadPadding

    Hi,
    I seem to be struggling with a problem that I'm not sure if I can ever find a solution.
    I have a configured a local JMS client to forward my messages to a remote WLSB 9.2.
    The local client is running JDK 1_0_14 on a windows platform.
    The remote server is on IBM JRE on linux. Now I'm getting problems when the messages are forwarded by the local SAF client. The client does not seem to be able to decrypt the password I have in my SAFClient.xml. I have pretty much followed every line in the documentation of SAF client and has already revisited it a few times.
    It seems to be something to do with the ClientSAFEncrypt utility that I was advised to get the encrypted password which I have put in the XML File. Here is the exception. Any help will be greatly appreciated.
    All I know is it is something to do with encoding of the password, but I cannot get a clue what else.
    <Mar 25, 2008 12:28:40 PM PDT> <Info> <Store> <BEA-280050> <Persistent store "SAFSTORE0V" opened: directory="C:\depot\javaSrc\logging\stores\default" writePolicy="Direct-Write" blockSize=512 directIO=false driver="NIO">
    javax.naming.NamingException: Invalid password key to unlock the passwords in the configuration file [Root exception is weblogic.jms.common.JMSException: Invalid password key to unlock the passwords in the configuration file]
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getNamingException(InitialContextFactoryImpl.java:31)
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:162)
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
         at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
         at javax.naming.InitialContext.init(InitialContext.java:223)
         at javax.naming.InitialContext.<init>(InitialContext.java:197)
         at com.netflix.messaging.ESBFactory.<init>(ESBFactory.java:103)
         at com.netflix.messaging.ESBFactory.getFactory(ESBFactory.java:45)
         at com.netflix.messaging.NFMessagingManager.getProducerHandle(NFMessagingManager.java:218)
         at com.netflix.messaging.NFMessagingManager.initProducers(NFMessagingManager.java:730)
         at com.netflix.messaging.NFMessagingManager.init(NFMessagingManager.java:863)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1461)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1628)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.startMessagingManager(MessageDestinationDispatcher.java:164)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.<init>(MessageDestinationDispatcher.java:25)
         at com.netflix.logging.NFMessageAppender.append(NFMessageAppender.java:72)
         at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
         at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
         at org.apache.log4j.Category.callAppenders(Category.java:206)
         at org.apache.log4j.Category.forcedLog(Category.java:391)
         at org.apache.log4j.Category.log(Category.java:838)
         at com.netflix.logging.log4jAdapter.Log4jLoggingAdapter.log(Log4jLoggingAdapter.java:64)
         at com.netflix.logging.NFLogger.log(NFLogger.java:125)
         at com.netflix.logging.LogManager.info(LogManager.java:152)
         at com.netflix.logging.aggregator.Bucketer.init(Bucketer.java:92)
         at com.netflix.logging.aggregator.Bucketer.<init>(Bucketer.java:80)
         at com.netflix.logging.aggregator.TracerAggregator.<init>(TracerAggregator.java:29)
         at com.netflix.logging.aggregator.TracerAggregator.<clinit>(TracerAggregator.java:20)
         at com.netflix.logging.NFLogger.start(NFLogger.java:105)
         at com.netflix.logging.LogManager.registerLogger(LogManager.java:67)
         at com.netflix.logging.test.LoggingTest.sendDefault(LoggingTest.java:32)
         at com.netflix.logging.test.LoggingTest.main(LoggingTest.java:19)
    Caused by: weblogic.jms.common.JMSException: Invalid password key to unlock the passwords in the configuration file
         at weblogic.jms.safclient.admin.ConfigurationUtils.doRemoteContexts(ConfigurationUtils.java:475)
         at weblogic.jms.safclient.agent.AgentManager.<init>(AgentManager.java:54)
         at weblogic.jms.safclient.ClientSAFDelegate.open(ClientSAFDelegate.java:65)
         at weblogic.jms.safclient.ClientSAFImpl.open(ClientSAFImpl.java:62)
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:160)
         ... 30 more
    Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
         at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
         at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
         at com.sun.crypto.provider.SunJCE_af.b(DashoA12275)
         at com.sun.crypto.provider.PBEWithMD5AndDESCipher.engineDoFinal(DashoA12275)
         at javax.crypto.Cipher.doFinal(DashoA12275)
         at weblogic.jms.common.SecHelper.decryptString(SecHelper.java:140)
         at weblogic.jms.safclient.admin.ConfigurationUtils.doRemoteContexts(ConfigurationUtils.java:473)
         ... 34 more
    java.lang.IllegalStateException: Cannot create context: Invalid password key to unlock the passwords in the configuration file
         at com.netflix.messaging.ESBFactory.<init>(ESBFactory.java:106)
         at com.netflix.messaging.ESBFactory.getFactory(ESBFactory.java:45)
         at com.netflix.messaging.NFMessagingManager.getProducerHandle(NFMessagingManager.java:218)
         at com.netflix.messaging.NFMessagingManager.initProducers(NFMessagingManager.java:730)
         at com.netflix.messaging.NFMessagingManager.init(NFMessagingManager.java:863)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1461)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1628)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.startMessagingManager(MessageDestinationDispatcher.java:164)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.<init>(MessageDestinationDispatcher.java:25)
         at com.netflix.logging.NFMessageAppender.append(NFMessageAppender.java:72)
         at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
         at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
         at org.apache.log4j.Category.callAppenders(Category.java:206)
         at org.apache.log4j.Category.forcedLog(Category.java:391)
         at org.apache.log4j.Category.log(Category.java:838)
         at com.netflix.logging.log4jAdapter.Log4jLoggingAdapter.log(Log4jLoggingAdapter.java:64)
         at com.netflix.logging.NFLogger.log(NFLogger.java:125)
         at com.netflix.logging.LogManager.info(LogManager.java:152)
         at com.netflix.logging.aggregator.Bucketer.init(Bucketer.java:92)
         at com.netflix.logging.aggregator.Bucketer.<init>(Bucketer.java:80)
         at com.netflix.logging.aggregator.TracerAggregator.<init>(TracerAggregator.java:29)
         at com.netflix.logging.aggregator.TracerAggregator.<clinit>(TracerAggregator.java:20)
         at com.netflix.logging.NFLogger.start(NFLogger.java:105)
         at com.netflix.logging.LogManager.registerLogger(LogManager.java:67)
         at com.netflix.logging.test.LoggingTest.sendDefault(LoggingTest.java:32)

    Hi,
    I seem to be struggling with a problem that I'm not sure if I can ever find a solution.
    I have a configured a local JMS client to forward my messages to a remote WLSB 9.2.
    The local client is running JDK 1_0_14 on a windows platform.
    The remote server is on IBM JRE on linux. Now I'm getting problems when the messages are forwarded by the local SAF client. The client does not seem to be able to decrypt the password I have in my SAFClient.xml. I have pretty much followed every line in the documentation of SAF client and has already revisited it a few times.
    It seems to be something to do with the ClientSAFEncrypt utility that I was advised to get the encrypted password which I have put in the XML File. Here is the exception. Any help will be greatly appreciated.
    All I know is it is something to do with encoding of the password, but I cannot get a clue what else.
    <Mar 25, 2008 12:28:40 PM PDT> <Info> <Store> <BEA-280050> <Persistent store "SAFSTORE0V" opened: directory="C:\depot\javaSrc\logging\stores\default" writePolicy="Direct-Write" blockSize=512 directIO=false driver="NIO">
    javax.naming.NamingException: Invalid password key to unlock the passwords in the configuration file [Root exception is weblogic.jms.common.JMSException: Invalid password key to unlock the passwords in the configuration file]
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getNamingException(InitialContextFactoryImpl.java:31)
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:162)
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
         at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
         at javax.naming.InitialContext.init(InitialContext.java:223)
         at javax.naming.InitialContext.<init>(InitialContext.java:197)
         at com.netflix.messaging.ESBFactory.<init>(ESBFactory.java:103)
         at com.netflix.messaging.ESBFactory.getFactory(ESBFactory.java:45)
         at com.netflix.messaging.NFMessagingManager.getProducerHandle(NFMessagingManager.java:218)
         at com.netflix.messaging.NFMessagingManager.initProducers(NFMessagingManager.java:730)
         at com.netflix.messaging.NFMessagingManager.init(NFMessagingManager.java:863)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1461)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1628)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.startMessagingManager(MessageDestinationDispatcher.java:164)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.<init>(MessageDestinationDispatcher.java:25)
         at com.netflix.logging.NFMessageAppender.append(NFMessageAppender.java:72)
         at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
         at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
         at org.apache.log4j.Category.callAppenders(Category.java:206)
         at org.apache.log4j.Category.forcedLog(Category.java:391)
         at org.apache.log4j.Category.log(Category.java:838)
         at com.netflix.logging.log4jAdapter.Log4jLoggingAdapter.log(Log4jLoggingAdapter.java:64)
         at com.netflix.logging.NFLogger.log(NFLogger.java:125)
         at com.netflix.logging.LogManager.info(LogManager.java:152)
         at com.netflix.logging.aggregator.Bucketer.init(Bucketer.java:92)
         at com.netflix.logging.aggregator.Bucketer.<init>(Bucketer.java:80)
         at com.netflix.logging.aggregator.TracerAggregator.<init>(TracerAggregator.java:29)
         at com.netflix.logging.aggregator.TracerAggregator.<clinit>(TracerAggregator.java:20)
         at com.netflix.logging.NFLogger.start(NFLogger.java:105)
         at com.netflix.logging.LogManager.registerLogger(LogManager.java:67)
         at com.netflix.logging.test.LoggingTest.sendDefault(LoggingTest.java:32)
         at com.netflix.logging.test.LoggingTest.main(LoggingTest.java:19)
    Caused by: weblogic.jms.common.JMSException: Invalid password key to unlock the passwords in the configuration file
         at weblogic.jms.safclient.admin.ConfigurationUtils.doRemoteContexts(ConfigurationUtils.java:475)
         at weblogic.jms.safclient.agent.AgentManager.<init>(AgentManager.java:54)
         at weblogic.jms.safclient.ClientSAFDelegate.open(ClientSAFDelegate.java:65)
         at weblogic.jms.safclient.ClientSAFImpl.open(ClientSAFImpl.java:62)
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:160)
         ... 30 more
    Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
         at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
         at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
         at com.sun.crypto.provider.SunJCE_af.b(DashoA12275)
         at com.sun.crypto.provider.PBEWithMD5AndDESCipher.engineDoFinal(DashoA12275)
         at javax.crypto.Cipher.doFinal(DashoA12275)
         at weblogic.jms.common.SecHelper.decryptString(SecHelper.java:140)
         at weblogic.jms.safclient.admin.ConfigurationUtils.doRemoteContexts(ConfigurationUtils.java:473)
         ... 34 more
    java.lang.IllegalStateException: Cannot create context: Invalid password key to unlock the passwords in the configuration file
         at com.netflix.messaging.ESBFactory.<init>(ESBFactory.java:106)
         at com.netflix.messaging.ESBFactory.getFactory(ESBFactory.java:45)
         at com.netflix.messaging.NFMessagingManager.getProducerHandle(NFMessagingManager.java:218)
         at com.netflix.messaging.NFMessagingManager.initProducers(NFMessagingManager.java:730)
         at com.netflix.messaging.NFMessagingManager.init(NFMessagingManager.java:863)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1461)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1628)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.startMessagingManager(MessageDestinationDispatcher.java:164)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.<init>(MessageDestinationDispatcher.java:25)
         at com.netflix.logging.NFMessageAppender.append(NFMessageAppender.java:72)
         at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
         at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
         at org.apache.log4j.Category.callAppenders(Category.java:206)
         at org.apache.log4j.Category.forcedLog(Category.java:391)
         at org.apache.log4j.Category.log(Category.java:838)
         at com.netflix.logging.log4jAdapter.Log4jLoggingAdapter.log(Log4jLoggingAdapter.java:64)
         at com.netflix.logging.NFLogger.log(NFLogger.java:125)
         at com.netflix.logging.LogManager.info(LogManager.java:152)
         at com.netflix.logging.aggregator.Bucketer.init(Bucketer.java:92)
         at com.netflix.logging.aggregator.Bucketer.<init>(Bucketer.java:80)
         at com.netflix.logging.aggregator.TracerAggregator.<init>(TracerAggregator.java:29)
         at com.netflix.logging.aggregator.TracerAggregator.<clinit>(TracerAggregator.java:20)
         at com.netflix.logging.NFLogger.start(NFLogger.java:105)
         at com.netflix.logging.LogManager.registerLogger(LogManager.java:67)
         at com.netflix.logging.test.LoggingTest.sendDefault(LoggingTest.java:32)

  • Javax.crypto classes not found using JDK1.4

    We're trying to upgrade to using JDK 1.4, in which the Java Cryptography Extensions are incorporated into the JDK. However, iPlanet does not seem to be able to find the classes that make up the extension.
    If I write a simple Java app that creates a java.crypto.SecretKey, and run it from the command line on our web server machine using our Java 1.4 JDK, it runs fine.
    If I adapt the same program into a simple servlet and run it from within iPlanet, it fails with a ClassNotFound error trying to find javax/crypto/NoSuchPaddingException.
    I've done a lot of variations trying to hone in on the problem, but I'm running out of options. Does anyone have any information or experience with this particular problem?
    We're running iPlanet 6.0 SP5 and the JDK is build 1.4.1-b21.

    David,
    I'm also facing the same problem, none of the javax.crypto classes are found.When I'm running the Encryption code it's working standlone and in Tomcat 4.0 but in IPlanet it's giving me ClassNotFound.
    I have added jce.jar in the classpath as mentioned and it's getting picked.
    But you have mentioned some start-jvm files, I'm not able to find these files.
    Can u please summarize what all settings you did?.
    As it's urgent if possible mail me at,
    [email protected] (OR)
    [email protected]
    Sachin

  • NoClassDefFoundError javax.crypto.spec.secretkeyspec from console

    Hello, I have done a program in eclipse, using the JCE to encrypt and decrypt some messages using AES. In the eclipse graphical interface it works perfect, but if i run it from console, i mean like this
    java -jar org.eclipse.osgi_3.6.0.v20100517.jar -console -configuration config_path -clean -dev file:dev.properties_path
    It works but throw the exception
    NoClassDefFoundError javax.crypto.spec.secretkeyspec
    I think there must be something wrong with the java path because JCE is already inside the jre environment. I need to know how can i indicate in the command line, the right path to the JCE
    I am working on windows
    Thank you!

    yes, i mean
    NoClassDefFoundError javax.crypto.spec.SecretKeySpec
    but i wrote it fast and i didn't realize....
    My output for java -version is
    java version "1.6.0_21"
    Java (TM) SE Runtime Environment (build 1.6.0_21-b06)
    Java HotSpot(TM) Client VM (build 17.0-b16, mixed mode, sharing)
    So i think that outside eclipse i am using the good one, then i don't know why it doesn't work. Actually, i forgot to say that in the log file, i get this exception message:
    !ENTRY org.eclipse.osgi 4 0 2010-10-15 11:35:12.273
    !MESSAGE Application error
    !STACK 1
    java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini).
         at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:74)
         at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
         at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
         at org.eclipse.core.runtime.adaptor.EclipseStarter.main(EclipseStarter.java:150)
    So maybe this is the real problem. I am sorry but i am not really used to launch java applications from console (i always do it with eclipse) so, i don't really know if i need some more parameters or what happen.
    My config.ini file is the same that eclipse uses when it launches the application, and the dev.properties file is also the same.

  • How javax.crypto can do "ALG_DES_CBC_ISO9797_M2" padding?

    First Question :
    Do "javacardx.crypto, javacard.security" can use outside applet in card?
    I try to use this on client-side ?(in RMI, we say client-side is reader , card is host-side) but it's not work , throw exception.
    I write javacard RMI style. My problem is...
    Source code below is work when it write in applet (card - side)
    but in client-side (reader -side) I copy it to client - side code and test to run, if fail --> throw exception 0x3 - javacard.security.CryptoException.NO_SUCH_ALGORITHM
    It seem to be "javacardx.crypto" and "javacard.security" is make for use in applet in card only. Did I misunderstand?
    if it make for use in applet only, how is possible to do like this " card use privatekey to sign message and send to reader , reader use card's publickey to verify that card sign this signature or not."
    or
    "card use reader's publickey to encrypt message and send to reader, then reader use privatekey to decrypt message (reader authencate itself) "
    because I can't do any of cipher , keybuilder in RMI-client side(reader)
    Cipher.getInstance(Cipher.ALG_RSA_PKCS1,false);
    it will throw nullPointerException
    and if (change false to true)
    Cipher.getInstance(Cipher.ALG_RSA_PKCS1,true);
    throw exception 0x3 - javacard.security.CryptoException.NO_SUCH_ALGORITHM
    after that I swap this line with
    pri_key = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE,KeyBuilder.LENGTH_RSA_512, false);
    since it will do this first (i swap the line already) it also throw exception 0x3 - javacard.security.CryptoException.NO_SUCH_ALGORITHM
    also be the same result with swap
    kp = new KeyPair(KeyPair.ALG_RSA,(short)KeyBuilder.LENGTH_RSA_512 );
    to a first line
    it throw exception 0x3 - javacard.security.CryptoException.NO_SUCH_ALGORITHM
    Please help me
    RSAPrivateKey pri_key;
    RSAPublicKey pub_key;
    KeyPair kp;
    Cipher RSAcipher;
    RSAcipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1,false);
    pri_key = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE,KeyBuilder.LENGTH_RSA_512, false);
    pub_key =(RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC,KeyBuilder.LENGTH_RSA_512, false);
    kp = new KeyPair(KeyPair.ALG_RSA,(short)KeyBuilder.LENGTH_RSA_512 );
    kp.genKeyPair();
    pri_key = (RSAPrivateKey) kp.getPrivate();
    pub_key = (RSAPublicKey) kp.getPublic();
    //ENCRYPT
    RSAcipher.init(pub_key, Cipher.MODE_ENCRYPT);
    t_cipherLengthRSA = RSAcipher.doFinal(plaintxt,(short)0, (short)plaintxt.length, t_cipherText, (short)0);
    //DECRYPT
    RSAcipher.init(pri_key, Cipher.MODE_DECRYPT);
    RSAcipher.doFinal(ciphertxt,(short)0,(short) t_cipherLengthRSA, temp1, (short)0);
    I just think to new solution , client-side(reader) is use normal crypto class from javax.crypto , java.security
    if I use javax.crypto
    Question : Can it do "ALG_DES_CBC_ISO9797_M2" padding?
    I want to use card to encrypt/sign and send to reader. Then reader decrypt/verify it.

    See my answer to your other post "RMI client-side -> how to encrypt,decrypt in client-side"
    Jan

  • Javax.crypto.BadPaddingException

    Hi there,
    java gurus could you please provide me at least one well format answer why does it happen. I have checked out the forum and I would say that there are many work around answers, but nothing usefull. So my problem is:
    I'm trying to execute the same application twice
    first time the sequence of operations is following encrypt the string and then decrypt result of previous operation and execution is OK!
    [af@juja db2file]$ java -classpath db2file.jar Crypter e a1a2a3a4
    97 49 97 50 97 51 97 52
    -39 -23 5 45 88 70 -57 -38 -124 -38 -111 -102 -61 106 0 -104
    -39 -23 5 45 88 70 -57 -38 -124 -38 -111 -102 -61 106 0 -104
    97 49 97 50 97 51 97 52
    Result e: 2ekFLVhGx9qE2pGaw2oAmA==; 24
    Result d: a1a2a3a4; 8
    second time the sequence of operations is following decrypt result of previous execution and execution isn't OK! at all
    [af@juja db2file]$ java -classpath db2file.jar Crypter d 2ekFLVhGx9qE2pGaw2oAmA==
    -39 -23 5 45 88 70 -57 -38 -124 -38 -111 -102 -61 106 0 -104
    javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA6275)
    at com.net2s.mobistar.util.Crypter.decrypt(Crypter.java:66)
    at com.net2s.mobistar.util.Crypter.main(Crypter.java:85)
    Result e: 2ekFLVhGx9qE2pGaw2oAmA==; 24
    Result d: ; 0
    As you can see the number of the bytes and its value are the same.
    That is the code:
    import java.security.Key;
    import java.security.Provider;
    import java.security.Security;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import javax.crypto.*;
    public class Crypter {
    private static Crypter crypter;
    private Cipher cipher;
    private Key key;
    private Crypter() {
    try {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    key = KeyGenerator.getInstance("DES","SunJCE").generateKey();
    cipher = Cipher.getInstance("DES");
    } catch (Exception ex) {
    ex.printStackTrace();
    public static Crypter getDefault() {
    if(crypter == null) {
    crypter = new Crypter();
    return crypter;
    public String encrypt(String str) {
    String result = "";
    try {
    cipher.init(Cipher.ENCRYPT_MODE,key);
    byte[] utf8 = str.getBytes("UTF8");
    printBytes(utf8);
    byte[] enc = cipher.doFinal(utf8);
    printBytes(enc);
    result = new sun.misc.BASE64Encoder().encode(enc);
    } catch (Exception ex) {
    ex.printStackTrace();
    return result;
    public String decrypt(String str) {
    String result = "";
    try {
    cipher.init(Cipher.DECRYPT_MODE,key);
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    printBytes(dec);
    byte[] utf8 = cipher.doFinal(dec);
    printBytes(utf8);
    result = new String(utf8,"UTF8");
    } catch (Exception ex) {
    ex.printStackTrace();
    return result;
    public static void main(String[] args) {
    String e = "";
    String d = "";
    if(args[0].equals("e")) {
    e = Crypter.getDefault().encrypt(args[1]);
    d = Crypter.getDefault().decrypt(e);
    System.out.println("Result e: " + e + "; " + e.length());
    System.out.println("Result d: " + d + "; " + d.length());
    } else {
    e = args[1];
    d = Crypter.getDefault().decrypt(e);
    System.out.println("Result e: " + e + "; " + e.length());
    System.out.println("Result d: " + d + "; " + d.length());
    private void printBytes(byte[] toPrint) {
    for(int i = 0;i < toPrint.length;i++) {
    System.out.print(toPrint);
    System.out.print(" ");
    System.out.println("");
    Enjoy!

    I am getting the same BadPaddingException when using (what I thought was the same key on different versions of the JDK. The original code is not mine, I would not have tried to get fancy with seed generation, but opted for secure key storage. Anyway, this code works on one verion of the JDK, but not another. I now assume, after reading these posts, that the SecureRandom has changed so that a different key is being generated. Is this correct, or am I doing something else wrong?
    -C
    public class SimpleDESEncryption {
         final static String PNRG_ALGORITHM = "SHA1PRNG";
         final static String KEYGEN_ALGORITHM = "DESede";
         final static String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
         final static String STRING_FORMAT = "UTF-16";
         final static String PROVIDER = "com.sun.crypto.provider.SunJCE";
         static {
              try {
                   Security.addProvider((Provider) Class.forName(PROVIDER).newInstance());
              catch(Exception e) {
          * C'tor
         private SimpleDESEncryption() {
          * Static, reentrant method to encrypt a given string using the specified key.
          * @param key The Stringified long value used for PRNG seeds.
          * @param raw The String to encrypt.
          * @return Base64 encoded version of encrypted text.
          * @throws PaygovSystemException if a system exception occurs
          * @throws PaygovException if a known expected error occurs
         public static String encrypt(String key, String raw) throws PaygovSystemException, PaygovException {
              Cipher cipher = null;
              String  encryptedString = null;
              String encodedString =  null;
              if(raw == null || raw.length() == 0) {
                   // Nothing to encrypt
                   return raw;
              try {
                   // Instantiate and initialize the cipher
                   long longKey = Long.parseLong(key);
                   SecretKey secretKey = deriveSecretKey(longKey);
                   cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                   cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                   // Encrypt and Base64 encode the data
                   BASE64Encoder  encoder = new BASE64Encoder();
                   byte[] clearBfr = raw.getBytes(STRING_FORMAT);
                   byte[] cipherBfr = cipher.doFinal(clearBfr);
                   encodedString = encoder.encodeBuffer(cipherBfr);
                   return(encodedString);
              catch(java.security.InvalidKeyException err) {
                   throw new PaygovSystemException(err);
              catch(javax.crypto.NoSuchPaddingException err) {
                   throw new PaygovSystemException(err);
              catch(java.security.NoSuchAlgorithmException err) {
                   throw new PaygovSystemException(err);
              catch(java.io.UnsupportedEncodingException err) {
                   throw new PaygovSystemException(err);
              catch(javax.crypto.IllegalBlockSizeException err) {
                   throw new PaygovSystemException(err);
              catch(javax.crypto.BadPaddingException err) {
                   throw new PaygovSystemException(err);
          * Static, reentrant method to decrypt a given string using the specified key
          * @param key The Stringified long value used for <code>PRNG</code> seeds.
          * @param encryptedDataString The Base64 encoded <code>String</code> to decrypt.
          * @return Base64 encoded version of encrypted text.
          * @throws PaygovSystemException if a system exception occurs
          * @throws PaygovException if a known expected error occurs
         public static String decrypt(String  key, String encryptedDataString) throws PaygovSystemException, PaygovException
              Cipher cipher = null;
              String decryptedString = null;
              String decodedString = null;
              if(encryptedDataString == null || encryptedDataString.length() == 0) {
                   // Nothing to decrypt
                   return encryptedDataString;
              // Instantiate and initialize the cipher
              try {
                   // Instantiate and initialize the cipher
                   long longKey = Long.parseLong(key);
                   SecretKey secretKey = deriveSecretKey(longKey);
                   cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                   cipher.init(Cipher.DECRYPT_MODE, secretKey);
                   BASE64Decoder decoder = new BASE64Decoder();
                   byte[] decodedBfr = decoder.decodeBuffer(encryptedDataString);
                   byte[] decryptedBfr = cipher.doFinal(decodedBfr);
                   decryptedString = new String(decryptedBfr, STRING_FORMAT);
                   return(decryptedString);
              catch(javax.crypto.BadPaddingException err) {
                   err.printStackTrace();
                   throw new PaygovException(err);
              catch(java.security.InvalidKeyException err) {
                   throw new PaygovException(err);
              catch(javax.crypto.IllegalBlockSizeException err) {
                   throw new PaygovException(err);
              catch(javax.crypto.NoSuchPaddingException err) {
                   throw new PaygovSystemException(err);
              catch(java.security.NoSuchAlgorithmException err) {
                   throw new PaygovSystemException(err);
              catch(java.io.IOException err) {
                   throw new PaygovSystemException(err);
          * Get the private key
         private static SecretKey deriveSecretKey(long key) throws PaygovSystemException {
              SecureRandom prng = null;
              KeyGenerator keyGen = null;
              SecretKey secretKey = null;
              try {
                   prng = SecureRandom.getInstance(PNRG_ALGORITHM);
                   prng.setSeed(twiddle(key));
                   // get the key generator
                   keyGen = KeyGenerator.getInstance(KEYGEN_ALGORITHM, "SunJCE");
                   // initialize it with _our_ carefuly seeded PRNG
                   keyGen.init(prng);
                   //  Get the key
                   secretKey = keyGen.generateKey();
              catch(java.security.NoSuchAlgorithmException err) {
                   throw new PaygovSystemException(err);
              catch(java.security.NoSuchProviderException err) {
                   throw new PaygovSystemException(err);
              return(secretKey);
         private static long twiddle(long key) {
              long twiddleBytes = (key % 8) << 3;
              return(key ^ twiddleBytes);
          * For testing different versions of the JDK. Tests encryption and decryption within
          * the VM and also saves encrypted text to a file and tries to decrypt it on the next
          * pass so that it can be run first with one version and then again with a different
          * version to ensure that the algorithm, padding, and decoding work consistently.
         public static void main(String[] args) {
              //Define our static key for testing
              String key = "1524567842321251673";
              String clearText = "Mary had a little lamb";
              String readText = null;
              String encryptedText = null;
              File outputFile = new File("encryptiontest.txt");
              try {
                   //Encrypt cleartext
                   encryptedText = SimpleDESEncryption.encrypt(key, clearText);
                   //Test in memory decryption
                   if(! SimpleDESEncryption.decrypt(key, encryptedText).equals(clearText)) {
                        System.out.println("In memory decryption failed. Exitting.");
                        return;
                   System.out.println("In memory decryption passed.");
                   //Check if saved output file exists
                   if(outputFile.exists()) {
                        System.out.println("Checking file from last run.");
                        FileInputStream fis = null;
                        try {
                             fis = new FileInputStream(outputFile);
                             LineNumberReader lineNumberReader = new LineNumberReader(new InputStreamReader(fis));
                             readText = lineNumberReader.readLine();
                             fis.close();
                        catch(IOException ioe) {
                             System.out.println("Error reading test file. Exitting.");
                             return;
                        //Test cross invocation decryption
                        if(! SimpleDESEncryption.decrypt(key, readText).equals(clearText)) {
                             System.out.println("Decrypted file test failed. Exitting.");
                             return;
                        System.out.println("File decryption passed.");
              catch(Exception pgse) {
                   System.out.println("Exception occured: " + pgse);
                   pgse.printStackTrace();
                   return;
              //Save the encrypted text from this run.
              PrintStream printStream = null;
              try {
                   System.out.println("Saving file for next run.");
                   printStream = new PrintStream(new FileOutputStream(outputFile));
                   printStream.println(encryptedText);
                   printStream.close();
              catch(IOException ioe) {
                   System.out.println("Error writing test file. Exitting.");
                   return;
              System.out.println("Test complete.");

  • Javax.crypto.IllegalBlockSizeException,javax.crypto.BadPaddingException

    hi friends
    iam writing and reading an encryted text to a file . this code executes well on windows xp o.s but does not executes on Macintosh ,solaris and linux systems.
    when executed it throws javax.crypto.IllegalBlockSizeException and javax.crypto.BadPaddingException .
    pls i am damp urgent need of it so kindly resolve my problem
    Below is the code.
    Thanks in advance.
    --------------------------------------------------code----------------------------------------
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.Cipher;
    import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
    public class EncryptionExample
         static SecretKey key = null;
         static String text="A=1,B=2,C=3";
         static String xform = "Blowfish/CFB/PKCS5Padding";
         private static byte[] iv =
    { 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c, 0x0d };
         public EncryptionExample() throws Exception
              key=EncryptionExample.getGeneratedKey();
         public static void writeToFile() throws Exception
              FileWriter file = null;
              BufferedWriter fileOutput = null;
              byte[] dataBytes = null;
              byte[] encBytes = null;
              try {
                        file = new FileWriter("C:\\Test.txt");
                        fileOutput= new BufferedWriter(file);
                        dataBytes = text.getBytes("UTF8");
                   encBytes = encrypt(dataBytes, key, xform);
                   String encStr = Base64.encode(encBytes);
                   fileOutput.write(encStr);
                        fileOutput.close();
                   } catch (Exception e) {
                   e.printStackTrace();
         //     reading encryted text from file
              public static void readFromFile() throws Exception
                   FileReader filerdr = null;
                   BufferedReader fileInput = null;
                   byte[] decBytes = null;
                   String decrystr = null;
                   String enText = null;
                   try {
                                  filerdr = new FileReader("C:\\Test.txt");
                                  fileInput = new BufferedReader(filerdr);
                                  while ((enText = fileInput.readLine())!=null)
                                       byte[] decrypted = Base64.decode(enText);
                                       decBytes = decrypt(decrypted, key, xform);
                                       decrystr=new String(decBytes,"UTF8");
                                       System.out.println("decrypted string token , "+decrystr);
                                  fileInput.close();
                             }catch (Exception e) {
                                  e.printStackTrace();
              private static byte[] encrypt(byte[] inpBytes,SecretKey key, String xform) throws Exception {
                   Cipher cipher = Cipher.getInstance(xform);
                   IvParameterSpec dps = new IvParameterSpec(iv);
                   cipher.init(Cipher.ENCRYPT_MODE, key,dps);
                   return cipher.doFinal(inpBytes);
         private static byte[] decrypt(byte[] inpBytes,SecretKey key, String xform) throws Exception
              Cipher cipher = Cipher.getInstance(xform);
              IvParameterSpec dps = new IvParameterSpec(iv);
              cipher.init(Cipher.DECRYPT_MODE, key,dps);
              return cipher.doFinal(inpBytes);
         private static SecretKey getGeneratedKey() throws Exception
    //          Generate a secret key
         KeyGenerator kg = KeyGenerator.getInstance("Blowfish");
         kg.init(128); // 56 is the keysize. Fixed for DES
         SecretKey key = kg.generateKey();
         return key ;
         public static void main(String[] unused) throws Exception {
              new EncryptionExample();
              EncryptionExample.writeToFile();
              EncryptionExample.readFromFile();
    }

    You are very lucky to get this working at all, even on Windows! You encrypt the whole of your string at one go and write it to a file using
    fileOutput= new BufferedWriter(file);
    dataBytes = text.getBytes("UTF8");
    encBytes = encrypt(dataBytes, key, xform);
    String encStr = Base64.encode(encBytes);
    fileOutput.write(encStr);
    fileOutput.close();but you then try to decrypt it a line at a time using
    while ((enText = fileInput.readLine())!=null)
    byte[] decrypted = Base64.decode(enText);
    decBytes = decrypt(decrypted, key, xform);
    decrystr=new String(decBytes,"UTF8");
    System.out.println("decrypted string token , "+decrystr);
    fileInput.close();This just does not make sense. If you encrypt all at one time you must decrypt all at one time.
    Your code happens to work because the Base64 encoding puts everything on one line. The fact that this seems to work does not make it correct.
    P.S. Your code works on my Linux FC5 so I have no idea why you get the exceptions!

  • Javax.crypto.IllegalBlockSizeException help?

    I am making a plain text encrypt/decrypt program for personal use.
    It will compile just fine, but if I try to run the decryption part, it freaks out on me.
    It keeps on saying:
    javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
    This is my code. I cannot figure out what is wrong...
    import java.io.*;
    import java.util.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    import static methods.methods.*;
    public class Base
        public static void main()
            Scanner kbReader = new Scanner(System.in);
            clear("Method > ");
            String s = kbReader.next();
            if(s.equals("output"))
                try{output();}
                catch(Exception e){e.printStackTrace();}
            if(s.equals("input"))
                try{input();}
                catch(Exception e){e.printStackTrace();}
            if(s.equals("genKey"))
                genKey();
            if(s.equals("x"))
                clear("Well it stopped.");
            else
                main();
        public static void output()
            throws IOException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            IllegalBlockSizeException,
            BadPaddingException,
            InvalidAlgorithmParameterException
            Scanner kbReader = new Scanner(System.in);
            Scanner kbr = new Scanner(System.in);
            clear("What is the name of the file?\nName > ");
            fileName = kbReader.next();
            String s2 = "/Users/ewsmith/base/" + fileName;
            FileWriter fw = new FileWriter(s2, true);
            PrintWriter output = new PrintWriter(fw, true);
            clear("Key > ");
            byte key[] = new byte[16];
            for(int j=0; j<16; j++)
                key[j] = kbReader.nextByte();
            clear("IV > ");
            byte ivBytes[] = new byte[16];
            for(int j=0; j<16; j++)
                ivBytes[j] = kbReader.nextByte();
            IvParameterSpec iv = new IvParameterSpec(ivBytes);
            String s = new String("");
            String ss = new String("");
            clear("Enter what you want output to a file.\nType 'x' to finish writing.\n\n");
            while(true)
                s = kbReader.nextLine();
                if(s.equalsIgnoreCase("x"))
                    break;
                ss = ss + s + "\n";
            byte data[] = ss.getBytes("UTF-8");
            Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            SecretKeySpec k = new SecretKeySpec(key, "AES");
            c.init(Cipher.ENCRYPT_MODE, k, iv);
            c.doFinal(data);
            for(int j=0; j<data.length; j++)
                output.print(data[j] + " ");
            clear("This is your key.\n\n");
            for(int j=0; j<key.length; j++)
            System.out.print(key[j] + "  ");
            println("\n\nType in 'x' and press enter to continue.");
            boolean alive = true;
            while(alive)
                String s3 = kbr.nextLine();
                if(s3.equalsIgnoreCase("x"))
                    alive = false;
            byte[] IV = c.getIV();
            clear("This is your IV:\n\n");
            for(int j=0; j<IV.length; j++)
                print(IV[j] + "  ");
            println("\n\nType x to continue.\n");
            String ew = "";
            while(true)
                ew = kbReader.nextLine();
                if(ew.equalsIgnoreCase("x"))
                    break;
            output.close();
            fw.close();
        public static void input()
            throws IOException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            IllegalBlockSizeException,
            BadPaddingException,
            InvalidAlgorithmParameterException
            Scanner kbReader = new Scanner(System.in);
            Scanner kbr = new Scanner(System.in);
            Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            clear("What is the name of the file?\nName > ");
            fileName = kbr.next();
            String s2 = "/Users/ewsmith/base/" + fileName;
            Scanner sf = new Scanner(new File(s2));
            int num = 1;
            clear("Key > ");
            byte key[] = new byte[16];
            for(int j=0; j<16; j++)
                key[j] = kbReader.nextByte();
            clear("IV > ");
            byte ivBytes[] = new byte[16];
            for(int j=0; j<16; j++)
                ivBytes[j] = kbReader.nextByte();
            IvParameterSpec iv = new IvParameterSpec(ivBytes);
            SecretKeySpec k = new SecretKeySpec(key, "AES");
            c.init(Cipher.DECRYPT_MODE, k, iv);
            clear("This text was stored inside the file.\n\n\n");
            int j = 0;
            ArrayList<Byte> ip = new ArrayList<Byte>();
            while(sf.hasNext())
                ip.add(sf.nextByte());
            byte input[] = new byte[ip.size()];
            for(j=0; j<ip.size(); j++)
                input[j] = ip.get(j);
            String recovered = new String(c.doFinal(input));
            println(recovered);
            sf.close();
            ip.clear();
            input = null;
            println("\n\nType in 'x' and press enter to continue.");
            boolean alive = true;
            while(alive)
                String s = kbReader.nextLine();
                if(s.equalsIgnoreCase("x"))
                    alive = false;
        public static void genKey()
            Scanner kbReader = new Scanner(System.in);
            clear();
            Random ranGen = new SecureRandom();
            byte[] aesKey = new byte[16];
            ranGen.nextBytes(aesKey);
            for(int j=0; j<aesKey.length; j++)
            System.out.print(aesKey[j] + "  ");
            println("\n\nType in 'x' and press enter to continue.");
            boolean alive = true;
            while(alive)
                String s = kbReader.nextLine();
                if(s.equalsIgnoreCase("x"))
                    alive = false;
        public static String fileName = "";
    }Thank you in advance for answering.
    EDIT:
    It now says:
    +     at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)+
    +     at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)+
    +     at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA12275)+
    +     at javax.crypto.Cipher.doFinal(DashoA12275)+
    +     at Base.input(Base.java:184)+
    +     at Base.main(Base.java:23)+
    +     at __SHELL3.run(__SHELL3.java:6)+
    +     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)+
    +     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)+
    +     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)+
    +     at java.lang.reflect.Method.invoke(Method.java:585)+
    +     at bluej.runtime.ExecServer$3.run(ExecServer.java:819)+
    Could this be an IV error?
    Can negative IV's be used?
    Edited by: eric_smith on Jan 6, 2010 9:25 PM
    Edited by: eric_smith on Jan 7, 2010 9:51 AM

    I turned this:
    String recovered = new String(c.doFinal(input));into this:
    String recovered = new String(input);and used 0's for the key and iv and the text was 'decrypted'.
    Something tells me the problem is in the output and input cipher.init()
    Can someone enlighten me as to what I am doing wrong?
    EDIT: btw, the code came from the input method.
    Edited by: eric_smith on Jan 7, 2010 9:28 PM

Maybe you are looking for

  • Trial Balance Report not showing in months

    Hi All. A client is trying to run a trial balance, wanting it to display in months. He chooses monthly report, but it still gives just one total amount. The company he is running is a seconday company. He ran the report in the main company and it wor

  • How long should upgrade to Yosemite take?

    I have downloaded Yosemite from the AppStore and on my initial attempt to install got to the point of having a grey screen with apple in the middle and a progress bar which stopped about 1/4th the way to completion.  I let it run overnight after read

  • I can't use my USB ports or connect to the Internet after downgradin​g from Windows 8 to 7

    I downgraded my HP Pavilion p7-1534 desktop computer from Windows 8 to Windows 7 today with a Windows 7 Home Premium disk I purchased. I checked online first to see everything I'd need to do, including backing up all my personal files and information

  • Adobe acrobat 9 Pro Convert to PDF Access Denied for users

    I recently installed IE 9 on my computer (windows 7 ultimate 64 bit). From this moment on I cannot convert web page to pdf. I am getting " permission denied", code 0. Can anyone help me?

  • Oracle.Dataaccess.dll deploy windows application

    I have a windows application that I developed in VS 2005 on XP. It access the DB via the oracle data provider. I just switched to vista and was adding some new items ot the application and then tried to redeploy it. I had to add a new installer to th