java使用异或对文件进行加密解密
时间:2021-04-14 09:06:35|栏目:JAVA代码|点击: 次
本文实例为大家分享了java使用异或对文件进行加密解密的具体代码,供大家参考,具体内容如下
1.使用异或的方式加密文件的原理
一个数异或另一个数两次,结果一定是其本身
2.使用异或的原理加密文件
/**
* 将文件内容加密
* 使用异或的方式将a.txt加密复制出一个b.txt,放到同一个文件夹下
*/
@Test
public void encryptFile(){
FileInputStream in = null;
FileOutputStream out = null;
try {
String sourceFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\a.txt";
String targetFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\b.txt";
in = new FileInputStream(sourceFileUrl);
out = new FileOutputStream(targetFileUrl);
int data = 0;
while ((data=in.read())!=-1){
//将读取到的字节异或上一个数,加密输出
out.write(data^1234);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//在finally中关闭开启的流
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.使用异或的原理解密文件
/**
* 将文件内容解密
* 将使用异或的方式加密复制出的b.txt解密到c.txt,放到同一个文件夹下
*/
@Test
public void decryptFile(){
FileInputStream in = null;
FileOutputStream out = null;
try {
String sourceFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\b.txt";
String targetFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\c.txt";
in = new FileInputStream(sourceFileUrl);
out = new FileOutputStream(targetFileUrl);
int data = 0;
while ((data=in.read())!=-1){
//将读取到的字节异或上一个数,加密输出
out.write(data^1234);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//在finally中关闭开启的流
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上一篇:Java中的泛型详解
栏 目:JAVA代码
下一篇:解决SpringBoot在后台接收前台传递对象方式的问题
本文标题:java使用异或对文件进行加密解密
本文地址:http://www.codeinn.net/misctech/101322.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




