文件的加密和解密

文件的加密和解密

文件的加密和解密是一个简单的逻辑过程,最简单的文件的加密过程,就是在文件的读取过程中,借助异或运算的特性(一个数据异或同一个数据两次,得到原本的数据),所以在加密的过程中直接使用异或的方式,将文件变为乱码的格式,解密时再次异或一个数值,就可以实现文件的加密和解密过程了。

在加密过程中我们异或的数值可以称为密匙,在解密时输入密匙的值,即可进行解密

下面为大家展示文件的加密和解密的代码:

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

解密代码与加密代码基本相同,只需要添加一个判别密匙的选择语句即可,在此就不展示了。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值