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.

Similar Messages

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

  • 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

  • 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

  • Javax.crypto.BadPaddingException

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

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

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

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

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

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

  • 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

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

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

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

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

    Well from what I read about this issue, seems the biggest issue is using the wrong keys. Well since this data exchange has been in production for 3+ years, I pretty certain its not the keys. To verify this i did:
    1) From a server running JDK 1.2 and ran this process successfully, so I copied the keystore from this server to the server I was running 1.4 and reran the same data through. I still got the exception.
    2) From another post I read about the difference in keys between older versions of Java and 1.4, so modifying the code listed and then exported my private key while running under 1.2 and created a new 1.4 keystore and imported this key & certificate. I'm still getting the exception.
    Any ideas would be great.
    Thanks

  • Issue with javax.crypto.SecretFactory

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

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

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

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

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

Maybe you are looking for

  • I'm trying to reset my iPhone 5 but no longer have the email address iTunes is connected to

    IM trying to reset my ipone 5. But my email address is no longer active so cant get my pass word back is there any other way I can reset my phone to factory settings .

  • HP LAser Jet Pro MFP M127fw not Receiving Auto FAX

    I Own two HP All-in-Ones.  First is an Officejet 7500A and second is an HP LaserJet Pro MFP M127fw. I hooked my Phone line to the 7500 and was able to send and receive FAX's, but no matter what I did (Including setting it to Automatically Receive FAX

  • Safari 6.0.5 unexpectedly quits

    Running 10.8.4 on my MacBook Pro and in recent days, Safari 6.0.5 unexpectedly quits. Not while I am working in it, but when the window is closed and the app is just running in the background. I get no alert that is has crashed, it just quits. I pull

  • Nokia E5 camera problems.

    Hi, I am a proud owner of Nokia E5-00 andI have a few queries regarding the camera features. 1.How to turn off the camera sound? 2.When I take a pic with flash ON, a cloudy-hazy-whitish image is taken. Solution? Thanks in advance. Anupam Roy

  • Safari Problems with websites w/video clips

    Hello, this is my first MAC so please don't flame me. When going to sites that play video/audio clips I'm getting "plugin not found" but there's no link where to get the plugin (reminds me of the netscape days). Specific Error: has content of MIME ty