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();
                }
            }
        }
    }









  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值