Reputation: 6091
I'm reading a database that has encrypted data. I can read an decrypt the contents but I can't decrypt something that I encrypt. The result are different:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
SecretKey skey = new SecretKeySpec(key, 0, key.length, "AES");
Here is how I decrypt the string:
public byte[] decrypt(byte[] data) {
byte[] result = new byte[0];
try {
cipher.init(DECRYPT_MODE, skey, new IvParameterSpec(iv));
InflaterInputStream inflaterStream = new InflaterInputStream(
new CipherInputStream(new ByteArrayInputStream(data), cipher));
return IOUtils.toByteArray(inflaterStream);
} catch (Exception e) {
e.printStackTrace();
return result;
}
}
And here is how I encrypt the string:
public byte[] encrypt(byte[] data) {
try {
cipher.init(ENCRYPT_MODE, skey, new IvParameterSpec(iv));
DeflaterInputStream deflaterInput = new DeflaterInputStream(
new CipherInputStream(new ByteArrayInputStream(data), cipher));
return IOUtils.toByteArray(deflaterInput);
} catch (Exception e) {
e.printStackTrace();
return new byte[0];
}
}
The error that I get is this:
W/System.err: java.util.zip.ZipException: incorrect header check
W/System.err: at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:170)
W/System.err: at java.io.FilterInputStream.read(FilterInputStream.java:107)
W/System.err: at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2146)
W/System.err: at org.apache.commons.io.IOUtils.copy(IOUtils.java:2102)
W/System.err: at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2123)
W/System.err: at org.apache.commons.io.IOUtils.copy(IOUtils.java:2078)
W/System.err: at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:721)
Upvotes: 0
Views: 2694
Reputation: 42009
Your nesting of streams on encryption is not correct. On encryption it should be
new CipherInputStream(new DeflaterInputStream(new ByteArrayInputStream(data)), cipher);
On decryption it should be
new InflaterInputStream(new CipherInputStream(new ByteArrayInputStream(data), cipher));
which is how you had it and is correct.
Upvotes: 3