在我的编码课程中有一个项目,我无法弄清楚这一个。文件的加密很好,加密就好了,但每当我得到解码时,我都会收到这个错误:线程中的异常" main" javax.crypto.BadPaddingException:给定最终块未正确填充。我不知道为什么会这样,所以这就是我在这里的原因。这是代码:
package Test;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
public class FileDecryptor
{
private static String filename;
private static String password;
private static FileInputStream inFile;
private static FileOutputStream outFile;
public static void main(String[] args) throws Exception
{
// File to decrypt.
filename = "Test.txt.des";
String password = "super_secret_password";
inFile = new FileInputStream(filename);
outFile = new FileOutputStream(filename + ".dcr");
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey passwordKey = keyFactory.generateSecret(keySpec);
byte[] salt = new byte[8];
inFile.read(salt);
int iterations = 100;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);
outFile.write(salt);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inFile.read(input)) != -1)
{
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
outFile.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
outFile.write(output);
inFile.close();
outFile.flush();
outFile.close();
}
}