⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 monoalphabetic.java

📁 Java实现传统算法加密解密
💻 JAVA
字号:
import java.util.*;
import java.io.*;

/**
 * 
 * @author Neng
 * 
 */
public class Monoalphabetic {
	/**
	 * input file containing plaintext
	 */
	private File inFile;

	/**
	 * ArrayList of an out-of-order alphabet
	 */
	private ArrayList<Integer> al;

	/**
	 * Hashmap for encrypt and decrypt
	 */
	HashMap<Integer, Integer> encryptMap, decryptMap;

	/**
	 * Constructor method
	 */
	public Monoalphabetic() {

//		System.out.println("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

		// create a new out-of-order alphabet
		al = new ArrayList<Integer>();
		for (int i = 65; i <= 90; i++) {
			al.add(i);
		}
		Collections.shuffle(al);

//		for (int i = 0; i < 26; i++) {
//			System.out.print((char) ((Integer) al.get(i)).intValue());
//
//		}
//		System.out.println("");

		// map the new alphabet with the original one
		encryptMap = new HashMap<Integer, Integer>();
		decryptMap = new HashMap<Integer, Integer>();

		for (int i = 0; i < 26; i++) {
			encryptMap.put(Integer.valueOf(97 + i), (Integer) al.get(i));
			decryptMap.put((Integer) al.get(i), Integer.valueOf(97 + i));
		}

	}

	public void encrypt(File in) throws IOException {
		inFile = in;
		saveAlphabet(inFile.getParent()+"/Mono_alphabet.txt");
		FileReader fr = new FileReader(inFile);
		FileWriter fw = new FileWriter(inFile.getParent() + "/Mono_cipher.txt");

		// read from input file and encrypt
		int temp;
		while ((temp = fr.read()) != -1) {
			// change plaintext to LowerCase
			temp = String.valueOf((char) temp).toLowerCase().charAt(0);
			if (temp >= 97 && temp <= 122) {
				temp = encryptMap.get(Integer.valueOf(temp)).intValue();
				fw.write(temp);
			}
		}
		fr.close();
		fw.close();

		System.out.println("Monoalphabetic encryption ok");

	}

	public void decrypt() throws IOException {
		FileReader fr2 = new FileReader(inFile.getParent() + "/Mono_cipher.txt");
		FileWriter fw2 = new FileWriter(inFile.getParent()
				+ "/Mono_decrypt.txt");
		int temp;
		while ((temp = fr2.read()) != -1) {
			if (temp >= 65 && temp <= 90) {
				temp = decryptMap.get(Integer.valueOf(temp)).intValue();
				fw2.write(temp);
			}
		}
		fw2.close();
		fr2.close();

		System.out.println("Monoalphabetic decryption ok");

	}
	
	public void saveAlphabet(String filename) throws IOException{
		FileWriter fw1 = new FileWriter(filename);
		for(int i=65;i<=90;i++) fw1.write(i);
		fw1.write(13);
		fw1.write(10);
		for (int i = 0; i < al.size(); i++) {
			fw1.write((Integer)al.get(i));
		}
		fw1.close();
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -