I read on this link AES Encryption/Decryption with Bouncycastle Example in J2ME about how to encrypt a string using AES as supplied by Bouncy Castle. The encryption method code works fine but decryption doesn't work.
Can anyone suggest how I can decrypt the encrypted string?
I've used the following code to test:
import com.codename1.util.Base64;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
/**
*
* @author SAMUEL
*/
public class Tester {
static String strEnc = "Hi This is my String";
final static String strPassword = "password12345678";
private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)throws Exception
{
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
private static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) throws Exception
{
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(false, ivAndKey);
return cipherData(aes, cipher);
}
private static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception
{
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(true, ivAndKey);
return cipherData(aes, plain);
}
public static void main(String [] args) throws Exception{
byte[] enc= encrypt(strEnc.getBytes(),"password12345678".getBytes(), "password12345678".getBytes());
String encrypted = Base64.encode(enc);
System.out.println("Encrypted is:"+encrypted);
byte[] dec= decrypt(encrypted.getBytes(),"password12345678".getBytes() , "password12345678".getBytes());
System.out.println("Decrypted file is:"+dec);
}
}
Output is:
Encrypted is:sw0SrUIKe0DmS7sRd9+XMgtYg+BUiAfiOsdMw/Lo2RA=
And the exception stacktrace is:
Exception in thread "main" org.bouncycastle.crypto.DataLengthException: last block incomplete in decryption
at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(PaddedBufferedBlockCipher.java:281)
at com.mycompany.myapp.Tester.cipherData(Tester.java:28)
at com.mycompany.myapp.Tester.decrypt(Tester.java:40)
at com.mycompany.myapp.Tester.main(Tester.java:57)