monoalphabetic.java

来自「单表加密算法、单表解密算法实现的简单示例」· Java 代码 · 共 105 行

JAVA
105
字号

import java.io.*;

public class Monoalphabetic {
	private String srcFilePath;
	private String prnPath;
	
	public Monoalphabetic(String filePath,String parentPath){
		this.srcFilePath = filePath;
		this.prnPath = parentPath;
	}
	
	public void cipher(){
		try{
        	File sourceFile = new File(srcFilePath);
			
        	File outFile = new File(prnPath+"\\Monoalphabetic encryption.txt");
			outFile.createNewFile();
			
			
 
			
		//  assuming that we only need to access data from .txt files
        	RandomAccessFile sf = new RandomAccessFile(sourceFile, "r");
    		RandomAccessFile of = new RandomAccessFile(outFile, "rw");	
			
    		Byte inChar;	// one byte read in
			int i;		//intValue of the inChar. It's to be written out after the substitution
			int key = 8;	//the key for encryption can be changed
			while(sf.getFilePointer()<sourceFile.length()){
				inChar = sf.readByte();			//读写二进制文件
				i = inChar.intValue();		
				if((i>=65)&&(i<=90))
				{
					i += key;
					if(i>90)
						i-=26;
					of.writeByte(i);
				}
				else if(i>=97&&i<=122)
				{
					i += key;
					if(i>122)
						i-=26;
					of.writeByte(i);
				}
				else
					of.writeByte(i);
			}
			sf.close();
			of.close();
		}
		catch(FileNotFoundException ex){
			System.out.println("Err when accessing source file");
		}
		catch(IOException ex){
			System.out.println("IOException");
		}
	}// cipher()
	
	public void decipher(){
		try{
        	File sourceFile = new File(srcFilePath);
			
        	File outFile = new File(prnPath+"\\Monoalphabetic decryption.txt");
			outFile.createNewFile();
			
        	RandomAccessFile sf = new RandomAccessFile(sourceFile, "r");
    		RandomAccessFile of = new RandomAccessFile(outFile, "rw");
    		
    		Byte inChar;
			int i;
			int key = 8;
			while(sf.getFilePointer()<sourceFile.length()){
				inChar = sf.readByte();
				i = inChar.intValue();		
				if((i>=65)&&(i<=90))
				{
					i -= key;
					if(i<65)
						i+=26;
					of.writeByte(i);
				}
				else if(i>=97&&i<=122)
				{
					i -= key;
					if(i<97)
						i+=26;
					of.writeByte(i);
				}
				else
					of.writeByte(i);
			}
			sf.close();
			of.close();
		}
		catch(FileNotFoundException ex){
			System.out.println("Err when accessing source file");
		}
		catch(IOException ex){
			System.out.println("IOException");
		}
	}// Decipher()
}

⌨️ 快捷键说明

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