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.

Similar Messages

  • RSA decryption Error: Data must start with zero

    Because of some reasons, I tried to use RSA as a block cipher to encrypt/decrypt a large file. When I debug my program, there some errors are shown as below:
    javax.crypto.BadPaddingException: Data must start with zero
         at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
         at sun.security.rsa.RSAPadding.unpad(Unknown Source)
         at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
         at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:394)
         at javax.crypto.Cipher.doFinal(Cipher.java:2299)
         at RSA.RRSSA.main(RRSSA.java:114)
    From breakpoint, I think the problem is the decrypt operation, and Cipher.doFinal() can not be operated correctly.
    I searched this problem from google, many people met the same problem with me, but most of them didn't got an answer.
    The source code is :
    Key generation:
    package RSA;
    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    public class GenKey {
          * @param args
                     * @author tang
         public static void main(String[] args) {
              // TODO Auto-generated method stub
                 try {
                      KeyPairGenerator KPG = KeyPairGenerator.getInstance("RSA");
                      KPG.initialize(1024);
                      KeyPair KP=KPG.genKeyPair();
                      PublicKey pbKey=KP.getPublic();
                      PrivateKey prKey=KP.getPrivate();
                      //byte[] publickey = decryptBASE64(pbKey);
                      //save public key
                      FileOutputStream out=new FileOutputStream("RSAPublic.dat");
                      ObjectOutputStream fileOut=new ObjectOutputStream(out);
                      fileOut.writeObject(pbKey);
                      //save private key
                          FileOutputStream outPrivate=new FileOutputStream("RSAPrivate.dat");
                      ObjectOutputStream privateOut=new ObjectOutputStream(outPrivate);
                                 privateOut.writeObject(prKey)
         }Encrypte / Decrypt
    package RSA;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.security.Key;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.crypto.Cipher;
    //import sun.misc.BASE64Decoder;
    //import sun.misc.BASE64Encoder;
    public class RRSSA {
          * @param args
         public static void main(String[] argv) {
              // TODO Auto-generated method stub
                //File used to encrypt/decrypt
                 String dataFileName = argv[0];
                 //encrypt/decrypt: operation mode
                 String opMode = argv[1];
                 String keyFileName = null;
                 //Key file
                 if (opMode.equalsIgnoreCase("encrypt")) {
                 keyFileName = "RSAPublic.dat";
                 } else {
                 keyFileName = "RSAPrivate.dat";
                 try {
                 FileInputStream keyFIS = new FileInputStream(keyFileName);
                 ObjectInputStream OIS = new ObjectInputStream(keyFIS);
                 Key key = (Key) OIS.readObject();
                 Cipher cp = Cipher.getInstance("RSA/ECB/PKCS1Padding");//
                 if (opMode.equalsIgnoreCase("encrypt")) {
                 cp.init(Cipher.ENCRYPT_MODE, key);
                 } else if (opMode.equalsIgnoreCase("decrypt")) {
                 cp.init(Cipher.DECRYPT_MODE, key);
                 } else {
                 return;
                 FileInputStream dataFIS = new FileInputStream(dataFileName);
                 int size = dataFIS.available();
                 byte[] encryptByte = new byte[size];
                 dataFIS.read(encryptByte);
                 if (opMode.equalsIgnoreCase("encrypt")) {
                 FileOutputStream FOS = new FileOutputStream("cipher.txt");
                 //RSA Block size
                 //int blockSize = cp.getBlockSize();
                 int blockSize = 64 ;
                 int outputBlockSize = cp.getOutputSize(encryptByte.length);
                 /*if (blockSize == 0)
                      System.out.println("BLOCK SIZE ERROR!");       
                 }else
                 int leavedSize = encryptByte.length % blockSize;
                 int blocksNum = leavedSize == 0 ? encryptByte.length / blockSize
                 : encryptByte.length / blockSize + 1;
                 byte[] cipherData = new byte[outputBlockSize*blocksNum];
                 //encrypt each block
                 for (int i = 0; i < blocksNum; i++) {
                 if ((encryptByte.length - i * blockSize) > blockSize) {
                 cp.doFinal(encryptByte, i * blockSize, blockSize, cipherData, i * outputBlockSize);
                 } else {
                 cp.doFinal(encryptByte, i * blockSize, encryptByte.length - i * blockSize, cipherData, i * outputBlockSize);
                 //byte[] cipherData = cp.doFinal(encryptByte);
                 //BASE64Encoder encoder = new BASE64Encoder();
                 //String encryptedData = encoder.encode(cipherData);
                 //cipherData = encryptedData.getBytes();
                 FOS.write(cipherData);
                 FOS.close();
                 } else {
                FileOutputStream FOS = new FileOutputStream("plaintext.txt");
                 //int blockSize = cp.getBlockSize();
                 int blockSize = 64;
                 //int j = 0;
                 //BASE64Decoder decoder = new BASE64Decoder();
                 //String encryptedData = convert(encryptByte);
                 //encryptByte = decoder.decodeBuffer(encryptedData);
                 int outputBlockSize = cp.getOutputSize(encryptByte.length);
                 int leavedSize = encryptByte.length % blockSize;
                 int blocksNum = leavedSize == 0 ? encryptByte.length / blockSize
                           : encryptByte.length / blockSize + 1;
                 byte[] plaintextData = new byte[outputBlockSize*blocksNum];
                 for (int j = 0; j < blocksNum; j++) {
                 if ((encryptByte.length - j * blockSize) > blockSize) {
                      cp.doFinal(encryptByte, j * blockSize, blockSize, plaintextData, j * outputBlockSize);
                      } else {
                      cp.doFinal(encryptByte, j * blockSize, encryptByte.length - j * blockSize, plaintextData, j * outputBlockSize);
                 FOS.write(plaintextData);
                 //FOS.write(cp.doFinal(encryptByte));
                 FOS.close();
    }Edited by: sabre150 on Aug 3, 2012 6:43 AM
    Moderator action : added [ code] tags so as to make the code readable. Please do this yourself in the future.
    Edited by: 949003 on 2012-8-3 上午5:31

    1) Why are you not closing the streams when writing the keys to the file?
    2) Each block of RSA encrypted data has size equal to the key modulus (in bytes). This means that for a key size of 1024 bits you need to read 128 bytes and not 64 bytes at a time when decrypting ( this is probably the cause of your 'Data must start with zero exception'). Since the input block size depends on the key modulus you cannot hard code this. Note - PKCS1 padding has at least 11 bytes of padding so on encrypting one can process a maximum of the key modulus in bytes less 11. Currently you have hard coded the encryption block at 64 bytes which is OK for your 1024 bits keys but will fail for keys of modulus less than about 936 bits.
    3) int size = dataFIS.available(); is not a reliable way to get the size of an input stream. If you check the Javadoc for InputStream.available() you will see that it returns the number of bytes that can be read without blocking and not the stream size.
    4) InputStream.read(byte[]) does not guarantee to read all the bytes and returns the number of bytes actually read. This means that your code to read the content of the file into an array may fail. Again check the Javadoc. To be safe you should used DataInputStream.readFully() to read a block of bytes.
    5) Reading the whole of the cleartext or ciphertext file into memory does not scale and with very large files you will run out of memory. There is no need to do this since you can use a "read a block, write the transformed block" approach.
    RSA is a very very very slow algorithm and it is not normal to encrypt the whole of a file using it. The standard approach is to perform the encryption of the file content using a symmetric algorithm such as AES using a random session key and use RSA to encrypt the session key. One then writes to the ciphertext file the RSA encrypted session key followed by the symmetric encrypted data. To make it more secure one should actually follow the extended procedure outlined in section 13.6 of Practical Cryptography by Ferguson and Schneier.

  • Javax.crypto.BadPaddingException: pad block corrupted with 1.4

    I'm getting a javax.crypto.BadPaddingException: pad block corrupted Exception while working on converting our existing java jdk 1.2 to java 1.4. Any suggestions would be great. Here are the specifics:
    We have a web application that been running for several years under java jdk 1.2 & jce_1_2.jar. Within the application we are exchanging data (XML) with a customer using the following encryption scheme:
    1) We create a one time DESede key through the KeyGenerator class passing in ("DESede", "BC")
    2) We encrypt the data with this one time key using ("DESede/ECB/PKCS5Padding", "BC")
    3) This one time key is then encrypted using ("RSA/ECB/PKCS1Padding", "BC") and customer's public key
    4) We create a signature with our private key, which they have the public key for.
    This is process/api that we had to use for their API's and its worked fine under 1.2, with "ABA" as the provider. Now moving to 1.4, I'm using BouncyCastle as the provider.
    Other differences, the keystore in 1.2 was defined as "JCEKS" provider "SunJCE" under 1.4 I changed them to "JKS" and "SUN" . I would get bad header exceptions from keystore until I changed it. I don't think its the BouncyCastle since I was able to download the 1.2 version of BC and get the existing app to work and I also got the 1.4 version of BC to work under the existing 1.2 application.
    So something seems to be different with the algorithms/padding, but I can't seem to find it. I tried the following: "RSA" "RSA/ECB" "RSA//PKCS1Padding" "NoPadding" also changed the DESede algorithm with no luck. All I know is that its failing on the decryption of the one time key.
    Thanks

    http://forum.java.sun.com/forum.jsp?forum=60 is probably a better place to post this.

  • 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 with two keys javax.crypto.BadPaddingException

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

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

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

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

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

  • Javax.crypto.BadPaddingException: pad block corrupted  when using Java 1.4

    I'm getting a javax.crypto.BadPaddingException: pad block corrupted Exception while working on converting our existing java jdk 1.2 to java 1.4. Any suggestions would be great. Here are the specifics:
    We have a web application that been running for 3+ years under java jdk 1.2 & jce_1_2.jar. Within the application we are exchanging data (XML) with a customer using the following encryption scheme:
    1) We create a one time DESede key through the KeyGenerator class passing in ("DESede", "BC")
    2) We encrypt the data with this one time key using ("DESede/ECB/PKCS5Padding", "BC")
    3) This one time key is then encrypted using ("RSA/ECB/PKCS1Padding", "BC") and customer's public key
    4) We create a signature with our private key, which they have the public key for.
    This is process/api that we required to use for their API's and its worked fine under 1.2, with "ABA" as the provider. Now moving to 1.4, I'm using BouncyCastle as the provider.
    Other differences, the keystore was created under 1.2 and in 1.2 it was defined as "JCEKS" provider "SunJCE" under 1.4 I changed them to "JKS" and "SUN" . I would get bad header exceptions when reading from the keystore until I changed it. I don't think its the BouncyCastle since I was able to download the 1.2 version of BC and get the existing app to work and I also got the 1.4 version of BC to work under the existing 1.2 application.
    So something seems to be different with the algorithms/padding, but I can't seem to find it. I tried the following: "RSA" "RSA/ECB" "RSA//PKCS1Padding" "NoPadding" also changed the DESede algorithm with no luck. All I know is that its failing on the decryption of the one time key, since its failing on the customer side, I don't have much other insight into it, other then the exception that they sent me.
    More info: getting error on Java: build 1.4.2_02-b03 on Solaris 5.8
    Existing application running: Java JDK_1.2.2_10 on Solaris 5.8
    BouncyCastle: bcprov-jdk14-124.jar
    Thanks

    Here is the stackTrace that I was sent:
    20040804;10:29:37: javax.crypto.BadPaddingException: pad block corrupted
    20040804;10:29:37: at org.bouncycastle.jce.provider.JCEBlockCipher.engineDo
    Final(JCEBlockCipher.java:460)
    20040804;10:29:37: at javax.crypto.Cipher.doFinal(Cipher.java:1129)
    20040804;10:29:37: at com.customer.crypto.SymmetricCryptor.decrypt(SymmetricCryptor.java:105)
    20040804;10:29:37: at com.customer.crypto.SymmetricCryptor.decryptToStr
    ing(SymmetricCryptor.java:95)
    20040804;10:29:37: at com.customer.api.Data.DataServlet doPost(DataServlet.java:88)

  • Javax.crypto.BadPaddingException

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

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

  • Javax.crypto.BadPaddingException: unknown block type

    Hello,
    I`m trying to decode some data but it keeps getting me: javax.crypto.BadPaddingException: unknown block type
    Here is my code:
    import java.io.*;
    import java.security.*;
    import java.security.spec.*;
    import java.security.interfaces.*;
    import javax.crypto.*;
    public class Main{
      public static void main(String args[]){
        try{
          byte[] pubKeyBytes  = getBytesFromFile("RSAPublicKey.der");
          byte[] privKeyBytes = getBytesFromFile("RSAPrivateKey.der");
          Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
          KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
          // decode public key
          X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
          RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
          System.out.println("Public Ket Spec: " + pubSpec.toString());
          System.out.println("Public Key: " + pubKey.toString());
          // decode private key
          PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
          RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
          System.out.println("Private Ket Spec: " + privSpec.toString());
          System.out.println("Private Key: " + privKey.toString());
          Cipher enc = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
          enc.init(Cipher.ENCRYPT_MODE, pubKey);
          Cipher dec = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
          dec.init(Cipher.DECRYPT_MODE, privKey);
          byte[] cyphered = new byte[] {
                  (byte) 0xA7, (byte) 0x08, (byte) 0x9A, (byte) 0xC0, (byte) 0x0A, (byte) 0x2F, (byte) 0x8D,
                  (byte) 0xA2, (byte) 0x3C, (byte) 0xC1, (byte) 0x49, (byte) 0x5B, (byte) 0x6A, (byte) 0xFF,
                  (byte) 0xF4, (byte) 0xC1, (byte) 0x9B, (byte) 0x87, (byte) 0x7C, (byte) 0xA2, (byte) 0xC5,
                  (byte) 0x6D, (byte) 0xB7, (byte) 0x84, (byte) 0xA5, (byte) 0x1A, (byte) 0xA5, (byte) 0x99,
                  (byte) 0xFF, (byte) 0x02, (byte) 0x16, (byte) 0xC4, (byte) 0x2D, (byte) 0x2E, (byte) 0x35,
                  (byte) 0xAC, (byte) 0x5B, (byte) 0x72, (byte) 0x51, (byte) 0xC1, (byte) 0xC7, (byte) 0x84,
                  (byte) 0xB5, (byte) 0x73, (byte) 0xAA, (byte) 0xB2, (byte) 0x85, (byte) 0x42, (byte) 0x7F,
                  (byte) 0xD2, (byte) 0xED, (byte) 0x0B, (byte) 0x0F, (byte) 0xD3, (byte) 0x8D, (byte) 0xFA,
                  (byte) 0xC4, (byte) 0x75, (byte) 0x16, (byte) 0x18, (byte) 0x62, (byte) 0xDC, (byte) 0xF9,
                  (byte) 0x84, (byte) 0xEF, (byte) 0x41, (byte) 0x76, (byte) 0x97, (byte) 0x63, (byte) 0x55,
                  (byte) 0x65, (byte) 0x4E, (byte) 0x7A, (byte) 0x0E, (byte) 0xC5, (byte) 0x2F, (byte) 0xC7,
                  (byte) 0xBC, (byte) 0x17, (byte) 0x83, (byte) 0x67, (byte) 0x3F, (byte) 0xD9, (byte) 0xC8,
                  (byte) 0x62, (byte) 0x3D, (byte) 0x74, (byte) 0xC6, (byte) 0x15, (byte) 0xBE, (byte) 0xA2,
                  (byte) 0xD8, (byte) 0x7C, (byte) 0x9F, (byte) 0x2A, (byte) 0x5A, (byte) 0xE5, (byte) 0xE9,
                  (byte) 0x02, (byte) 0x12, (byte) 0x6B, (byte) 0x78, (byte) 0x07, (byte) 0xB6, (byte) 0xF7,
                  (byte) 0xE3, (byte) 0x80, (byte) 0xCB, (byte) 0x20, (byte) 0xF5, (byte) 0x6D, (byte) 0xA8,
                  (byte) 0x56, (byte) 0xC6, (byte) 0xF7, (byte) 0xEB, (byte) 0xA4, (byte) 0xA4, (byte) 0xA6,
                  (byte) 0x28, (byte) 0xC2, (byte) 0x2D, (byte) 0x70, (byte) 0xAE, (byte) 0x99, (byte) 0xC8,
                  (byte) 0x6E, (byte) 0x22, (byte) 0xA0, (byte) 0x4F, (byte) 0xE8, (byte) 0x69, (byte) 0x05,
                  (byte) 0x6B, (byte) 0x63, (byte) 0xF0, (byte) 0x83, (byte) 0xD8, (byte) 0x2D, (byte) 0xA4,
                  (byte) 0xE2, (byte) 0x6A, (byte) 0x45, (byte) 0x88, (byte) 0xF6, (byte) 0xF2, (byte) 0x3B,
                  (byte) 0xF9, (byte) 0x40, (byte) 0x27, (byte) 0x53, (byte) 0x4D, (byte) 0xDB, (byte) 0x22,
                  (byte) 0x50, (byte) 0x5E, (byte) 0x30, (byte) 0xAC, (byte) 0x70, (byte) 0x53, (byte) 0x32,
                  (byte) 0x93, (byte) 0xC0, (byte) 0xF4, (byte) 0x5D, (byte) 0xDE, (byte) 0xC7, (byte) 0xCF,
                  (byte) 0xCC, (byte) 0x79, (byte) 0x1E, (byte) 0xE3, (byte) 0xBA, (byte) 0x2A, (byte) 0xB5,
                  (byte) 0xB3, (byte) 0xBB, (byte) 0x2D, (byte) 0x0A, (byte) 0x2E, (byte) 0x13, (byte) 0x56,
                  (byte) 0xDA, (byte) 0x29, (byte) 0x28, (byte) 0x9D, (byte) 0xA3, (byte) 0xB6, (byte) 0x95,
                  (byte) 0xA0, (byte) 0xFF, (byte) 0xAC, (byte) 0x19, (byte) 0x35, (byte) 0xD9, (byte) 0x5A,
                  (byte) 0xA4, (byte) 0xF6, (byte) 0x38, (byte) 0xF0, (byte) 0xBB, (byte) 0x8A, (byte) 0xC8,
                  (byte) 0x01, (byte) 0xBA, (byte) 0xDE, (byte) 0x4D, (byte) 0x4C, (byte) 0xB0, (byte) 0xBA,
                  (byte) 0x44, (byte) 0xB1, (byte) 0x60, (byte) 0xA8, (byte) 0x81, (byte) 0x94, (byte) 0x15,
                  (byte) 0x88, (byte) 0x5D, (byte) 0x92, (byte) 0x88, (byte) 0x50, (byte) 0xC7, (byte) 0x25,
                  (byte) 0xEC, (byte) 0xAB, (byte) 0x03, (byte) 0x82, (byte) 0x30, (byte) 0x13, (byte) 0xB6,
                  (byte) 0xC0, (byte) 0xC8, (byte) 0xA6, (byte) 0x8F, (byte) 0xD5, (byte) 0xB7, (byte) 0x78,
                  (byte) 0x10, (byte) 0x81, (byte) 0x5D, (byte) 0xF3, (byte) 0x7C, (byte) 0xAB, (byte) 0x5B,
                  (byte) 0xC3, (byte) 0x38, (byte) 0xA5, (byte) 0xE3, (byte) 0x8B, (byte) 0x85, (byte) 0x0B,
                  (byte) 0xC9, (byte) 0x54, (byte) 0x29, (byte) 0x79};
          System.out.println("Testing encoding: ");
          byte[] uncyph = cyphered;
          System.out.println(dec.doFinal(uncyph));
        }catch(Exception e){
          System.out.println(e.toString());
      public static byte[] getBytesFromFile(String filePath) throws IOException {
        File file = new File(filePath);
        InputStream is = new FileInputStream(file);
        long length = file.length();
        byte[] bytes = new byte[(int)length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)
            offset += numRead;
        if (offset < bytes.length)
            throw new IOException("Could not completely read file "+file.getName());
        is.close();
        return bytes;
    }

    jverd wrote:
    sabre150 wrote:
    Your ciphertext is 256 bytes so your RSA modulus needs to be 2048 bytes (256 bytes). ???
    2048 bits perhaps?:-)))) Aint this new site wonderful. I can edit my post even after someone has responded to it!

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

  • Option must start with -

    The server log has the following exception. Any ideas what the cause is?
    The server is in c:\sun but the JDK1.6 is in "C:\Program Files\Java." Is the problem to do with the space in "Program Files"? This was where the installation program defaulted to.
    [#|2007-07-29T12:37:22.344+0100|SEVERE|sun-appserver-pe9.0|javax.enterprise.tools.launcher|_ThreadID=10;_ThreadName=main;|launcher.jvmoptions_exception
    com.sun.enterprise.admin.util.InvalidJvmOptionException: Invalid Jvm Option Files/Java/jdk1.5.0_06/jre/lib/ext;C:/Sun/SDK/domains/domain1/lib/ext;C:/Sun/SDK/javadb/lib. Option must start with -.
         at com.sun.enterprise.admin.util.JvmOptionsElement.checkValidOption(JvmOptionsHelper.java:390)
         at com.sun.enterprise.admin.util.JvmOptionsElement.<init>(JvmOptionsHelper.java:277)
         at com.sun.enterprise.admin.util.JvmOptionsHelper.<init>(JvmOptionsHelper.java:66)
         at com.sun.enterprise.tools.launcher.ProcessLauncher.buildInternalCommand(ProcessLauncher.java:596)
         at com.sun.enterprise.tools.launcher.ProcessLauncher.buildCommand(ProcessLauncher.java:434)
         at com.sun.enterprise.tools.launcher.ProcessLauncher.process(ProcessLauncher.java:234)
         at com.sun.enterprise.tools.launcher.ProcessLauncher.main(ProcessLauncher.java:158)

    Solution
    Hi,
    It is what I guessed as the web page explains. The domain.xml file does not recognize any equipment name that has an acute in it. That was my case. So I have changed the name of my equipment and the problem was resolved when I installed the GlassFish again.
    Thanks for all of you about to visit my posts
    See you around,
    Oggie
    PS:
    Here I leave you the tag in the domain.xml that causes the problem,
    <jms-service addresslist-behavior="random" addresslist-iterations="3" default-jms-host="default_JMS_host" init-timeout-in-seconds="60" reconnect-attempts="3" reconnect-enabled="true" reconnect-interval-in-seconds="5" type="EMBEDDED">
            <jms-host admin-password="admin" admin-user-name="admin" host="Jose" name="default_JMS_host" port="7676"/>
          </jms-service>I hope this time you get it like me

  • How to form an Endeca query where a field must start with certain letters

    hi, Is it possible to form an Endeca query to retrieve a field that must start with certain letters? Say like get all users who's first letter is 'A' ? I checked with Range filters but it is supporting only numerical fields as well as Wild card search. But nothing worked well so far. any suggestion?

    Yes. Here's the gist of how it works:
    Typeahead is commonly implemented by enabling wildcard search on one or more Dimensions. An AJAX query is sent out containing the beginning of a search term. A controller in the app layer answers that AJAX query and formulates an Endeca Dimension Search query. It sends that off to the Endeca MDEX engine. Endeca responds with relevant Dimension matches. The controller returns these to the client who made the AJAX request. They are rendered as hyperlinks that lead to a particular navigation state in the catalog.

  • Can Check Number be start with zero?

    Dear all,
                   I knew that check number on SBO is numeric but check number of my country some number can start with zero and it effected to check number printing form. So, I'm not sure whether we can set check number to be charactor or not. Or how to apply for this issue, pls. suggest.
    Thanks you very much.
    Angnam

    Hi,
    It is not possible to set check number as alphanumeric, you can use remarks field to enter check number or any other filed that you think is not required and can be used as check number.
    it is not possible to add UDF in checks for payment . if you are using payment method checks tab, you can use UDF.
    Thanks,
    Neetu

  • Control record must start with tag EDI_DC40, not E1LFA1M

    Hi,
    I am trying sxample <b>FILE>XI>IDOC ADAPTER-->R/3</b>
    I am getting error as
      <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    - <!--  Call Adapter
      -->
    - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="">
      <SAP:Category>XIAdapter</SAP:Category>
      <SAP:Code area="IDOC_ADAPTER">ATTRIBUTE_IDOC_RUNTIME</SAP:Code>
      <SAP:P1>MSGGUID F95236609A0C11D98F65000D56714443: Control record must start with tag EDI_DC40, not E1LFA1M</SAP:P1>
      <SAP:P2 />
      <SAP:P3 />
      <SAP:P4 />
      <SAP:AdditionalText />
      <SAP:ApplicationFaultMessage namespace="" />
      <SAP:Stack>Error: MSGGUID F95236609A0C11D98F65000D56714443: Control record must start with tag EDI_DC40, not E1LFA1M</SAP:Stack>
      <SAP:Retry>M</SAP:Retry>
      </SAP:Error>
    Do i have to apply the note saying Apply the Support pack SP 11(Note No)  792957.
    Currently I have XI 3.0 SR1.
    Or can i try the similar example with some other IDOC.
    Please Help me in this.
    Thanks a lot
    Deepti

    Hi Deepti,
    I have got the same problem but after rescheduling the message its fine on the XI end. But at the R/3 End the status is still red with status number 56 (IDoc with errors added)Idoc used is CREMAS03. what might be the possible errors.
    Please help me.
    Regards,
    Gopesh Kumar Agarwal

  • Javax.crypto.BadPaddingException in DES encrypt/decrypt algorithm

    I am using DES algorithm, the default provided by J2ME to encrypt and decrypt some text. My problem is that I can encrypt the text but when I decrypt I get javax.crypto.BadPaddingException. I used a sample code from this forum I suppose and modified it to some extend.
    Here's the output -
    Plain Text :debayandas
    Cipher Text :Ɩ2&#65533;Ü°*Yð´4}&#65533;f¥
    Recovered Plain Text :javax.crypto.BadPaddingExceptionAnd here's the J2ME code -
    Declaration part:
    private boolean midletPaused = false;
            private static String algorithm = "DES";
         private static byte[] secretKey = {(byte) 0x2b, (byte) 0x7e, (byte) 0x15, (byte) 0x16,
                                                      (byte) 0x28, (byte) 0xae, (byte) 0xd2, (byte) 0xa6 };
         private static String secretKeyAlgorithm = "DES";
         private static byte[] iv = "DES".getBytes();
         private static byte[] plainText = null;
         private Key key = null;
         private static Cipher cipher = null;
         private static int ciphertextLength = 512;
            private static byte[] cipherText = new byte[ciphertextLength];
            private static int decryptedtextLength = 1024;
            private static byte[] decryptedText = new byte[decryptedtextLength];commandAction:
    public void commandAction(Command command, Displayable displayable) {                                              
            if (displayable == form) {                                          
                if (command == exitCommand) {                                        
                    exitMIDlet();                                          
                } else if (command == okCommand) {
                    plainText=textField.getString().getBytes();
                    encrypt();
                    decrypt();                                                        
        } Encrypt:
    public void encrypt()
                try
                    key = new SecretKeySpec(secretKey,0,secretKey.length,secretKeyAlgorithm);
              cipher = Cipher.getInstance(algorithm);
                    cipher.init(Cipher.ENCRYPT_MODE, key);
                    cipher.doFinal(plainText, 0, plainText.length, cipherText, 0);
              System.out.println("Plain Text :"+new String(plainText));
              System.out.println("Cipher Text :"+new String(cipherText));
                catch(Exception e)
                    System.out.println(""+e);
        }Decrypt:
    public void decrypt()
            try
    //            cipher = Cipher.getInstance(algorithm);
                cipher.init(Cipher.DECRYPT_MODE,key);
                cipher.doFinal(cipherText,0,cipherText.length,decryptedText,0);
                System.out.println("Recovered Plain Text :"+new String(decryptedText));
            catch(Exception e)
                System.out.println(""+e);
        }Where am I going wrong?

    debayandas wrote:
    I am using DES algorithm, the default provided by J2ME to encrypt and decrypt some text. My problem is that I can encrypt the text but when I decrypt I get javax.crypto.BadPaddingException. I used a sample code from this forum I suppose and modified it to some extend.How did you get DES in J2ME?
    I am asking as there isn't one default implementation in J2ME and as far as I am aware it is not included in any Configurations or Profiles of J2ME.
    You might be using [Bouncycastle library|http://www.bouncycastle.org/java.html] or any other third party implementation of DES, in which case please refer to the documentation of it to see in which methods throw BadPaddingException and in what circumstances, in order to pinpoint the problem.
    Daniel

Maybe you are looking for

  • How can I catch a error in a BAPI?

    Hi, I use BAPI L_TO_CREATE_MULTIPLE. If, for example, I put a warehouse that not is the warehouse of the unit that I want to move, I receive an error that isn't in exceptions. In the program, I need, in the sy-subrc, catch this error, to do anything.

  • How to run performance trace on a program

    Hi All,       I need to run pefromance trace on a program that I will run in background. I think I have to use ST05 to run SQL trace. Could someone please confirm the steps? 1) Go to ST05 2) Activate trace with filter 3) Run the program in background

  • Picking UTF-16 coded xml file thru file adapter

    Dear All, We are working on an interface in which we are receiving an XML file in UTF-16 format. Now we want to send this file to a RFC in SAP. We are getting an error in picking the file as UTF-16 file format is not getting picked. Also we are not a

  • How do I open JPEG document Adobe?

    I have tried many times to open JPEG documents and always get a message stating Adobe does not work with this kind of document. Is there something I am missing?

  • GPS apps take me to a place I've never been

    When I've got crappy accuracy (most of the time) any GPS based app will take me to a place about 5 miles from my house that I've never been to in my life. Ever. It's the same place and every GPS app shows me in this spot. Some of the apps that have e