1. 程式人生 > >凱撒密碼--簡單的加密與解密

凱撒密碼--簡單的加密與解密

凱撒密碼–簡單的加密與解密

public class MyEncrypt {

    private static final int KEY = 3;

    public enum EncryptState {
        ENCRYPT,    //表示加密操作
         DECRYPT    //表示解密操作
    }

    public static void main(String[] args) {

        String input = "wo men dou shi cheng xu yuan";

        System.out.println(input);

        String result = myEncrypt(input, KEY, EncryptState.ENCRYPT);

        System.out.println(result);

        result = myEncrypt(result, KEY, EncryptState.DECRYPT);

        System.out.println(result);


        File input = new
File("C:\\Users\\zhang\\Desktop\\code", "yuanwenjian.txt"); if (input == null) { input.mkdirs(); } File encrypt = new File("C:\\Users\\zhang\\Desktop\\code", "encrypt.txt"); if (encrypt == null) { encrypt.mkdirs(); } myEncrypt(input, encrypt, KEY, EncryptState.ENCRYPT); File decrypt = new
File("C:\\Users\\zhang\\Desktop\\code", "decrypt.txt"); if (decrypt == null) { decrypt.mkdirs(); } myEncrypt(encrypt, decrypt, KEY, EncryptState.DECRYPT); } private static String myEncrypt(String input, int key, EncryptState encrypt) { // 將字串轉為字元陣列
char[] chars = input.toCharArray(); // 遍歷陣列,在每個元素的基礎上加key值 for (int i = 0; i < chars.length; i++) { if (encrypt == EncryptState.ENCRYPT) { chars[i] += key; } else if (encrypt == EncryptState.DECRYPT) { chars[i] -= key; } } return new String(chars); } /** * 加密或解密檔案 * * @param input * @param output * @param key * @throws IOException */ private static void myEncrypt(File input, File output, int key, EncryptState encrypt) throws IOException { BufferedReader br = new BufferedReader(new FileReader(input)); BufferedWriter bw = new BufferedWriter(new FileWriter(output)); String temp = ""; while ((temp = br.readLine()) != null) { char[] array = temp.toCharArray(); for (int i = 0; i < array.length; i++) { if (encrypt == EncryptState.ENCRYPT) { array[i] += key; } else if (encrypt == EncryptState.DECRYPT) { array[i] -= key; } } String result = new String(array); System.out.println(result); bw.write(result); } bw.close(); br.close(); }