Java AES解密检测不正确的密钥 [英] Java AES decryption detect incorrect key

查看:871
本文介绍了Java AES解密检测不正确的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写Android应用程序,使AES加密/解密文件。我想能够检测到是否指定了错误的密码,因此导出解密不匹配的密钥。
我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆