文件的加密和解密
文件的加密和解密是一个简单的逻辑过程,最简单的文件的加密过程,就是在文件的读取过程中,借助异或运算的特性(一个数据异或同一个数据两次,得到原本的数据),所以在加密的过程中直接使用异或的方式,将文件变为乱码的格式,解密时再次异或一个数值,就可以实现文件的加密和解密过程了。
在加密过程中我们异或的数值可以称为密匙,在解密时输入密匙的值,即可进行解密
下面为大家展示文件的加密和解密的代码:
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
System.out.println("请输入要加密的文件路径");
String fileName = sc.nextLine();
//加密前的文件
File oldFile = new File(fileName);
//加密后的文件,将文件命命为旧文件名前加“key-”
File newFile = new File(oldFile.getParentFile(),"key-"+oldFile.getName());
FileInputStream fis = new FileInputStream(oldFile);
FileOutputStream fos = new FileOutputStream(newFile);
//密匙值
int key = keyword();
while (true){
int b = fis.read();
if (b == -1){
break;
}
fos.write(b^key);
}
System.out.println("加密完成,文件地址为:"+newFile.getParent());
}
public static int keyword(){
int key;
System.out.println("请输入密匙的值:");
try {
key = sc.nextInt();
}catch (Exception e){
System.out.println("密匙应输入数值,请重新输入:");
return keyword();
}
return key;
}
解密代码与加密代码基本相同,只需要添加一个判别密匙的选择语句即可,在此就不展示了。