JAVA 文本文件用异或算法进行加密解密的程序代码!

如题!
2024-11-20 05:29:52
推荐回答(1个)
回答1:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class XorExample {

public static final byte XOR_CONST = 0X12;

public static void main(String[] args) throws Exception {

File src = new File("level1.txt");

File dest = new File("level2.txt");

File dest2 = new File("level3.txt");

xorEn(src, dest);

xorEn(dest, dest2);

}

/**

* 异或的一个特点: a^b = c c^b = a

* 所以简单点,这里的加解密都用一个函数就行了

* @param src

* @param dest

* @throws Exception

*/

public static void xorEn(File src, File dest) throws Exception {

// 文件不存在或为文件夹就不判断了

FileInputStream fis = new FileInputStream(src);

FileOutputStream fos = new FileOutputStream(dest);

byte[] bs = new byte[1024];

int len = 0;

while ((len = fis.read(bs)) != -1) {

for (int i = 0; i < len; i++) {

bs[i] ^= XOR_CONST;

}

fos.write(bs, 0, len);

}

fos.close();

fis.close();

}
}