gpt4 book ai didi

java - Java中的文件加密和解密,不起作用解密

转载 作者:行者123 更新时间:2023-12-02 02:50:46 24 4
gpt4 key购买 nike

大家好,我必须这样做,我可以根据 des 算法加密文件,但我无法再次解密文件,我收到这样的错误消息:

javax.crypto.BadPaddingException 给定的最终 block 未正确填充

我无法解密文件,我找不到原因。你能帮我吗感谢你们。

JAVA代码:

public class Sifreleme {

public static void encrypt(){
try {
SecretKey key = KeyGenerator.getInstance("DES").generateKey();

FileOutputStream fosKey = new FileOutputStream("..\\KEY");
SecretKeyFactory keyfac = SecretKeyFactory.getInstance("DES");
DESKeySpec keyspec = (DESKeySpec) keyfac.getKeySpec(key, DESKeySpec.class);
fosKey.write(keyspec.getKey());
fosKey.close();

Cipher crypt = Cipher.getInstance("DES");
crypt.init(Cipher.ENCRYPT_MODE, key);

FileInputStream fis = new FileInputStream("C:\\Users\\akif\\Desktop\\zilsesi.mp3");
FileOutputStream fos = new FileOutputStream("C:\\Users\\akif\\Desktop\\sifrelenenzilsesi.mp3");
byte[] arrayBytes = new byte[8];
int bytesReads;
while ((bytesReads = fis.read(arrayBytes)) != -1) {
fos.write(crypt.doFinal(arrayBytes), 0, bytesReads);
}
fis.close();
fos.close();

} catch (Exception e) {
e.printStackTrace();
}
}




public static void decrypt(){
try {
FileInputStream fisKey = new FileInputStream("..\\KEY");
byte[] arrayKey = new byte[fisKey.available()];
fisKey.read(arrayKey);
SecretKey key = new SecretKeySpec(arrayKey, "DES");

Cipher decrypt = Cipher.getInstance("DES");
decrypt.init(Cipher.DECRYPT_MODE, key);

FileInputStream fis = new FileInputStream("C:\\Users\\akif\\Desktop\\sifrelenenzilsesi.mp3");
byte[] encText = new byte[16];
int bytesReads;
while ((bytesReads = fis.read(encText)) != -1) {
fis.read(decrypt.doFinal(encText), 0, bytesReads);
}
fis.close();
System.out.println(new String(encText));

} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String []args) throws IOException{
encrypt();
decrypt();
}

最佳答案

您的代码在这里:

    while ((bytesReads = fis.read(encText)) != -1) {
fis.read(decrypt.doFinal(encText), 0, bytesReads);
}

显然是错误的:您需要编写通过调用 decrypt.doFinal 生成的明文,就像加密期间一样。目前,您正在用下一个密文 block 覆盖生成的明文,因为您在循环中调用了两次read

此外,根据您的 DES Cipher 实现,您忘记了 IV。

<小时/>

许多其他事情也是错误的,包括:

  • 使用getAvailable()进行流处理;
  • 使用 56 位 DES 密码;
  • 使用ECB模式;
  • 重复调用doFinal(这会导致非常大的开销和不安全的代码);
  • 不使用CipherInputStreamCipherOutputStream(等等);
  • 使用字符串作为键;
  • 发生异常时忘记关闭流(对资源使用 try);
  • printStackTracke() 异常处理;
  • 使用静态字段作为变量。

new String(encText)中使用平台编码很可能是错误的。

<小时/>

请注意,使用错误的 key /密文组合也可能会导致此错误。

关于java - Java中的文件加密和解密,不起作用解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43872318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com