无法在安卓棒棒糖版本解密加密文件

5

我在我的应用中有一个针对下载文件的加密/解密机制。

这个机制可以在所有安卓设备和Android 5.0-lollipop之前的版本上运行。

以下是解密的过程:

cipher.init(Cipher.DECRYPT_MODE, key);
fileInputStream = new FileInputStream(file);
cipherInputStream = new CipherInputStream(fileInputStream, cipher);
byte[] fileByte = new byte[(int) file.length()];
int j = cipherInputStream.read(fileByte);
return fileByte;

密钥和密码已经在整个应用程序中生成并使用:
 key = new SecretKeySpec(keyValue, "AES");
 try {
     cipher = Cipher.getInstance("AES");
 } catch (Exception e) {
     e.printStackTrace();
 }

当我在安卓5.0上解密一个文件,文件大小约为200,000字节时,变量j(在返回之前)只有大约8000,远低于200,000,在旧的安卓版本中它恰好等于解密文件长度。

我发现问题出在解密上。因为我可以在安卓5.0上加密一个文件并在旧的安卓版本中解密它,但反过来就不行。但是我会发布加密过程:

cipher.init(Cipher.ENCRYPT_MODE, AESutil.key);
cipherOutputStream = new CipherOutputStream(output, cipher);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
    cipherOutputStream.write(data, 0, count);
}

预先感谢您


你的流处理对我来说似乎相当奇怪。创建与文件大小相同的缓冲区并不意味着所有这些字节都被实际读取。而且在加密期间,你似乎没有显式关闭流(但也许这只是没有包括在内)。 - Maarten Bodewes
@MaartenBodewes-owlstead 是的,我已经关闭它们了。问题仍然存在。 - Misagh Emamverdi
你能否确保读取正确数量的字节,通过读取字节直到 j-1 - Maarten Bodewes
通常问题不在于解密,而在于密钥生成。因此我强烈建议在加密/解密之前比较使用的密钥。 - Robert
@MaartenBodewes-owlstead。我按照您的建议更改了代码,问题得到了解决。非常感谢。 - Misagh Emamverdi
1个回答

2

我的密码示例(L):

APPPATH是我应用程序在SD卡上的目录字符串。

static void encrypt(File file, String pass) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {


        FileInputStream fis = new FileInputStream(file);


        FileOutputStream fos = new FileOutputStream(APPPATH+"/E_"+file.getName());


        SecretKeySpec sks = new SecretKeySpec(pass.getBytes(), "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, sks);

        CipherOutputStream cos = new CipherOutputStream(fos, cipher);

        int b;
        byte[] d = new byte[8];
        while((b = fis.read(d)) != -1) {
            cos.write(d, 0, b);
        }

        cos.flush();
        cos.close();
        fis.close();


    }



     static void decrypt(File file, String pass) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

            FileInputStream fis = new FileInputStream(file);

            FileOutputStream fos = new FileOutputStream(APPPATH+"/D_"+file.getName());
            SecretKeySpec sks = new SecretKeySpec(pass.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, sks);
            CipherInputStream cis = new CipherInputStream(fis, cipher);
            int b;
            byte[] d = new byte[8];
            while((b = cis.read(d)) != -1) {
                fos.write(d, 0, b);
            }
            fos.flush();
            fos.close();
            cis.close();
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接