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!

Similar Messages

  • 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

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

  • '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.BadPaddingException: Data must start with zero

    Actually, I didn't write the entire codes, most of it was written by someone here, and I only tried to add a method. Here:
    public class RSAEncrypt {
        private KeyPair keys;
        private Cipher rsaCipher;
        public RSAEncrypt() throws GeneralSecurityException {
            KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
            keygen.initialize(512);
            keys = keygen.generateKeyPair();
            rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        public byte[] encrypt(byte[] message) throws GeneralSecurityException {
            rsaCipher.init(Cipher.ENCRYPT_MODE, keys.getPublic());
            return rsaCipher.doFinal(message);
        public byte[] decrypt(byte[] encryptedMessage) throws GeneralSecurityException {
             rsaCipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
             return rsaCipher.doFinal(encryptedMessage);
         * @param args
        public static void main(String[] args) throws Exception {
             String message = "The quick brown fox ran away";
             System.out.println("Message: " + message);
             byte[] encrypted = new RSAEncrypt().encrypt(message.getBytes());
            System.out.println("Cipher Text: " + HexBin.encode(encrypted));
            byte[] decrypted = new RSAEncrypt().decrypt(encrypted);
            System.out.println("Decrypted Text: " + decrypted);
    }The idea is that the program should encrypt the String, "The quick brown fox ran away," which it does. But when it gets to this line:
    byte[] decrypted = new RSAEncrypt().decrypt(encrypted);i get the error: javax.crypto.BadPaddingException: Data must start with zero.
    But here's the funny thing: If I edit the codes so that the encryption and decryption are done in the constructor, it works! Here:
    public class RSAEncrypt {
        private KeyPair keys;
        private Cipher rsaCipher;
        public RSAEncrypt() throws GeneralSecurityException {
            KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
            keygen.initialize(512);
            keys = keygen.generateKeyPair();
            rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            rsaCipher.init(Cipher.ENCRYPT_MODE, keys.getPublic());
            String message = "The quick brown fox ran away";
            byte[] cipherText = rsaCipher.doFinal(message.getBytes());
            System.out.println(new BASE64Encoder().encode(cipherText));
            rsaCipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
            byte[] decryptedText = rsaCipher.doFinal(cipherText);
            String dText = new String(decryptedText);
            System.out.println(dText);
         * @param args
        public static void main(String[] args) throws Exception {
             new RSAEncrypt();
    }So, I'm confused. The Data must start with zero error is coming up when I pass encrypted data to a method for decryption, but it doesn't come out when I run everything in one method or in the constructor. Why???
    Also, when performing RSA encryption (or decryption) on a plaintext stored in a file (not a big file, just a file with probably one or two lines), this is what I do (and it works):
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    CipherInputStream cis = new CipherInputStream(new FileInputStream(new File("message.txt")),cipher);My question is, I do see some people doing this as well:
    cipher.doFinal(byteArray);The fact that I don't have this in my code when encrypting data from a file, that's ok, right? I don't need to do a ".doFinal()" method, do I?
    Edited by: glenak on Aug 19, 2010 4:26 AM

    glenak wrote:
    I don't quite understand, but if you mean this:
    String message = "The quick brown fox ran away";
    System.out.println("Message: " + message);
    RSAEncrypt rsaEncrypt = new RSAEncrypt();
    Creates and instance of RSAEncrypt with a new random RSA key pair.
    byte[] encrypted = rsaEncrypt.encrypt(message.getBytes());Encrypts with the random public key created in the first instance.
    System.out.println("Cipher Text: " + HexBin.encode(encrypted));
    RSAEncrypt rsaDecrypt = new RSAEncrypt();Creates and second instance of RSAEncrypt with a new random RSA key pair nothing to do with the first instance.
    byte[] decrypted = rsaDecrypt.decrypt(encrypted);Attempts to decrypt the ciphertext created with the public key of the first instance using the private key of the second, and totally unrelated, instance.
    System.out.println("Decrypted Text: " + decrypted);I still get the "Data must start with zero" error.
    If you could show me an example of what you mean, it would help very muchNo example is required. You cannot encrypt with the public key of one key pair and expect to decrypt with the private key of a totally independent key pair.

  • Javax.crypto.BadPaddingException: unknown block type - URGENT

    I am trying to encryp-decrypt a file (serialized xml file ) using BC provider with RSA algorithm and PKCS1Padding padding..
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC")
    Sequence of action is encrypt - base64encode -
    base64decode - decrypt.
    Encryption seems to be working fine but while decrypting it gives the error mentioned below:
    javax.crypto.BadPaddingException: unknown block type
    I tried using OAEPPadding - In that scenario I get this error
    javax.crypto.BadPaddingException: data hash wrong
    I tried searching the cause and resolution of the problems on various resources on net but in vain. Need it urgently. PLS HELP. THANKS
    I am pasting my code below :
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Security;
    import java.security.spec.EncodedKeySpec;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import javax.crypto.Cipher;
    import org.apache.log4j.Logger;
    import org.bouncycastle.jce.provider.*;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    public class EncryptBase64File
    protected static final String ALGORITHM = "RSA";
         private static Logger logger = Logger.getLogger(EncryptFiles.class.getClass());
    private EncryptBase64File()
    * Init java security to add BouncyCastle as an RSA provider
    public static void init()
    Security.addProvider(new BouncyCastleProvider());
    * Generate key which contains a pair of privae and public key using 1024 bytes
    * @return key pair
    * @throws NoSuchAlgorithmException
    public static KeyPair generateKey() throws NoSuchProviderException,NoSuchAlgorithmException
    //KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
              KeyPairGenerator keyGen =
                                  KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(1024);
    KeyPair key = keyGen.generateKeyPair();
    return key;
    * Encrypt a text using public key.
    * @param text The original unencrypted text
    * @param key The public key
    * @return Encrypted text
    * @throws java.lang.Exception
    public static byte[] encrypt(byte[] text, PublicKey key) throws Exception
    byte[] cipherText = null;
    try
    // get an RSA cipher object and print the provider
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
                   //Cipher cipher = Cipher.getInstance("RSA");
                   System.out.println("\nProvider is: " + cipher.getProvider().getInfo());
                   System.out.println("\nStart encryption with public key");
    if (logger.isDebugEnabled())
                        logger.debug("\nProvider is: " + cipher.getProvider().getInfo());
                        logger.debug("\nStart encryption with public key");
    // encrypt the plaintext using the public key
    cipher.init(Cipher.ENCRYPT_MODE, key);
    cipherText = cipher.doFinal(text);
    catch (Exception e)
                   logger.error(e, e);
    throw e;
    return cipherText;
    * Encrypt a text using public key. The result is enctypted BASE64 encoded text
    * @param text The original unencrypted text
    * @param key The public key
    * @return Encrypted text encoded as BASE64
    * @throws java.lang.Exception
    public static String encrypt(String text, PublicKey key) throws Exception
    String encryptedText;
    try
    byte[] cipherText = encrypt(text.getBytes("UTF8"),key);
    encryptedText = encodeBASE64(cipherText);
                   System.out.println("Enctypted text is: " + encryptedText);
                   logger.debug("Enctypted text is: " + encryptedText);
    catch (Exception e)
                   logger.error(e, e);
    throw e;
    return encryptedText;
    * Decrypt text using private key
    * @param text The encrypted text
    * @param key The private key
    * @return The unencrypted text
    * @throws java.lang.Exception
    public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception
    byte[] dectyptedText = null;
    try
    // decrypt the text using the private key
    //Cipher cipher = Cipher.getInstance("RSA/CBC/PKCS1Padding","BC");
                   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
                   //Cipher cipher = Cipher.getInstance("RSA");
                   logger.debug("Start decryption");
                   System.out.println("Start decryption");
    cipher.init(Cipher.DECRYPT_MODE, key);
    dectyptedText = cipher.doFinal(text);
    catch (Exception e)
                   logger.error(e, e);
    throw e;
    return dectyptedText;
    * Decrypt BASE64 encoded text using private key
    * @param text The encrypted text, encoded as BASE64
    * @param key The private key
    * @return The unencrypted text encoded as UTF8
    * @throws java.lang.Exception
    public static String decrypt(String text, PrivateKey key) throws Exception
    String result;
    try
    // decrypt the text using the private key
    byte[] dectyptedText = decrypt(decodeBASE64(text),key);
    result = new String(dectyptedText, "UTF8");
                   logger.debug("Decrypted text is: " + result);
    catch (Exception e)
                   logger.error(e, e);
    throw e;
    return result;
    * Encode bytes array to BASE64 string
    * @param bytes
    * @return Encoded string
    private static String encodeBASE64(byte[] bytes)
    BASE64Encoder b64 = new BASE64Encoder();
    return b64.encode(bytes);
    * Decode BASE64 encoded string to bytes array
    * @param text The string
    * @return Bytes array
    * @throws IOException
    private static byte[] decodeBASE64(String text) throws IOException
    BASE64Decoder b64 = new BASE64Decoder();
    return b64.decodeBuffer(text);
    * Encrypt file using 1024 RSA encryption
    * @param srcFileName Source file name
    * @param destFileName Destination file name
    * @param key The key. For encryption this is the Private Key and for decryption this is the public key
    * @param cipherMode Cipher Mode
    * @throws Exception
    public static void encryptFile(String srcFileName, String destFileName, PublicKey key) throws Exception
    encryptDecryptFile(srcFileName,destFileName, key, Cipher.ENCRYPT_MODE);
    * Decrypt file using 1024 RSA encryption
    * @param srcFileName Source file name
    * @param destFileName Destination file name
    * @param key The key. For encryption this is the Private Key and for decryption this is the public key
    * @param cipherMode Cipher Mode
    * @throws Exception
    public static void decryptFile(String srcFileName, String destFileName, PrivateKey key) throws Exception
    encryptDecryptFile(srcFileName,destFileName, key, Cipher.DECRYPT_MODE);
    * Encrypt and Decrypt files using 1024 RSA encryption
    * @param srcFileName Source file name
    * @param destFileName Destination file name
    * @param key The key. For encryption this is the Private Key and for decryption this is the public key
    * @param cipherMode Cipher Mode
    * @throws Exception
    public static void encryptDecryptFile(String srcFileName, String destFileName, Key key, int cipherMode) throws Exception
    OutputStream outputWriter = null;
    InputStream inputReader = null;
    try
              Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    String textLine = null;
    byte[] buf = cipherMode == Cipher.ENCRYPT_MODE? new byte[100] : new byte[128];
    int newBuffer;
    // init the Cipher object for Encryption...
    cipher.init(cipherMode, key);
    // start FileIO
    outputWriter = new FileOutputStream(destFileName);
    inputReader = new FileInputStream(srcFileName);
    while ( (bufl = inputReader.read(buf)) != -1)
    String encText = null;
    String base64EncText = null ;
    if (cipherMode == Cipher.ENCRYPT_MODE)
    encText = encrypt(getBytes(buf,newBuffer).toString(),(PublicKey)key);
    else
    encText = decrypt(getBytes(buf,newBuffer).toString(),(PrivateKey)key);
                   outputWriter.write(encText.getBytes());
    outputWriter.flush();
    catch (Exception e)
                   logger.error(e,e);
    throw e;
    finally
    try
    if (outputWriter != null)
    outputWriter.close();
    if (inputReader != null)
    inputReader.close();
    catch (Exception e)
    public static byte[] getBytes(byte[] arr, int length)
    byte[] newArr = null;
    if (arr.length == length)
    newArr = arr;
    else
    newArr = new byte[length];
    for (int i = 0; i < length; i++)
    newArr[i] = (byte) arr;
    return newArr;
         public static void main(String args[])
              throws Exception
              init();
              KeyPair keyPair = generateKey();
              PublicKey pubKey = keyPair.getPublic();
              PrivateKey privKey = keyPair.getPrivate();
              encryptFile("C:\\Temp\\TestFile.xml","C:\\Temp\\RSAEncryptedText.xml",pubKey);
              decryptFile("C:\\Temp\\RSAEncryptedText.xml","C:\\Temp\\RSADecryptedText.xml",privKey);

    I think you are the same poster as 'contebral'. Why the multiple identities?
    First off, the code you posted doesn't even compile. The getBytes() method has an error. Also, in method encryptDecryptFile() the variable bufl is not declared.
    The rest of the code is a mess. The toString() method does not do what you think it does; you're just going to get the object reference id. There is no reason to keep converting to/from byte arrays and Strings. Most of the time your data should be kept as a byte array, only possibly converting for I/O operations.
    The size of the base64 encoded output is not 128 bytes, it is 172 bytes. At this point I ran out of patience and stopped looking.
    There is no shame in being a beginner in Java, but you must walk before you can run. Stop running.

  • 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

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

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

  • ORA-28232: invalid input length for obfuscation toolkit

    hi,
    i am facing this error when i enterd more then 8 charecter in the input string.
    ORA-28232: invalid input length for obfuscation toolkit
    why i cant user more then 8 charecter for password.?

    Rajnish Chauhan wrote:
    hi,
    i am facing this error when i enterd more then 8 charecter in the input string.
    ORA-28232: invalid input length for obfuscation toolkit
    why i cant user more then 8 charecter for password.?
    28232, 0000, "invalid input length for obfuscation toolkit"
    // *Cause:  Length of data submitted for encryption or decryption is not a
    //          multiple of 8 bytes.
    // *Action: Make sure that the length of the data to be encrypted or decrypted
    //          is a multiple of 8 bytes.since you did not share with us exactly what you did, we can say exactly what you did wrong.
    How do I ask a question on the forums?
    SQL and PL/SQL FAQ

Maybe you are looking for

  • Creation of Query View

    Hi All, Can someone pls explain me how to create a query view and what is its importance? Thanks in advance. Chaitra

  • BPEL - SOA Suite 10.1.3.1.0

    How do we create a new domain in BPEL 10.1.3.1? I want to leave the default domain alone and create a new domain say, "myDevBPEL" In 10.1.2.0.x seems straight forward - login to admin console and we can create a new domain and this way, we can leave

  • New iPhone 5 error message

    i got a new iPhone bought to me from Egypt and trying to connect the App Store the phone won't connect at all and it gave me the following message "the certificate for this server is invalid.you might be connecting to a server that is pretending to b

  • 2.0.1 Problem

    While I am downloading the 2.0.1. update for my iPod touch, it stops and says "There was a problem downloading the iPod software. The network connection timed out. Make sure your network settings are correct and your network connection is active, or

  • Restore default isolation level fails with connection in pool

    Hi, I am developing an application that needs to set the TransactionIsolation to SERIALIZE for a transaction. Setting the TransactionIsolation is not the problem. After this transaction is committed or rolled back, i set the isolation level back to t