1

我正在使用 Bouncycastle 对文件进行 AES 256 位加密,然后将其上传到后端。

我的应用程序可以在 Android 4.0 设备上完美运行。当我在 Android 4.3 设备上测试同一个应用程序时,首先它在进行加密时崩溃并显示 OutofMemory 异常。所以我添加了try catch异常。

它完成了加密,但是当解密文件显示乱码时发送到后端的后续文件。

不确定这是怎么可能的,因为它是使用相同键的同一个应用程序。

知道如何解决这个问题吗?难道我做错了什么?下面是我的加密代码:

public void encryptfile(String encpathname , String destencfile){

        try {

            byte enc[] = null;

            File file = new File(encpathname);
            byte[] data = new byte[(int) file.length()];

            FileInputStream fis;

                fis = new FileInputStream(file);
                fis.read(data);
                fis.close();

                enc = encrypt(passphrase, data);

                FileOutputStream stream = new FileOutputStream(destencfile);
                stream.write(enc);
                stream.close();

                file.delete();

                System.gc();

                }catch (Exception e) {

                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }

private static byte [] encrypt(String passphrase, byte [] inbytes) throws Exception {
                SecretKey key = generateKey(passphrase);

                Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
               // Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

                cipher.init(Cipher.ENCRYPT_MODE, key, generateIV(cipher), random);
                return cipher.doFinal(inbytes);
            }

            private static SecretKey generateKey(String passphrase) throws Exception {
                PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength);
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWITHSHA256AND256BITAES-CBC-BC");
                return keyFactory.generateSecret(keySpec);
            }

            private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
                byte [] ivBytes = new byte[cipher.getBlockSize()];
                random.nextBytes(ivBytes);
                return new IvParameterSpec(ivBytes);
            }
4

0 回答 0