java - 使用 aes/ecb/pkcs5padding 解密字节数组时出现 IllegalBlockSizeException

标签 java android encryption gradle aes

我知道aes加密需要以16为单位,但我的印象是使用Cipher.getInstance("AES/ECB/PKCS5PADDING");填充字节数组来实现这。我的代码如下:

CipherUtils.java

private static byte[] key = {
        0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x41, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x4b, 0x65, 0x79
};//"thisIsASecretKey";

public static byte[] EncryptByteArray(byte[] array)
{
    try
    {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        return (cipher.doFinal(array));
    }
    catch (Exception e)
    {
      e.printStackTrace();

    }
    return null;
}

public static byte[] DecryptByteArray(byte[] array)
{
    try
    {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        return cipher.doFinal(array);
    }
    catch (Exception e)
    {
      e.printStackTrace();

    }
    return null;
}

主程序

        fis = new FileInputStream(path);

        toDecrypt = new byte[fis.available()+1];

        int content;
        int i = 0;
        while ((content = fis.read()) != -1) {

            // convert to byte and display it
            toDecrypt[i] = (byte)content;
            i += 1;
        }

        byte[] decryptedStr = CipherUtils.DecryptByteArray(toDecrypt);

        FileOutputStream decryptedStream = new FileOutputStream(path);
        decryptedStream.write (decryptedStr);
        decryptedStream.close();

path 处的文件使用 cipherutils.java 中的函数加密,并使用 FileOutputStream.write 写入文件

更新 - 我正在使用 Gradle 为 Android 构建。

最佳答案

问题是:

toDecrypt = new byte[fis.available()+1];

首先,您正在使用 available() 方法,这绝不是一个好主意。接下来,即使假设它正在 返回文件的长度,您也要向它加 1 - 为什么?当然,您只需要文件中的字节。

最简单的方法就是使用 Files.readAllBytes :

byte[] toDecrypt = Files.readAllBytes(Paths.get(path));
// TODO: Change the method name to follow Java conventions
byte[] decrypted = CipherUtils.DecryptByteArray(toDecrypt);
Files.write(Paths.get(path), decrypted);

现在您也不必担心关闭文件流...(如果您设法解密,您可能无法写入,因为您仍然打开文件阅读你当前的代码。)

我还强烈建议重新审视您的异常“处理”:

  • 捕获异常几乎总是一个坏主意
  • 调用 e.printStackTrace() 然后继续好像什么都没发生几乎总是一个坏主意

关于java - 使用 aes/ecb/pkcs5padding 解密字节数组时出现 IllegalBlockSizeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897347/

相关文章:

java - 如何检查均匀分布的元素的最大数量?

java - Java中从src/main/resources访问静态文件

java - 是否可以在 tomcat 中的过滤器的 doFilter 函数中恢复 Referrer?

android - 如何实现 ContentObserver?

Android,当我在设备上安装我的应用程序时图标重复

Android android.credentials.UNLOCK 在没有密码的情况下初始化 keystore

linux - 我可以使用 openJDK 而不是 Oracle JDK 安装 RubyMine 5 吗?

java - Web3j ECKeyPair 到 KeyPair

security - 如何通过 OAuth2 身份验证保护私有(private)数据?

android - 在 C 代码中访问 Android 属性