Javax.crypto.IllegalBlockSizeException: Input data length not a multiple

Hi All ,
M worknig with NWCE 7.1.1. I have written code for decryption for decryption.  Earlier my web dynpro application was on CE7.1. We migrated it to CE 7.1.1 just week ago after migrating to CE 7.1.1 , on execution of decryption code m gtting as
javax.crypto.IllegalBlockSizeException: Input data length not a multiple of blocksize
i have written following code for decryption.
public String decrypt( String encryptedString, String encryptionKey )
     String UNICODE_FORMAT = "UTF8";
     try
          if ( encryptedString == null || encryptedString.trim().length() <= 0 )
               throw new IllegalArgumentException( "encrypted string was null or empty" );
            byte[] keyAsBytes = encryptionKey.getBytes(UNICODE_FORMAT);
            keySpec = new DESKeySpec(keyAsBytes);
            keyFactory = SecretKeyFactory.getInstance( "DES" );
            cipher = Cipher.getInstance( "DES" );
          SecretKey key = keyFactory.generateSecret( keySpec );
          cipher.init( Cipher.DECRYPT_MODE, key );
          BASE64Decoder base64decoder = new BASE64Decoder();
          byte[] cleartext = base64decoder.decodeBuffer( encryptedString );
          byte[] ciphertext = cipher.doFinal( cleartext );
          return new String( ciphertext );
     }catch (Exception e){
          IWDMessageManager messageManager = wdComponentAPI.getMessageManager();
          messageManager.reportException("Error while Decryption");
          e.printStackTrace();
          return "";
This code was working fine in CE 7.1 . After migrating to CE 7.1.1 it started giving this error.

Thank you for your answer
how the code is usedI have hardcoded key, example
byte[] key = "123456789abcdefg".getBytes();and String for crypt (Example, String in = "green";)
Then I encrypt string in with code above (in qwestion body) and get exception IllegalBlockSizeException: Input data length not a multiple of blocksize
String encrypt(String in) throws Exception{
  String out="";
  byte[] key = "123456789abcdefg".getBytes();
  Cipher ecipher = Cipher.getInstance("AES");
  ecipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
  byte[] utf8 = in.getBytes("UTF8");
  byte[] enc = ecipher.doFinal(utf8);
  out = (new sun.misc.BASE64Encoder().encode(enc)).toString();
  return out;
}Clients use JRE1.4 or high. I have JRE1.4 and all work correctly. Also, many clients have 1.4, but only part of they get exception. Code is in the server (this is part of servlet)
This function run in one thread and doesn't use shared resources

Similar Messages

  • 'Input data length not a multiple of blocksize' error in CUP

    Hello All
    I receive the error below when trying to configure CUP. I got this error whilst trying to define the password for the RFC user created in the Connector screen in CUP. CUP doesn't accept the SAP password maintained in SU01. CUP only allows a 4 character password but SU01 is configured to only accept 8 characters. Full error message below.
    'com.virsa.ae.commons.utils.StringEncrypter$EncryptionException: Input data length not a multiple of blocksize.'
    Can anyone shed any light on this?

    Hi All,
    This issue is in Version 5.3 SP 7.1 of CUP. It occurs when we are trying to change the password for the CUP connector.
    Please note that testing the connectors within the Content Administrator --> Maintain JCO Connections screens works fine and the risk analysis from RAR also works without issue. However, whenever we attempt to enter the password for CUP connecotr setup, it returns an error saying "Action Failed" with the 'Input data length not a multiple of blocksize' error showing in the trace logs.
    We seem to be able to store a password of 4 characters e.g. 1234 but this then naturally fails the connection test.
    Can anyone suggest a parameter setting to check or a resolution for this particular issue?
    Thanks,
    Simon

  • Javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8

    Hello!
    I have encrypted/decrypted one String with DES. I tried to do so on one computer and it seams to work fine. But what I realy want is to encrypt 3 String: username, id, and password, and send them to server. On server I want to decrypt them, and use them to check in database if the person exist. I save this 3 String in an ArrayList, and use ObjectInput/OutputStream to send and receive. Here is some of my code(I hope it is enough for you to help me solve this problem,othervice I will send more).
    I get this error: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
    public class CryptDecryptString {
    public byte[] cryptString( String password) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
    byte [] plainTextPassword = password.getBytes("UTF-8");
    System.out.println(new String(plainTextPassword,"UTF-8"));
    //SecureRandom sr = new SecureRandom();
    String nyckeln = "HELLOHEJ";
    byte rawKeyData[] = nyckeln.getBytes();
    DESKeySpec dks = new DESKeySpec(rawKeyData);
    SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks);
    Cipher cipher=Cipher.getInstance("DES");
    cipher.init(Cipher.ENCRYPT_MODE, key);//, sr);
         System.out.println("\nStart encryption:");
    cipher.init(Cipher.ENCRYPT_MODE,key);
         byte[] cipherTextPassword=cipher.doFinal(plainTextPassword);
         System.out.println("Finish encryption:");
         System.out.println(new String(cipherTextPassword));
    return cipherTextPassword;
    }// end cryptString
    public byte[]decryptString(byte[] cipherTextPassword) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    String nyckeln = "HELLOHEJ";
    byte rawKeyData[] = nyckeln.getBytes();
    DESKeySpec dks = new DESKeySpec(rawKeyData);
    SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks);
    Cipher cipher=Cipher.getInstance("DES");
         System.out.println("\nStart decryption:");
    cipher.init(Cipher.DECRYPT_MODE,key);
         byte[] plainTextPassword=cipher.doFinal(cipherTextPassword);
         System.out.println(" Finnish decryption:");
         System.out.println(new String(plainTextPassword,"UTF-8"));
    return plainTextPassword;
    }// end decryptString
    {public boolean TryLogin(String uname, String insID, String pass) throws Exception{
            connect();
            //sendOutStream = new DataOutputStream(socket.getOutputStream());
            sendOutStream = new ObjectOutputStream(socket.getOutputStream());
            InputStream inpuStream;
            inpuStream = socket.getInputStream();
            BufferedReader in= new BufferedReader(new InputStreamReader(inpuStreamtext s));
            CryptDecryptString cryptString = new CryptDecryptString();
          String krypteradeUname = cryptString.cryptString(uname);
           String krypteradeInsID = cryptString.cryptString(insID);
            String krypteradePass = cryptString.cryptString(pass);
            ArrayList<String> loggInPersonInfo= new ArrayList<String>();
                                   loggInPersonInfo.add(krypteradeUname);
                                   loggInPersonInfo.add(krypteradeInsID);
                                   loggInPersonInfo.add(krypteradePass);
                                   Object[] elements = loggInPersonInfo.toArray();
    for(int i=0; i < elements.length ; i++)
    System.out.println(elements);
    sendOutStream.writeObject(loggInPersonInfo);
    sendOutStream.close();
    sendOutStream.flush();
    System.out.println("Skickade information...");
    int line = in.read();
    if(line > 0){
    user_id = line;
    return true;
    }else{
    return false;

    Here is the rest of code
    public void CheckLogin() throws SQLException, IOException, InterruptedException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, Exception{
    /**InputStream inpuStream;
    inpuStream = client.getInputStream();
    BufferedInputStream in= new BufferedInputStream(inpuStream);//(new BufferedReader(inpuStream));
    inpuStream = client.getInputStream();
    ObjectInputStream objectIn = new ObjectInputStream(inpuStream);
    ArrayList<String> personLoggIn = new ArrayList<String>();
    String krypteradeUname;
    String krypteradeInsID ;
    String krypteradePass ;
    personLoggIn = null;
    personLoggIn = (ArrayList<String>)objectIn.readObject();
    for (int i=0;i<personLoggIn.size();i++) {
    krypteradeUname=personLoggIn.get(0);
    krypteradeInsID =personLoggIn.get(1);
    krypteradePass = personLoggIn.get(2);
    System.out.println(i);
    inpuStream.close();
    CryptDecryptString decryptString = new CryptDecryptString();
    byte[] byteUname = decryptString.decryptString((krypteradeUname.getBytes()));
    String username = new String(byteUname);
    byte[] byteInsID = decryptString.decryptString((krypteradeInsID.getBytes()));
    String instanceID = new String(byteInsID);
    byte[] bytePassword = decryptString.decryptString((krypteradePass.getBytes()));
    String password = new String(bytePassword);
    Please help!
    Thanks!

  • Javax.crypto.IllegalBlockSizeException :Urgent please help !!!!

    error message:
    ===================================================
    javax.crypto.IllegalBlockSizeException: Input length (with padding) not multiple of 8 bytes
         at com.ibm.crypto.provider.DESCipher.a(Unknown Source)
         at com.ibm.crypto.provider.DESCipher.engineDoFinal(Unknown Source)
         at com.ibm.crypto.provider.DESCipher.engineDoFinal(Unknown Source)
         at javax.crypto.Cipher.doFinal(Unknown Source)
         at CreateRandomImage.doGet(CreateRandomImage.java:69)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.servlet.engine.webapp.StrictServletInstance.doService(ServletManager.java:827)
         at com.ibm.servlet.engine.webapp.StrictLifecycleServlet._service (StrictLifecycleServlet.java:167)
         at com.ibm.servlet.engine.webapp.IdleServletState.service(StrictLifecycleServlet.java:297)
         at com.ibm.servlet.engine.webapp.StrictLifecycleServlet.service(StrictLifecycleServlet.java:110)
         at com.ibm.servlet.engine.webapp.ServletInstance.service(ServletManager.java:472)
         at com.ibm.servlet.engine.webapp.ValidServletReferenceState.dispatch(ServletManager.java:1012)
         at com.ibm.servlet.engine.webapp.ServletInstanceReference.dispatch(ServletManager.java:913)
         at com.ibm.servlet.engine.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:721)
         at com.ibm.servlet.engine.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:374)
         at com.ibm.servlet.engine.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:118)
         at com.ibm.servlet.engine.srt.WebAppInvoker.doForward(WebAppInvoker.java:134)
         at com.ibm.servlet.engine.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:239)
         at com.ibm.servlet.engine.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:67)
         at com.ibm.servlet.engine.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:151)
         at com.ibm.servlet.engine.oselistener.OSEListenerDispatcher.service(OSEListener.java:315)
         at com.ibm.servlet.engine.http11.HttpConnection.handleRequest(HttpConnection.java:60)
         at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:332)
         at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:251)
         at com.ibm.ws.util.CachedThread.run(ThreadPool.java:138)
    ============================================================
    code part:
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++
    public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException
              String strValue = "";
              // fixedness encrypt key
              byte[] ENCRYPT_KEY = { 2, 69, -70, -5, -94, -15, -22, 93 };
              // get encrypted data from request
         String encryptedData = request.getParameter("encrypt");
         byte[] encryptedDataByte = encryptedData.getBytes();
              byte[] enbytes = encryptedData.getBytes();
         System.out.println("encrypted data >>>>>>>>" + encryptedData);
         try
         SecureRandom sr = new SecureRandom();
         DESKeySpec dks = new DESKeySpec(ENCRYPT_KEY);
         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
         javax.crypto.SecretKey keyEncrypt = keyFactory.generateSecret(dks);
         Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
         cipher.init(Cipher.DECRYPT_MODE, keyEncrypt, sr);
         System.out.println(" ========== length " + encryptedData.getBytes().length);
         // when execute the sentence, Exception throw !!!
         byte decryptedData[] = cipher.doFinal(enbytes);
         // dencrypted data
         strValue = new String(decryptedData);
         }catch(Exception ex){
              ex.printStackTrace();
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=

    // get encrypted data from request
    String encryptedData = request.getParameter("encrypt");
    byte[] encryptedDataByte = encryptedData.getBytes();
    byte[] enbytes = encryptedData.getBytes();Right here. This gets "encrypt" as a String, and tries to get the ciphertext as that String's bytes. You can't do that. String does horrible, horrible things to ciphertext.
    If you're going to transmit ciphertext as strings, you need to use Base64 to encode it before transfer, and then decode it after, to get your ciphertext back.
    Grant

  • 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

  • Javax.crypto.IllegalBlockSizeException: 6 trailing bytes

    Hi everybody!
    I'm facing a error when i try to encrypt a string with symmetric algorithm DES. I try to run the following code on Redhat:
    byte[] data="It is a test!".getBytes();
         Cipher cipher = Cipher.getInstance(algName);
         cipher.init(Cipher.ENCRYPT_MODE, key);
    int blocksize=cipher.getBlockSize();
         System.out.println("--------blocksize: "+blocksize); // blocksize=8
         byte[] cipherByte = cipher.doFinal(data); // 52 line
    The error showing is:
    javax.crypto.IllegalBlockSizeException: 6 trailing bytes
    at gnu.javax.crypto.jce.cipher.CipherAdapter.engineDoFinal(CipherAdapter.java:491)
    at javax.crypto.Cipher.doFinal(Cipher.java:495)
    at javax.crypto.Cipher.doFinal(Cipher.java:461)
    at cn.com.webinfo.security.SymmetricAlgorithm.encrypt(SymmetricAlgorithm.java:52)
    at cn.com.webinfo.stest.MainSymmetricAlgorithm.main(MainSymmetricAlgorithm.java:32)
    Can any one support.
    Thanks and waiting your replies.

    It would help if you showed the content of the String referenced by 'algName' since it looks to me like you are using "DES/ECB/NoPadding" and not either "DES" or "DES/ECB/PKCS5Padding".

  • 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.BadPaddingException: Given final block not properly padded

    import java.security.*;
    import javax.crypto.*;
    public class Cryptographer
    private final String DEFAULT_KEY="1111111111111111";
    private String KEY;
    public Cryptographer(String key)
    if((key==null)||key.equals(""))
    this.KEY = DEFAULT_KEY;
    else
    this.KEY = key;
    public byte[] encrypt(String toEncrypt)
    if((toEncrypt==null)||(toEncrypt.trim().equals("")))
    return null;
    try
    return DESEncrypt(toEncrypt,KEY);
    catch(Exception e)
    e.printStackTrace();
    return null;
    public String decrypt(byte[] bytes)
    if(bytes==null)
    return null;
    try
    return DESDecrypt(bytes,KEY);
    catch(Exception e)
    e.printStackTrace();
    return null+"hi";
    public String ToMac(byte[] bytes,String key)
    if(bytes==null)
    return null;
    try
    return getMac(bytes,KEY);
    catch(Exception e)
    return null;
    private byte[] DESEncrypt(String toEncrypt, String key)
    throws Exception
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    // do the encryption with that key
    Cipher cipher = Cipher.getInstance("DES");
    //DES/CFB8/NOPadding;DES/OFB32/PKCS5Padding;DESEDE/ECB/PKCS5Padding;DES/ECB/NOPadding==DES
    cipher.init(Cipher.ENCRYPT_MODE, sk);
    byte[] encrypted = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
    return new sun.misc.BASE64Encoder().encode(encrypted).toUpperCase().getBytes();
    //return encrypted;
    private String DESDecrypt(byte[] toDecrypt, String key)
    throws Exception
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    // do the decryption with that key
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.DECRYPT_MODE, sk);
    byte[] decrypted = cipher.doFinal(toDecrypt);
    return new sun.misc.BASE64Encoder().encode(decrypted).toUpperCase();
    //return new String(decrypted,"UTF-8");
    //create mac String; byte[] to be maced
    private String getMac(byte[] bytes,String key)
    byte[] bmac =null;
    try
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes());
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    Mac mac = Mac.getInstance("HmacMD5");
    //HmacMD5;HmacSHA1;PBEWith<mac> e.g PBEWithHmacSHA1
    mac.init(sk);
    bmac = mac.doFinal(bytes);
    catch(Exception e)
    e.printStackTrace();
    return new String(bmac);
    public String byte2hex(byte[] b) //��������������
    String hs="";
    String stmp="";
    for (int n=0;n<b.length;n++)
    stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
    if (stmp.length()==1) hs=hs+"0"+stmp;
    else hs=hs+stmp;
    if (n<b.length-1) hs=hs+"";
    return hs.toUpperCase();
    public static void main(String args[])
    throws Exception
    String key = new String("1111111111111111");
    Cryptographer c = new Cryptographer(key); //use key to initialize the class
    String str = new String("4A6C98EAEF14EAB6");
    byte[] b = c.encrypt(str); //to encrypt data
    System.out.println(b.length);
    System.out.println("Encrypted data:"+new String(b)+":"+new String(c.byte2hex(b))); //println Encrypt data
    String st = c.decrypt(str.getBytes()); //to decrypt data
    System.out.println(st.getBytes().length);
    System.out.println(st.length());
    System.out.println("Decrypted data:"+st+":"+c.byte2hex(st.getBytes())); //println decrypt data
    please help me! thax

    One: Use the [ code ] tags. Please. It'll only help you get answers.
    Two: encrypt() is returning the getBytes() of the result of Base64'ing the ciphertext. Bad. The whole POINT to Base64 is to produce Strings from byte[]'s. Don't use Base64 to produce a byte[]. Change encrypt() to return the byte[] directly.
    Three: Given that encrypt() is returning the byte[] from the Base64 - decrypt() needs to be ready to UNDO that. It isn't. decrypt() assumes the byte[] it's getting is the ciphertext. That's not what you're giving to it. It's very, very unhappy.
    Four: your main() isn't even handing decrypt() the (bogus) return from encrypt(). Your main() is asking decrypt() to decrypt your plaintext. That trick never works...
    Five: your choice of variable names in your main() is...suboptimal. If you'd chosen names that reflected the purpose of the variable (things like, say, 'plaintext' and 'ciphertext'), some of this would have been obvious.
    Try the following:import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.Mac;
    import javax.crypto.SecretKey;
    public class Cryptographer {
        private final String DEFAULT_KEY = "1111111111111111";
        private String KEY;
        public Cryptographer(String key) {
            if ((key == null) || key.equals("")) {
                this.KEY = DEFAULT_KEY;
            } else {
                this.KEY = key;
        public byte[] encrypt(String toEncrypt) {
            if ((toEncrypt == null) || (toEncrypt.trim().equals("")))
                return null;
            try {
                return DESEncrypt(toEncrypt, KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
        public String decrypt(byte[] bytes) {
            if (bytes == null)
                return null;
            try {
                return DESDecrypt(bytes, KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return null +"hi";
        public String ToMac(byte[] bytes, String key) {
            if (bytes == null)
                return null;
            try {
                return getMac(bytes, KEY);
            } catch (Exception e) {
                return null;
        private byte[] DESEncrypt(String toEncrypt, String key) throws Exception {
            // create a binary key from the argument key (seed)
            SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(56, sr);
            SecretKey sk = kg.generateKey();
            // do the encryption with that key
            Cipher cipher = Cipher.getInstance("DES");
            //DES/CFB8/NOPadding;DES/OFB32/PKCS5Padding;DESEDE/ECB/PKCS5Padding;DES/ECB/NOPadding==DES
            cipher.init(Cipher.ENCRYPT_MODE, sk);
            byte[] encrypted = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
            return encrypted;
        private String DESDecrypt(byte[] toDecrypt, String key) throws Exception {
            // create a binary key from the argument key (seed)
            SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(56, sr);
            SecretKey sk = kg.generateKey();
            // do the decryption with that key
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, sk);
            byte[] decrypted = cipher.doFinal(toDecrypt);
            return new String(decrypted,"UTF-8");
        //create mac String; byte[] to be maced
        private String getMac(byte[] bytes, String key) {
            byte[] bmac = null;
            try {
                // create a binary key from the argument key (seed)
                SecureRandom sr = new SecureRandom(key.getBytes());
                KeyGenerator kg = KeyGenerator.getInstance("DES");
                kg.init(56, sr);
                SecretKey sk = kg.generateKey();
                Mac mac = Mac.getInstance("HmacMD5");
                //HmacMD5;HmacSHA1;PBEWith<mac> e.g PBEWithHmacSHA1
                mac.init(sk);
                bmac = mac.doFinal(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            return new String(bmac);
        public String byte2hex(byte[] b) //��������������
            String hs = "";
            String stmp = "";
            for (int n = 0; n < b.length; n++) {
                stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
                if (stmp.length() == 1)
                    hs = hs + "0" + stmp;
                else
                    hs = hs + stmp;
                if (n < b.length - 1)
                    hs = hs + "";
            return hs.toUpperCase();
        public static void main(String args[]) throws Exception {
            String key = new String("1111111111111111");
            Cryptographer c = new Cryptographer(key); //use key to initialize the class
            String str = new String("Hello world!");
            byte[] ciphertext = c.encrypt(str); //to encrypt data
            System.out.println(ciphertext.length);
            System.out.println("Encrypted data:"  + new String(c.byte2hex(ciphertext )));
            String plaintext = c.decrypt(ciphertext );  //to decrypt data
            System.out.println(plaintext.getBytes().length);
            System.out.println(plaintext.length());
            System.out.println("Decrypted data:" + plaintext ); //println decrypt data
    }And please, please, PLEASE use the [ code ] tags...
    Grant

  • Input Date does not work correctly In dynamic region

    Hello everyone.
    I created a view with a dynamic region. When switch to a region with Input Date components, if I click the "Choose Date" button, this region will exit to default region without any error message.
    The component works well in default region but not in regions switched by Link.
    I tried it in a completely new application and i am sure there is no any problem except the component and the region themselves.
    SO, if someone tied doing this and know what cause it and how to fix it?
    Edited by: 1007000 on 2013-5-20 下午8:49

    Well, i find out the problem. I set the managed bean of the region backing scope, and Input Date is a server-side component. So the taskflow id will lost when i click the Choose Date button.
    change the scope to pageflow, and it works.

  • Display error messages in Visual Composer if Input Data is not valid

    Hi,
    We developed a small iView with a single input field FO (Factory Order).
    The output is a table with some fields corresponding to the given FO.
    My requirement is if the given FO (Factory Order) has no data then the table should not be displayed, instead a message should be displayed saying
    'No Data is found' and stop the program.
    Please reply soon if anyone has got a solution.
    Thanks,
    Shashidhar

    Hi
    You can use <b>guard condition</b> of the event to check whether input field(FO) has data or not. When the input field is empty , you can open a <b>pop-up iView</b> displaying "No Data is found" and when the input field has data , you can execute your service to produce the table output.
    If, you have any more doubts, revert back
    Thanks & Regards
    Harsimran

  • Problem with input data format - not "only" XML

    Hi Experts,
    I have problem with input data format.
    I get some data from JMS ( MQSeries) , but input format is not clear XML. 
    This is some like flat file with content of XMLu2026.
    Example:
    0000084202008-11-0511:37<?xml version="1.0" encoding="UTF-8"?>
    <Document xmlns="urn:xsd:test.01" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance Sndr="0001" Rcvr="SP">
    ...content....
    </Document>000016750
    Problems in this file is :
    1. data before parser <? xml version="1.0"> -> 0000084202008-11-0511:37 
    2. data after last parser </Document> -> 000016750
    This data destroy XML format.
    Unfortunately XI is not one receiver of this files and we canu2019t change this file format in queue MQSeries ( before go to XI) .
    My goal is to get XML from this file:
    <?xml version="1.0" encoding="UTF-8"?>
    <Document xmlns="urn:xsd:test.01" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance Sndr="0001" Rcvr="SP">
    ...content....
    </Document>
    My questions:
    1. Is any way or technique to delete this data 0000084202008-11-0511:37  in XI from this file ?
    2. Is any way to get only XML from this file ?
    Thanx .
    Regards,
    Seo

    Hi Buddy
    What is the XI adapter using?
    If you use inbound File adapter content conversion you could replace these values with none and then pass it to the scenario.
    Does that help?
    Regards
    cK

  • Cryptography - javax.crypto.BadPaddingException: Given final block not prop

    Hi,
    I am getting BadPaddingException while invoking doFinal method. My requirement is that I have to encode a string and then send append it to a URL as query string and send this URL in email. When user gets the email he can click on the link. When the link is clicked the servlet reads the encoded string from request parameter and decodes it. While decoding I am getting following error. Though the error does not come always. Sometimes it decodes nicely but a lot of times it throws error. I am posting my code here. Any help will be appreciated. Thanks in advance.
    public class EncryptionUtil {
         private static final String ENCRYPTION_ALGORITHM = "AES/ECB/PKCS5Padding";
         private static final String DIGEST_ALGORITHM = "MD5";
         //following instance variables are maintained/cached for performance reasons
         private Key key;
         private Cipher encryptCipher;
         private Cipher decryptCipher;
         * @param keyText keyText the corresponds to the password-wrapped secret key
         * @param password password to unwrap the secret key
         private EncryptionUtil(String keyText, String password) {
              key = KeyGenUtil.parseKey(keyText, password);
              if (key == null) {
                   throw new RuntimeException("Unable to retrieve key from the database");
              try {
                   encryptCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
                   encryptCipher.init(Cipher.ENCRYPT_MODE, key);
                   decryptCipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
                   decryptCipher.init(Cipher.DECRYPT_MODE, key);
         } catch (GeneralSecurityException ex) {
              throw new RuntimeException("Unable to instantiate ciphers", ex);
         private static EncryptionUtil instance;
         * Returns an instance of EncryptionUtil that has been initialized with
         * the appropriate encryption and decryption ciphers.
         * @param keyText keyText the corresponds to the password-wrapped secret key
         * @param password password to unwrap the secret key
         * @return EncryptionUtil
         public static EncryptionUtil newInstance(String keyText, String password) {
              if (instance == null) {
                   instance = new EncryptionUtil(keyText, password);
              return instance;
    * Encrypt the input message
    * @param message the message to be encrypted
    * @return the result of encryption
         public String encrypt(String clearText) {
              if (clearText == null) {
                   return null;
              try {
                   return new String(Base64.encodeBase64(encryptCipher.doFinal(clearText.getBytes())));
    } catch (GeneralSecurityException ex) {
         throw new RuntimeException("Encryption failed", ex);
    * Decrypt an encrypted message
    * @param encryptedMessage the encrypted message to be decrypted
    * @return the result of decryption
         public String decrypt(String encryptedMessage) {
              if (encryptedMessage == null) {
                   return null;
              try {
                   return new String(decryptCipher.doFinal(Base64.decodeBase64(encryptedMessage.getBytes())));
    } catch (GeneralSecurityException ex) {
         throw new RuntimeException("Decryption failed", ex);
         * Digest operation on a String message.
         * @param msg
         * @return
         * @throws CPException
         public static String digest(String msg) throws CPException{
              if(null == msg){
                   return null;
              String encrytedMessage = null;
              byte[] digest = null;
              try{
                   byte[] msgBytes = msg.getBytes();
                   // Generating Salt.
                   byte[] salt = KeyGenUtil.generateSalt();
                   digest = digest(msgBytes, salt);
         // Encode the bytes with Base64.
                   encrytedMessage = new String(Base64.encodeBase64(digest));
              }catch(GeneralSecurityException ex){
                   throw new RuntimeException("Error while digest.", ex);
              return encrytedMessage;
         * This method is used for digest the message bytes with the given salt.
         * @param message
         * @param salt
         * @return
         * @throws GeneralSecurityException
         private static byte[] digest(byte[] message, byte[] salt)
                                                           throws GeneralSecurityException {
              byte[] encrytedMessage = new byte[0];
              MessageDigest md;
              if(null != salt){
                   encrytedMessage = ArrayUtils.addAll(encrytedMessage, salt);
              byte[] digest = null;
              // Getting Message Digest
              md = MessageDigest.getInstance(DIGEST_ALGORITHM);
              // Digest the message.
              md.reset();
              if(null != salt){
                   // Salt added to Digest.
                   md.update(salt);
              md.update(message);
              // Digest the message for SECRET_KEY_ITERATION_COUNT times.
              digest = md.digest();
              for(int i=0; i<(KeyGenUtil.SECRET_KEY_ITERATION_COUNT - 1); i++){
                   md.reset();
                   digest = md.digest(digest);
              // Merge the salt and digest.
              encrytedMessage = ArrayUtils.addAll(encrytedMessage, digest);
              return encrytedMessage;
    }

    bini_dev wrote:
    Thanks for your response.
    I am getting the point. But then how am I supposed to solve it?
    Should I use some other encoding?If it is an encoding problem then that is all you can do. To prove the point, you could URL encode the Base64 output.

  • 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.");

  • AES with two keys javax.crypto.BadPaddingException

    Hello,
    I'am trying to encrypt / decrypt using AES, which performs correctly for one level encryption / decryption. However, when I am trying a two level encryption / decryption. I have this code:
    String message="This is just an example";
    byte[] raw="df5ea29924d39c3be8785734f13169c6".getBytes("ISO-8859-1");
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal((args.length == 0 ? "This is just an example" : args[0]).getBytes());
    System.out.println("encrypted string: " + asHex(encrypted));
    raw="ef5ea29924d39c3be8785734f13169c7".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypteded = cipher.doFinal(encrypted);
    raw="df5ea29924d39c3be8785734f13169c6".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original1 = cipher.doFinal(encrypteded);
    raw="ef5ea29924d39c3be8785734f13169c7".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original2 = cipher.doFinal(original1);
    I get this exception:
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:317)
    at javax.crypto.Cipher.doFinal(Cipher.java:1813)
    Thank you!

    marya_a wrote:
    Thank you for you replay. Can you tell me if there is a symmetric and commutative cryptosystem. Since XOR commutes I would expect that any of the stream ciphers that generate a stream of pseudo random bits and XOR these with the cleartext to create the ciphertext will work. RC4 and block algorithms (AES, DES etc) using modes such as CFB spring to mind.
    Of course these should only be used with random session keys since using fixed keys (as you seem to have) is fundamentally insecure.
    I know that RSA is commutative, I'm pretty sure that this applies only if all stages use the same modulus.
    but I want it to be also symmetric.Edited by: sabre150 on Apr 13, 2010 9:41 AM

  • Issue with javax.crypto.SecretFactory

    I am getting the following error in the following code:
    DESedeKeySpec spec = new DESedeKeySpec( baKey );
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstanc( "DESede" );
    Here is the error message:
    java.security.NoSuchAlgorithmException: Algorithm DESede not available
         at javax.crypto.SunJCE_b.a(DashoA6275)
         at javax.crypto.SecretKeyFactory.getInstance(DashoA6275)
    I will really appreciate any help.

    Looks like it has something to do with the jdk installed on my machine. I changed the location of jdk and I get the following error:
    javax.crypto.BadPaddingException: Given final block not properly padded
         at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
         at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
         at javax.crypto.Cipher.doFinal(DashoA6275)

Maybe you are looking for