Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:从加密文件解密时出现错误的填充_Java_Arrays_Encryption_Cryptography - Fatal编程技术网

Java:从加密文件解密时出现错误的填充

Java:从加密文件解密时出现错误的填充,java,arrays,encryption,cryptography,Java,Arrays,Encryption,Cryptography,我正在构建一个文件加密实用程序,以下是我的加密代码: Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES"); cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.ge

我正在构建一个文件加密实用程序,以下是我的加密代码:

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
    for(int i = 0; i < input.size(); i++){
        plainText = input.get(i);
        byte[] b = cipher.doFinal(plainText.getBytes("UTF-8"));
        String outString = new String(b);
        //to be written to file
以及解密函数:

public static String decrypt(byte[] cipherText) throws Exception{
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
    return new String(cipher.doFinal(cipherText),"UTF-8");
  }

加密密钥等都是相同的。

Java library Reader和Writer类设计用于处理面向行的未加密文本。但是,文本一旦加密,就不再是文本,因此将其视为文本可能会导致问题


您应该改为使用InputStream和OutputStream类来处理原始数据,而不是读写器类来访问文件。编辑:特别是,可以使用CipherInputStream和CipherOutputStream,这样就不必直接调用密码方法。您还可以在CipherInputStream上构造InputStreamReader,在CipherOutputStream上构造OutputStreamWriter,只需使用read()和write()方法,让流负责加密。

String outString=new String(b)将不起作用。如果必须将密码视为字符串,则必须对其进行编码。您可以使用标准Java中的和方法在base64字符串之间进行转换。如果你在Android上,你可以使用这个类


另外,至少可以说,您的加密机的使用有点可疑。通过将每个输入作为单独的纯文本序列处理,每次都会重复使用IV。通常,如果要使用该方法加密每个输入片段,请在完成后使用
doFinal(…)

谢谢,我试试这个。我可以继续正常加密并使用数据流读取加密文件吗?@user3289385无论何时对密文执行
新建字符串(…)
,您都将加密数据视为文本。@user3289385如果要继续直接加密,请参阅下面的GregS注释。或者,使用CipherOutputStream和CipherInputStream可能更容易。我已经编辑了我的答案,加入了关于这个问题的讨论。
public static String decrypt(byte[] cipherText) throws Exception{
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
    return new String(cipher.doFinal(cipherText),"UTF-8");
  }