【问题标题】:Java: write byte[] to file (missing bytes)Java:将字节 [] 写入文件(缺少字节)
【发布时间】:2016-06-02 08:40:29
【问题描述】:

我的代码遇到了一些问题。

当我每次尝试使用函数Files.write write 将文件byte[](例如长度为173517)写入文件随机字节(例如3355)时,我得到一个不同的值。

这是我的代码:

byte[] dataBytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
byte[] cipByte = cipher.doFinal(dataBytes);
byte[] encr = Base64.getEncoder().encode(cipByte);
Files.write(Paths.get(encryptedFile.getAbsolutePath()), encr); //encr len = 173517

【问题讨论】:

    标签: java file byte


    【解决方案1】:

    从我的测试来看,问题似乎不在于 Files.write。我设法编写了一个大小为 94486449 的字节数组,没有问题。
    因此,可能出现的问题可能与预期不符:

    • cipher 没有达到您的预期,并且 cipByte 的大小与预期不同。
    • 编码器没有按照您的预期进行。请注意,如果您调用 Base64.getEncoder.encode(cipByte),生成的字节数组将不是 cipByte 的大小,而是具有不同的大小。

    【讨论】:

      【解决方案2】:

      你确定你检查的是正确的encryptedFile吗?

      富含缺失部分的 sn-p 会产生有效的输出。

      byte[] dataBytes = "text to be encrypted".getBytes(StandardCharsets.ISO_8859_1);
      
      Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
      SecretKey key = KeyGenerator.getInstance("DES").generateKey();
      cipher.init(Cipher.ENCRYPT_MODE, key);
      
      byte[] cipByte = cipher.doFinal(dataBytes);
      byte[] encr = Base64.getEncoder().encode(cipByte);
      
      File encryptedFile = new File("/tmp/in.enc");
      Files.write(Paths.get(encryptedFile.getAbsolutePath()), encr);
      
      System.out.println("encr length: " + encr.length);
      System.out.println("file length: " + encryptedFile.length());
      

      输出

      encr length: 32
      file length: 32
      

      【讨论】:

      • 感谢您的帮助,但我认为问题在于服务器并发送无效数据:)
      猜你喜欢
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 2022-01-10
      • 1970-01-01
      • 2015-09-04
      • 2011-10-13
      相关资源
      最近更新 更多