java对文件进行加密解密操作
源码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.junit.Test;
public class Demo2 {
//测试加密
@Test
public void test1() throws IOException{
String sourceFilePath = “e:\\001.png”;
String targetFilePath = “e:\\001_0.png”;
security(sourceFilePath,targetFilePath);
}
//测试解密
@Test
public void test2() throws IOException{
String sourceFilePath = “e:\\001_0.png”;
String targetFilePath = “e:\\001_1.png”;
security(sourceFilePath,targetFilePath);
}
/*
* 加密 和 解密操作
* sourceFilePath : 输入文件路径
* targetFilePath : 输出文件路径
*/
public void security(String sourceFilePath,String targetFilePath) throws IOException{
File sourceFile = new File(sourceFilePath);
File targetFile = new File(targetFilePath);
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try{
inputStream = new FileInputStream(sourceFile);
byte[] buffer = new byte[1024];
int len = 0;
outputStream = new FileOutputStream(targetFile);
while((len = inputStream.read(buffer))>0){
byte[] outputBuffer = new byte[len];
//分别对每个字节进行异或操作
for(int i=0;i<len;i++){
byte b = buffer[i];
b = (byte) (b ^ 25);
outputBuffer[i] = b;
}
outputStream.write(outputBuffer,0,len);
}
}finally{
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
}
}
}