java | 基于异或的 字节加密和解密文件

任何文件,都可以基于 字节进行加密。只要知道密码,就可以进行解密。

原理,就是字节流中,逐字节和密码做异或,然后写入文件。

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!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值