Java异或进行文件加密

来源:互联网 发布:linux内核源代码在哪 编辑:程序博客网 时间:2024/06/05 02:13

  位运算符异或^,对二进制进行操作,连续异或两次相同的数值,得到的结果和原来的一样,如12 ^ 2 ^ 2 = 12;

所以,根据异或的特定可以对文件进行加密和解密,别人想要破解那必须得知道你异或的是哪个数值才行了。

package com.java;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import org.junit.Test;public class Demo {    /**     * 加密     */    @Test    public void encrypt() throws Exception{        String before = "D:\\image\\需要加密的文件名.jpg";        String after = "E:\\image\\加密后的命名.jpg";        encryptOrDecode(before, after);    }    /**     * 解密     */    @Test    public void decode() throws Exception{        String before = "D:\\image\\需要解密的文件名.jpg";        String after = "E:\\image\\解密后的命名.jpg";        encryptOrDecode(before, after);    }    /**     * 加密或解密方法     * @param before 需要加密或解密的路径,e.g C:\\encrypt.jpg     * @param after 需要解密或解密的路径,e.g D:\\decode.jpg     * @throws Exception     */    public static void encryptOrDecode(String before, String after) throws Exception{        File in = new File(before);        File out = new File(after);        FileInputStream inputStream = new FileInputStream(in);        FileOutputStream outputStream = new FileOutputStream(out);        int con;        while((con = inputStream.read()) != -1){//每次读取1个字节            outputStream.write(con^1314);        }        if(outputStream != null){            outputStream.close();        }        if(inputStream != null){            inputStream.close();        }    }}
0 0
原创粉丝点击