Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:将字节[]写入文件(缺少字节)_Java_File_Byte - Fatal编程技术网

Java:将字节[]写入文件(缺少字节)

Java:将字节[]写入文件(缺少字节),java,file,byte,Java,File,Byte,我的代码遇到一些问题 当我尝试使用函数Files.write将byte[](例如长度173517)写入文件时,每次都会将写入文件随机字节(例如3355),我会得到不同的值 这是我的代码: byte[] dataBytes = Files.readAllBytes(Paths.get(file.getAbsolutePath())); byte[] cipByte = cipher.doFinal(dataBytes); byte[] encr = Base64.getEncoder().enco

我的代码遇到一些问题

当我尝试使用函数
Files.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

从我的测试来看,问题似乎不是文件。我成功地编写了一个大小为94486449的字节数组,没有任何问题。
因此,可能出现的问题是,什么事情没有按预期进行:

  • 密码没有达到预期效果,并且cipByte的大小与预期不同
  • 编码器没有执行您期望的操作。请注意,如果调用Base64.getEncoder.encode(cipByte),生成的字节数组的大小将与cipByte不同,但大小不同

您确定要检查正确的
加密文件吗

用缺少的部分充实的代码段将生成有效的输出

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

感谢您的帮助,但我认为问题出在服务器上,发送的数据无效:)