java 密钥 aes 解密,Java AES解密检测不正确的密钥

作者分享了在开发Android应用中遇到的问题,即如何在使用CipherInputStream解密文件时检测到不正确的密码导致的坏Padding。他们提供了一个修改后的getMoreData方法,以在遇到问题时抛出异常。讨论了在处理AES/CBC/PKCS7Padding时确保解密安全性的策略。
摘要由CSDN通过智能技术生成

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值