Java AES解密检测不正确的密钥 [英] Java AES decryption detect incorrect key
问题描述
我正在使用256位密钥的AES / CBC / PKCS7Padding。
如果我做cipher.doFinal()我可以尝试/捕获BadPaddingException,它告诉我有问题,可能键是不正确的。但是如果我使用CipherInputStream来读取加密文件,我没有得到关于填充正确性的反馈。所以如果我故意指定不正确的密码解密文件,那么报告一切都可以,但解密的文件是一个完整的垃圾。
所以我的问题是如何使用CipherInputStream检测不良填充?
这是getMoreData()的修改版本方法在CipherInputStream中,对于面对我的问题的人来说,这可能是有用的:
private int getMoreData()throws IOException {
if(done)return -1;
int readin = input.read(ibuffer);
if(readin == -1){
done = true;
try {
obuffer = cipher.doFinal();
}
catch(IllegalBlockSizeException e){
throw new IOException(e);
}
catch(BadPaddingException e){
throw new IOException(e);
}
if(obuffer == null)
return -1;
else {
ostart = 0;
ofinish = obuffer.length;
returninin;
}
}
try {
obuffer = cipher.update(ibuffer,0,readin);
} catch(IllegalStateException e){obuffer = null;};
ostart = 0;
if(obuffer == null)
ofinish = 0;
else ofinish = obuffer.length;
returninin;
}
I am writing android app that makes AES encryption/decryption of files. I want to be able to detect if incorrect password is specified and thus not matching key is derived for decryption. I am using AES/CBC/PKCS7Padding with 256 bit key. If I do cipher.doFinal() I can try/catch the BadPaddingException and it tells me that something is wrong and probably key was incorrect. But if I use CipherInputStream to read encrypted file, I get no feedback on correctness of padding. So if I deliberately specify incorrect password it decrypts file, then reports that everything is ok, however decrypted file is a total junk. So my question is how to detect bad padding when using CipherInputStream?
Here is modified version of getMoreData() method in CipherInputStream, it maybe useful for someone who faced my problem:
private int getMoreData() throws IOException {
if (done) return -1;
int readin = input.read(ibuffer);
if (readin == -1) {
done = true;
try {
obuffer = cipher.doFinal();
}
catch (IllegalBlockSizeException e) {
throw new IOException(e);
}
catch (BadPaddingException e) {
throw new IOException(e);
}
if (obuffer == null)
return -1;
else {
ostart = 0;
ofinish = obuffer.length;
return ofinish;
}
}
try {
obuffer = cipher.update(ibuffer, 0, readin);
} catch (IllegalStateException e) {obuffer = null;};
ostart = 0;
if (obuffer == null)
ofinish = 0;
else ofinish = obuffer.length;
return ofinish;
}
这篇关于Java AES解密检测不正确的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!