The way Java encrypts files is:
Use the input buffer byte stream to read the file content into the buffer, and then use the The section array output buffer stream is written into a byte array
// 第一步文件的加密 // 先用字节缓冲流读取文件 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(“你要加密的文件全路径”)); // 再用字节数组输出流将文件写到一个字节数组内 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 调用writeFile2方法写到一个字节数组内 writeFile2(baos, bis) // 将字节数组输出流内的内容转换成一个字节数组 byte[] byteArray = baos.toByteArray();
writeFile2方法: /** private static void writeFile2(ByteArrayOutputStream baos, BufferedInputStream bis) throws Exception { byte [] bytes = new byte [1024]; int len = -1; while ((len= bis.read(bytes))!=-1) { baos.write(bytes, 0, len); } bis.close(); }
Encryption is achieved by performing an XOR operation on each data in the array, because the same number is XORed twice and is still the original one. Through this, encryption and Decrypt
private static byte[] jiami(byte[] byteArray) { for (int i = 0; i < byteArray.length; i++) { byteArray[i] = (byte) (byteArray[i] ^ 96);// 将异或后的数据强转成字节类型 } return byteArray; }
Divide the array contents into three parts.
int size = byteArray.length / 3; byte[] byteArray1 = new byte[size]; byte[] byteArray2 = new byte[size]; byte[] byteArray3 = new byte[byteArray.length-2*size]; for (int i = 0; i < size; i++) { byteArray1[i] = byteArray[i]; } for (int i = size; i < 2*size; i++) { byteArray2[i - size] = byteArray[i]; } for (int i = size * 2; i < byteArray.length; i++) { byteArray3[i - size * 2] = byteArray[i]; }
4. Write these divided arrays into specific files through streams
ByteArrayInputStream bais = null; BufferedOutputStream bos = null; for (int i = 0; i < 3; i++) { switch (i) { case 0:// 第一份 bais = new ByteArrayInputStream(byteArray1); // 用字节缓冲输出流将数组内容写到具体的位置 bos = new BufferedOutputStream(new FileOutputStream("F:/test/111.dll")); // 下面还要用到这个方法写数据的方法,可以定义一个方法 writeFile(size, bais, bos, 0); break; case 1:// 第二份 bais = new ByteArrayInputStream(byteArray2); // 用字节缓冲输出流将数组内容写到具体的位置 bos = new BufferedOutputStream(new FileOutputStream("F:/test/112.dll")); writeFile(size, bais, bos, 1); break; case 2:// 第三份 bais = new ByteArrayInputStream(byteArray3); bos = new BufferedOutputStream(new FileOutputStream("F:/test/113.dll")); writeFile(byteArray.length-2*size, bais, bos, 2); break; } }
writeFile方法 private static void writeFile(int size, ByteArrayInputStream bais, BufferedOutputStream bos, int i) throws Exception { byte[] bytes = new byte[1024]; int len = -1; while ((len = bais.read(bytes)) != -1) { bos.write(bytes, 0, len); } bos.close(); }
Recommended tutorial: "java tutorial"
The above is the detailed content of How to encrypt files in java. For more information, please follow other related articles on the PHP Chinese website!