Java文件加密与解密

使用Java的二进制IO,对文件每个字节的数据进行修改,从而达到加密的目的。默认的加密方法是每个字节的数据+5,解密方法则是-5。

不用担心数字的值超过255而溢出,超过之后的值会减256从而回到0~255。

上代码

import java.io.*;

public class EncryptionAndDeciphering {

    private static final int OFFSET = 5;
    private static final String ENCRYPTION_PREFIX = "Encrypted_";
    private static final String DECIPHER_PREFIX = "Deciphered_";

    public static boolean changeFile(File inFile, int offset, String prefix) {
        //check input file
        if (!inFile.exists()) {
            System.out.println("File does not exist");
            return false;
        }

        //create output file
        File outFile = new File(prefix + inFile.getName());
        if (outFile.exists()) {
            return false;
        }
        try {
            if (!outFile.createNewFile()) {
                return false;
            }
        } catch (IOException e) {
            return false;
        }

        //IO
        try (
                BufferedInputStream input = new BufferedInputStream(new FileInputStream(inFile));
//                FileInputStream input = new FileInputStream(inFile);
                BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(outFile));
//                FileOutputStream output = new FileOutputStream(outFile);
        ) {
            int value;
            for (; ; ) {
                value = input.read();
                if (value == -1) {
                    break;
                }
                output.write(value + offset); //change
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean encryptFile(File inFile, int offset, String prefix) {
        return changeFile(inFile, offset, prefix);
    }

    public static boolean encryptFile(File inFile) {
        return changeFile(inFile, OFFSET, ENCRYPTION_PREFIX);
    }

    public static boolean decipherFile(File inFile, int offset, String prefix) {
        return changeFile(inFile, -offset, prefix);
    }

    public static boolean decipherFile(File inFile) {
        return changeFile(inFile, -OFFSET, DECIPHER_PREFIX);
    }

}

 

posted @ 2019-03-01 20:57  Elucidator  阅读(8744)  评论(0编辑  收藏  举报