Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Could anybody help me to solve a Decryption problem in java, i have to encrypt data and to save in db (SQL SERVER 2005 nvarchar type), if i encrypt and try to decrypt (Before storing to db) everything is OK but after i have stored them in db i can not decrypt them. i got the following message
javax.crypto.BadPaddingException: Given final block not properly padded

i use the following code (got on internet), i tried to use other algorithms to decrypt(with base64 ) but no success.
THANX A LOT
Java
import java.io.IOException;
    import javax.crypto.Cipher;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import java.security.Key;
    import java.security.InvalidKeyException;


public class EncriptAndDecript {

    private static String algorithm = "DESede";
    private static Key key = null;
    private static Cipher cipher = null;
    private static EncriptAndDecript obj = new EncriptAndDecript();

    public EncriptAndDecript() {
    try {
    key = KeyGenerator.getInstance(algorithm).generateKey();
    cipher = Cipher.getInstance(algorithm);
    } catch (Exception e) {
    }
    }

    public static EncriptAndDecript getInstance() {
    return obj;
    }

    public static byte[] encrypt(String input)
    throws InvalidKeyException,
    BadPaddingException,
    IllegalBlockSizeException {
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] inputBytes = input.getBytes();
    return cipher.doFinal(inputBytes);
    }

    public  String getEncryptStringValue(String input)
    {
        String vali = "";
        try{
                 vali= new String(encrypt(input));
         }
         catch(Exception e){vali= "";}
        return vali;
    }
   public String getDecryptStringValue(String input) throws IOException
    {
                 String vali ="";
            byte[] a = input.getBytes();
        //byte[] a = new BASE64Decoder().decodeBuffer(input);
        try{
                 vali= new String(decrypt(a));
         }
         catch(Exception e){vali= e.toString();}
        return vali;
    }


    public static String decrypt(byte[] encryptionBytes)
    throws InvalidKeyException,
    BadPaddingException,
    IllegalBlockSizeException {
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] recoveredBytes =
        cipher.doFinal(encryptionBytes);
        String recovered = new String(recoveredBytes);
        return recovered;
    }
      
  Cipher ecipher;
    Cipher dcipher;


    }
Posted
Updated 9-Jun-11 4:53am
v2

I would humbly suggest you are not getting the full stream for decription. Why is your encrypted stream a string? I think when you take the output from encrypt - byte[] which is correct - and convert it to a string you're loosing something.

Plus there is a nasty mixture of class and member variables / members. I don't think you should really be using any class variables or methods; i.e. static.
 
Share this answer
 
Comments
dajask 10-Jun-11 3:00am    
while i can decrypt before storing data in db, i don't think that i'm losing something converting byte[] to string. if something is lost i couldn't decrypt it before storing in db! (So think i do)
Nagy Vilmos 10-Jun-11 3:40am    
Check the encrypted data you write to the db and compare it to the data you read. It could be because you are using an nvarchar datatype. It might be better to use a binary or a blob if it is likely to be over 8,0000 bytes.
Gerben Jongerius 10-Jun-11 7:38am    
Nagy Vilmos is right. The conversion from byte[] to String could cause you to loose data, or could cause space padding to the end. Especially when Java also starts converting from UTF8 to ISO-8895-1. This last might occur pending on the database driver settings. I've had this exact issue in the past with encryption and decryption.

You are best of storing the byte[] in a blob data field preventing any conversion.
This can be a pain in the *ss, you never know why it's not working.
Try this one - it works in a couple of my solutions (incuding storage on SQL Servers):

package de.security;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public final class DeEncrypter {
	private static DeEncrypter instance = new DeEncrypter(); 
	
	private Cipher cipher;
	private Key key;
//	private final BASE64Encoder b64Encoder = new BASE64Encoder();
//	private final Base64 b64Decoder = Base64.;
	
	public static DeEncrypter getInstance() {
		
		return DeEncrypter.instance;
	}	
	
	private DeEncrypter() {
		
		try {
			this.cipher = Cipher.getInstance("AES");
			byte[] raw = { (byte) 0xA5, (byte) 0x01, (byte) 0x7B, (byte) 0xE5,
					(byte) 0x23, (byte) 0xCA, (byte) 0xD4, (byte) 0xD2,
					(byte) 0xC6, (byte) 0x5F, (byte) 0x7D, (byte) 0x8B,
					(byte) 0x0B, (byte) 0x9A, (byte) 0x3C, (byte) 0xF1 };
			this.key = new SecretKeySpec(raw, "AES");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
	}
	
	public String encrypt(String aData) {
		String result = "";
		try {
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] utf8 = aData.getBytes("UTF8");
			byte[] encryptedData = cipher.doFinal(utf8);
			result = Base64.encode(encryptedData);//this.b64Encoder.encode(encryptedData);
		} 
		catch (InvalidKeyException oException) { 			oException.printStackTrace(); } 
		catch (IllegalBlockSizeException oException) { 		oException.printStackTrace(); } 
		catch (BadPaddingException oException) { 			oException.printStackTrace(); } 
		catch (IOException oException) { 					oException.printStackTrace(); }
		return result;
	}
	public String decrypt(String aData) {
		String result = "";
			try {
				cipher.init(Cipher.DECRYPT_MODE, key);
				byte[] decodedData = Base64.decode(aData);//this.b64Decoder.decodeBuffer(aData);
				byte[] utf8 = cipher.doFinal(decodedData);
				result = new String(utf8, "UTF8");
			} 
			catch (InvalidKeyException oException) { 			oException.printStackTrace(); } 
			catch (Base64DecodingException oException) { 		oException.printStackTrace(); } 
			catch (IllegalBlockSizeException oException) { 		oException.printStackTrace(); } 
			catch (BadPaddingException oException) { 			oException.printStackTrace(); } 
			catch (UnsupportedEncodingException oException) { 	oException.printStackTrace(); }
		return result;
	}
}


the call is
DeEncrypter.getInstance().encrypt(someStringValue);


regards
Torsten
 
Share this answer
 
Comments
dajask 10-Jun-11 7:43am    
Really it works, thanks a lot.
regards
Valdet Zabeli

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900