java - BadPaddingException 和一些文件卡在 99%

标签 java javafx aes encryption-symmetric badpaddingexception

我尝试从这里收集有关加密/解密的所有可能的信息。鼓捣了一下,有成功,也有失败。
但现在我已经应用了代码,它的成功和失败也有。某些文件(exe 或 msi)正在工作,但它们仍然给出有关 BadPaddingException 的错误。此外,其他一些媒体文件(如(mp4、mkv 等))卡在 99% 并且不会超出该值,尽管它们已完全接收(只是一些微小的字节差异,但磁盘上的大小始终匹配) ).

我只是想要一些帮助来摆脱这两个问题。文件通过套接字编程从一台 PC 传输到另一台 PC。
服务器:(已编辑)

    DataInputStream dis = new DataInputStream(msock.getInputStream());
    DataOutputStream dos = new DataOutputStream(msock.getOutputStream());

    String file2dl = dis.readLine(); //2
    File file = new File(sharedDirectory.toString() + "\\" + file2dl);
    dos.writeLong(file.length()); //3+

    //Get file name without extension.
    String fileName = Files.getNameWithoutExtension(file2dl);

    //AES-128 bit key initialization.
    byte[] keyvalue = "AES128BitPasswd".getBytes();
    SecretKey key = new SecretKeySpec(keyvalue, "AES");

    //Initialize the Cipher.
    Cipher encCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);

    //Get the IV from cipher.
    IvParameterSpec spec = null;
    try {
        spec = encCipher.getParameters().getParameterSpec(IvParameterSpec.class);
    } catch (InvalidParameterSpecException ex) {
        Logger.getLogger(PeersController.class.getName()).log(Level.SEVERE, null, ex);
    }

    byte[] iv = spec.getIV();

    dos.write(iv, 0, iv.length);
    File tempDir = new File(tempDirectory.toString());
    //Encryption Mechanism.
        try (FileInputStream fis = new FileInputStream(file)) {
            try (CipherOutputStream cos = new CipherOutputStream(dos, encCipher);
                    FileInputStream stream = new FileInputStream(tempDir + "\\" + fileName + ".encr")) {
                int read, r;
                byte[] buffer = new byte[1024 * 1024];
                while ((read = fis.read(buffer)) != -1) {
                    cos.write(buffer, 0, read);
                }
        }
    }
 }


客户:

 long len;
 int count = 0;
 int dflag = 0;
 String size;
 dos.writeBytes("Download\r\n"); //1+
 dos.writeBytes(filename + "\r\n"); //2+
 System.out.println("File to fetch: -> " + filename);
 len = dis.readLong(); //3
 System.out.println("Size of file: -> " + len);

//Get file name without Extension.
String fileName = Files.getNameWithoutExtension(filename);

//Get Initialization Vector from Encryption Cypher.
byte[] iv = new byte[16];
int j = dis.read(iv, 0, iv.length);

final File encrypted = new File(sharedDirectory.toString() + "\\" + fileName + ".encr");
final File decrypted = new File(sharedDirectory.toString() + "\\" + filename);
try (FileOutputStream fos = new FileOutputStream(encrypted)) {
    byte[] b = new byte[1024 * 1024];
    while (fetching) {
        int r = dis.read(b, 0, b.length); //4
        count = count + r;
        double p = (double) count / len;
        double per = new BigDecimal(p).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
        fos.write(b, 0, r);
        System.out.println("Size Appending: -> " + count);
        System.out.println("Percentage: ->" + per);
        Platform.runLater(() -> {
            pBar.setProgress(per);
        });
        if (count >= len) {
         dflag = 1;
         break;
        }
    }
}


如果加密数据已完全接收

if(dflag == 1) {
     //AES-128 bit key initialization.
     System.out.println("File completely received");
     byte[] keyvalue = "AES128PeerBuLLet".getBytes();
     Key key = new SecretKeySpec(keyvalue, "AES");

     //Initialization Vector initialized
     IvParameterSpec ivParameterSpec = null;

     //Cipher Initialization.
     Cipher decCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      try {
           decCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
     } catch (InvalidAlgorithmParameterException ex) {
                        Logger.getLogger(PeersController.class.getName()).log(Level.SEVERE, null, ex);
      }
      System.out.println(decCipher.getProvider().getInfo());

      //Decryption Mechanism.
      try (FileOutputStream stream = new FileOutputStream(decrypted)) {
             try (FileInputStream fis = new FileInputStream(encrypted)) {
                    try (CipherInputStream cis = new CipherInputStream(fis, decCipher)) {
                           int read, i = 0;
                           byte[] buffer = new byte[(1024 * 1024) + 16];
                           while ((read = cis.read(buffer)) != -1) {
                                    stream.write(buffer, 0, read);
                                    i = i + read;
                                    double d = (double) i / len;
                                    double progress = new BigDecimal(d).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
                                    Platform.runLater(() -> {
                                        pBar.setProgress(progress);
                                        progressText.setText("Decrypting..");
                                    });
                                }
                            } catch (Exception e) {
                                System.out.println(e.getMessage());
                            }
                        }
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
        }

任何意见都将受到高度赞赏。谢谢。

编辑1:添加了通过流接收的加密和解密文件大小的链接。 Dropbox Link

编辑2:最后,在三位参与帮助我的成员的帮助下,问题得到了解决。我正在查看问题的其他解决方案,并遇到 this解决方案帮助我深入思考后台发生的实际场景。感谢 Artjom B. 的推荐解决方案,以及 @zaph 和 @jtahlborn 消除了我对填充和输入/输出流的错误假设。

最佳答案

当使用填充、PKCS#5 或 PKCS#7 时,加密输出将会更大,最多可达并包括一个 block 大小。请参阅PKCS#7 。解密后填充被删除。

加密数据会更长,因此必须考虑在内。如何取决于如何处理输出。如果它要进入预分配区域(例如内存缓冲区),则必须为缓冲区分配大一个 block 大小(对于 AES 为 16 字节)。如果流式传输通常只是确保发送所有加密字节,则 n=它只是输入的长度。所有这些都取决于每个实现和系统/语言。

填充字节是由加密方法动态创建的,因此不需要更改输入。这假设加密方法是添加填充,解密方法是删除填充。

示例 1:如果您有 1024 字节的数据,则加密输出将为 1040 字节。解密时,输入数据将为 1040 字节,输出解密数据将为 1024 字节。

示例 2:如果您有 1020 字节的数据,则加密输出将为 1024 字节。解密时,输入数据将为 1024 字节,输出解密数据将为 1020 字节。

关于java - BadPaddingException 和一些文件卡在 99%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661789/

相关文章:

java - JXDatePicker 上的 NoClassDefFoundError

java - 我似乎无法让 RadioButtons 在 JavaFX 中工作

java - 使用 AES 解密文件时密码 doFinal 填充 block 损坏

java - 在 Java 和 golang 中使用 AES 时获得不同的结果(密文)

algorithm - C# 和 ColdFusion AES 加密不匹配

java - 用 Hashmap<String, List<String>> 比较两个字符串

java - 将单独类的方法调用到另一个类中

JavaFX 无法设置自定义属性

java - Java 和 MongoDB 集成中从 JSON 中读取所需字段,该 JSON 既不是 JSONobject,也不是 JSONArray

java - Hibernate createNativeQuery 使用 IN 子句