[英]Android AES/CBC/PKCS5Padding encryption
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)
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. 这是您的做法,而且是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.