任何文件,都可以基于 字节进行加密。只要知道密码,就可以进行解密。
原理,就是字节流中,逐字节和密码做异或,然后写入文件。
import java.io.*;
public class Encry {
public static void main(String[] args) throws Exception {
//String inputFilename="D:\\ProgramFiles\\Desktop\\index2-encryption.txt";
//String outputFilename="D:\\ProgramFiles\\Desktop\\index2-encryption2.txt";
//int encryNumber = 128;
// 至少三个参数
if(args.length<3){
throw new Exception("Must have 3 parames: inputFilename outputFilename encryNumber");
}
String inputFilename=args[0];
String outputFilename=args[1];
int encryNumber = Integer.parseInt(args[2]);
//检测: input 必须存在
if(! new File(inputFilename).exists()) {
throw new Exception("input file NOT exists!" + inputFilename);
}
//检测: output 必须不能存在
if( new File(outputFilename).exists()) {
throw new Exception("output file Already exists!" + outputFilename);
}
//数字必须在 [1, 128] 之间
System.out.println("encryNumber: " + encryNumber);
// 开始加密
BufferedInputStream bufferedInputStream=null;
BufferedOutputStream bufferedOutputStream=null;
try{
bufferedInputStream = new BufferedInputStream(new FileInputStream(inputFilename));
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFilename));
byte[] bytes = new byte[1024];
int len;
while( (len=bufferedInputStream.read(bytes)) != -1 ){
for(int i=0; i<len; i++){
bufferedOutputStream.write( bytes[i] ^ encryNumber );
}
}
} catch (IOException e){
e.printStackTrace();
}finally {
if( bufferedInputStream != null){
try {
bufferedInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(bufferedOutputStream != null){
try {
bufferedOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
System.out.println("End encryption!\n");
}
}
使用方法:
编译
E:\>javac Encry.java
执行加密:
E:\>java Encry index2.txt index2e.txt 5
encryNumber: 5
End encryption!
执行解密:
E:\>java Encry index2e.txt index2e2.txt 5
encryNumber: 5
End encryption!