我使用AES加密了.txt文件,tha文件包含整数,现在我试图将其解密为下面的代码:
try {
FileOutputStream outStream;
CipherOutputStream cos;
try (FileInputStream file = new FileInputStream(pOld.toString())) {
outStream = new FileOutputStream(pNew.toString());
byte k[]= Key.getBytes();
SecretKeySpec KEYY=new SecretKeySpec(k, EncAlgo);
Cipher enc = Cipher.getInstance(EncAlgo);
enc.init(Cipher.DECRYPT_MODE, KEYY);
cos = new CipherOutputStream(outStream,enc);
byte [] buffer = new byte[1024];
int read;
while((read=file.read(buffer))!=-1)
{
cos.write(buffer, 0, read);
}
}
outStream.flush();
cos.close();
JOptionPane.showMessageDialog(null, "The Message Was Decrypted Successfully");
}
catch(HeadlessException | IOException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {
JOptionPane.showMessageDialog(null, "Decryption Failed");
}
但解密的.txt结果文件总是空的! 任何想法为什么会发生? 它告诉我解密成功了,但file.txt是空的!
因此: POld,PNew => Paths.txt ///// AncAlgo =" AES" 我试过解密.txt和.jpg文件,两者都是空的, 这里是特定AES的加密代码,两者都具有相同的密钥::
public static void EncryptFile(Path POld, String key, Path PNew)
{
try {
File FileOld = new File(POld.toString());
FileInputStream file = new FileInputStream(FileOld);
FileOutputStream outStream = new FileOutputStream(FileOld);
byte k[]= key.getBytes();
SecretKeySpec KEYY=new SecretKeySpec(k, "AES");
Cipher enc = Cipher.getInstance("AES");
enc.init(Cipher.ENCRYPT_MODE, KEYY);
CipherOutputStream cos = new CipherOutputStream(outStream,enc);
byte[] buffer = new byte[1024];
int read;
while((read=file.read(buffer))!=-1){
cos.write(buffer, 0, read);
}
file.close();
outStream.flush();
cos.close();
JOptionPane.showMessageDialog(null, "Encrypted!");
}
catch(FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File Not Found!");
}
catch (IOException e){
JOptionPane.showMessageDialog(null, "IO Exception!");
}
catch (NoSuchPaddingException e){
JOptionPane.showMessageDialog(null, "No such padding!");
}
catch (NoSuchAlgorithmException e){
JOptionPane.showMessageDialog(null, "No Such Algorithm!");
}
catch (InvalidKeyException e){
JOptionPane.showMessageDialog(null, "Invalid Key!");
}
}
答案 0 :(得分:0)
您在加密代码中使用新的输出文件覆盖输入文件。您正在生成零长度文件。您需要生成一个新文件。