Information Security Internship: Internship One Classical Encryption Algorithm Swing Graphical (Report + Detailed Code)

The purpose of the internship

  1. Familiar with the Java platform development environment;
  2. Understand common classical encryption algorithms: Caesar cipher, multi-letter substitution cipher, multi-table substitution cipher;
  3. Understand the replacement technology and replacement technology in classical encryption technology.

2. Internship requirements

  1. Before the internship, carefully preview the relevant content of Chapters 1 and 2;
  2. Write programs and prepare data for the given topics in the practice content before going on the computer;
  3. Edit, debug, run the program on the computer, save the final program, and then write the internship report;
  4. The internship report needs to be written on a special report paper, and the contents include: internship name, internship purpose, content, operation process, program list, operation results, problems and solutions during the internship, and internship experience, etc. See Appendix 1 for specific requirements.

3. Internship content

1. [Problem Description]

The Caesar cipher replaces each letter in the alphabet with the letter after that letter.

The general encryption algorithm of the Caesar cipher is: C=E(P)=(P+k) mod 26 0<k<26

The general decryption algorithm of the Caesar cipher is: P=D(C)=(Pk) mod 26 0<k<26

2. [Ladder tasks]: Internship tasks are given gradually according to the difficulty. Step (1) is the basic task that must be completed. Please choose the subsequent ladder tasks according to your actual situation.

(1) The encryption and decryption algorithm of Caesar cipher can be realized by using Table 2-1 of the textbook, and encryption and decryption can be performed according to the user's selected key (shift number) and plaintext, and the user key is within the integer range;

(2) For the Caesar encryption implementation graphical interface, the user can input the plaintext and the key, and display the corresponding ciphertext in the text box;

(3) To realize the user's operation on the file, the user can store the encrypted result in the specified file by specifying the path file and key;

(4) Extend the Caesar cipher to any starting position, character set, key length, encryption and decryption algorithms;

(5) Learn a Chinese encoding method to realize character set encryption and decryption. (This option is optional).

3. [implementation hints]

(1) The user can select the key and plaintext through commands;

(2) Since there are 26 characters in the alphabet, the shifted number of digits (key) and 26 should be modulo first before shifting. The automatic conversion of characters and integers can be implemented in the Java platform, so adding a positive integer to a character represents the number of shifts to the right in the alphabet. If the number of bits shifted is negative, it represents the number of left shifts in the letter.

(3) Although the number of bits to be shifted and 26 have been taken modulo before shifting, the right and left shifts implemented in this way may still be out of bounds. Therefore, it is still necessary to judge whether it is out of bounds after shifting.

4. Experimental Design

1. Basic idea

(1) Design encryption and decryption algorithm

According to the general encryption and decryption algorithm (the general encryption algorithm of Caesar cipher is: C=E(P)=(P+k) mod 26 0<k<26), the encryption and decryption can be realized, and the key (shift key) can be selected according to the user. number) and plaintext for encryption and decryption, and the user key is in the integer range. First, define a Caesar class first, there are two options: after selecting encryption, you must enter the string to be encrypted, and enter the key (shift number), encrypt the text according to the encryption algorithm function, and encrypt the encrypted result. output. After selecting decryption, input the string to be decrypted and the key (shift number), decrypt the text according to the decryption algorithm function, and output the decrypted result. These two functions are just the opposite. All encryption and decryption characters are between a~z and A~Z. If they are not among them, they are out of bounds and need to be converted into range values.

(2) Design the operation interface of encryption and decryption

The interface class Caesarframe includes three input text boxes for ciphertext, key, and ciphertext, as well as two buttons for encryption and decryption. Event listeners are added to the buttons. By obtaining the input string, the key Start bit, declare the object of the Caesar class, and call the encryption and decryption methods to encrypt and decrypt the input string.

If you want to encrypt, enter the string to be encrypted and the key, click the "Encrypt" button, and the encrypted ciphertext will be displayed in the ciphertext text box. On the contrary, if you want to decrypt, enter the string to be decrypted and the key, click the "Decrypt" button, and the decrypted plaintext will be displayed in the plaintext text box.

(3) Realize the operation of the file by the user

Create two files miwen.txt and mingwen.txt in the project folder , and then enter the plaintext content in mingwen.txt and save it. Then read the contents of the file in turn and encrypt the contents of the file according to the input key and save it to miwen.txt .

2. Class diagram design 

Figure 4-1 Class Diagram

3. Core method flow chart design 

Figure 4-2 Flowchart of the core method

V. Test of experimental results

1. Design encryption and decryption algorithm

Encryption: Enter the plaintext " I love you ", the key is 3 , the encrypted result is shown in Figure 5-1

 Figure 5-1

Decryption: Enter the ciphertext " I miss you ", the key is 4 , the decrypted result is shown in Figure 5-2

Figure 5-2

2. Design the operation interface of encryption and decryption

Encryption: Enter the plaintext " I love you ", the key is 3 , click the "Encrypt" button and the result is shown in Figure 5-3

Figure 5-3

Decryption: Enter the ciphertext " I miss you ", the key is 4 , click the "Decrypt" button and the result is shown in Figure 5-4

Figure 5-4

3. Implement user operations on files

Create two files, mingwen.txt and miwen.txt, under the work1 project, as shown in Figure 5-5.

 Figure 5-5

Enter the following content in mingwen.txt, as shown in Figure 5-6.

Figure 5-6

Enter the input file, output file and key in the console, as shown in Figure 5-7.

Figure 5-7

The following content is displayed in miwen.txt, as shown in Figure 5-8.

Figure 5-8

Code:

 

package work1;

import java.util.Scanner;

public class Caesar {
		@SuppressWarnings("resource")
		public static void main(String[] args) {
			System.out.println("[1 加密][2 解密],请选择一个");
			Scanner c=new Scanner(System.in);   //	创建Scanner对象
			String s1=c.nextLine();             //获取本行的字符串
			if(s1.equalsIgnoreCase("1")) {      //判断变量s1与A是否相等,忽略大小
				System.out.println("请输入明文:");
				Scanner sc=new Scanner(System.in);
				String s=sc.nextLine();
				System.out.println("请输入密钥:");
				Scanner sc1=new Scanner(System.in);
				int key=sc1.nextInt();        //将下一输入项转换成int类型
				JiaMi(s,key);                 //调用加密方法
			}
			else if(s1.equalsIgnoreCase("2")) {
				System.out.println("请输入密文:");
				Scanner sc=new Scanner(System.in);
				String s=sc.nextLine();
				System.out.println("请输入密钥:");
				Scanner sc1=new Scanner(System.in);
				int key=sc1.nextInt();
				JieMi(s,key);                   //调用解密方法
			}
		}
		public static void JiaMi(String str, int k) {
			String string="";
			for(int i=0;i<str.length();i++) {
				char c=str.charAt(i);
				if(c>='a'&&c<='z')//如果字符串中的某个字符是小写字母
				{
					c+=k%26;//移动key%26位
					if(c<'a')
						c+=26;//向左超界
					if(c>'z')
						c-=26;//向右超界
				}else if(c>='A'&&c<='Z')//如果字符串中的某个字符是大写字母
				{
					c+=k%26;//移动key%26位
					if(c<'A')
						c+=26;//向左超界
					if(c>'Z')
						c-=26;//向右超界
				}
				string +=c;//将解密后的字符连成字符串
			}
			System.out.println(str+"加密后为:"+string);
		}
	 
		public static void JieMi(String str, int n) {
			int k=Integer.parseInt("-"+n);
			String string="";
			for(int i=0;i<str.length();i++) {
				char c=str.charAt(i);
				if(c>='a'&&c<='z')//如果字符串中的某个字符是小写字母
				{
					c+=k%26;//移动key%26位
					if(c<'a')
						c+=26;//向左超界
					if(c>'z')
						c-=26;//向右超界
				}else if(c>='A'&&c<='Z')//如果字符串中的某个字符是大写字母
				{
					c+=k%26;//移动key%26位
					if(c<'A')
						c+=26;//向左超界
					if(c>'Z')
						c-=26;//向右超界
				}
				string +=c;//将解密后的字符连成字符串
			}
			System.out.println(str+"解密后为:"+string);		
		}
}
package work1;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Encryptor {
    private int key;

    public Encryptor(int aKey) {
        key = aKey;
    }

    public void encryptFile(String inFile, String outFile) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(inFile);
            out = new FileOutputStream(outFile);
            encrypStream(in,out);
        }
        finally {
            if(in != null ) in.close();
            if(out != null ) out.close();
        }
    }
    public void encrypStream(InputStream in, OutputStream out) throws IOException { 
        boolean done = false;
        while (!done) {
            int next = in.read();
            if (next == -1) done = true;
            else {
                byte b = (byte) next;
                byte c = encrypt(b);
                out.write(c);

            }
        }
    }
    public byte encrypt(byte b) {
        return (byte) (b + key);

    }
}

package work1;

import java.io.IOException;
import java.util.Scanner;

public class EncryptorTester {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try {
            System.out.print("Input file: ");
            String inFile = in.next();
            System.out.print("Output file: ");
            String outFile = in.next();
            System.out.print("Encryption key: ");
            int key = in.nextInt();
            Encryptor crypt = new Encryptor(key);
            crypt.encryptFile(inFile, outFile);

        } catch (IOException e) {
            System.out.println("Error processing file : " + e);
        }

    }
}
package work1;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;

public class CaesarFrame extends JFrame {

	private JPanel contentPane;
	private JTextField mingwenJTF;
	private JTextField keyJTF;
	private JTextField miwenJTF;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					CaesarFrame frame = new CaesarFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public CaesarFrame() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JLabel nameJL = new JLabel("\u607A\u6492\u5BC6\u7801");
		nameJL.setFont(new Font("宋体", Font.BOLD, 22));
		
		JLabel mingwenJL = new JLabel("\u660E  \u6587\uFF1A");
		mingwenJL.setFont(new Font("宋体", Font.PLAIN, 18));
		
		mingwenJTF = new JTextField();
		mingwenJTF.setColumns(10);
		
		JLabel keyJL = new JLabel("\u5BC6  \u94A5\uFF1A");
		keyJL.setFont(new Font("宋体", Font.PLAIN, 18));
		
		keyJTF = new JTextField();
		keyJTF.setColumns(10);
		
        
		
		miwenJTF = new JTextField();
		miwenJTF.setColumns(10);
		
		JLabel miwenJL = new JLabel("\u5BC6  \u6587\uFF1A");
		miwenJL.setFont(new Font("宋体", Font.PLAIN, 18));
		
		JButton jiamiJL = new JButton("\u52A0\u5BC6");
		jiamiJL.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String mingwen=mingwenJTF.getText();
				String key1=keyJTF.getText();
                String string="";
				int key = Integer.parseInt(key1);
				for(int i=0;i<mingwen.length();i++) {
					char c=mingwen.charAt(i);
					if(c>='a'&&c<='z')//如果字符串中的某个字符是小写字母
					{
						c+=key%26;//移动key%26位
						if(c<'a')
							c+=26;//向左超界
						if(c>'z')
							c-=26;//向右超界
					}
					else if(c>='A'&&c<='Z')//如果字符串中的某个字符是大写字母
					{
						c+=key%26;//移动key%26位
						if(c<'A')
							c+=26;//向左超界
						if(c>'Z')
							c-=26;//向右超界
					}
					string+=c;//将解密后的字符连成字符串
					miwenJTF.setText(string);
				}				
			}
		});
		jiamiJL.setFont(new Font("宋体", Font.PLAIN, 18));
		
		
		JButton jiemiJB = new JButton("\u89E3\u5BC6");
		jiemiJB.addActionListener(new ActionListener() {
			//解密
			public void actionPerformed(ActionEvent e) {
				String miwen=miwenJTF.getText();
				String key1=keyJTF.getText();
				int key=Integer.parseInt("-"+key1);
				String string="";
				for(int i=0;i<miwen.length();i++) {
					char c=miwen.charAt(i);
					if(c>='a'&&c<='z')//如果字符串中的某个字符是小写字母
					{
						c+=key%26;//移动key%26位
						if(c<'a')
							c+=26;//向左超界
						if(c>'z')
							c-=26;//向右超界
					}else if(c>='A'&&c<='Z')//如果字符串中的某个字符是大写字母
					{
						c+=key%26;//移动key%26位
						if(c<'A')
							c+=26;//向左超界
						if(c>'Z')
							c-=26;//向右超界
					}
					string +=c;//将解密后的字符连成字符串
					mingwenJTF.setText(string);
				}
			}
		});
		jiemiJB.setFont(new Font("宋体", Font.PLAIN, 18));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(64)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
							.addComponent(mingwenJL)
							.addComponent(keyJL)
							.addComponent(miwenJL))
						.addComponent(jiamiJL))
					.addGap(18)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(nameJL)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addGap(10)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
								.addComponent(keyJTF, GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
								.addComponent(miwenJTF)
								.addComponent(mingwenJTF, GroupLayout.PREFERRED_SIZE, 180, GroupLayout.PREFERRED_SIZE)
								.addComponent(jiemiJB, Alignment.TRAILING))))
					.addContainerGap(78, Short.MAX_VALUE))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(22)
					.addComponent(nameJL)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(mingwenJL)
						.addComponent(mingwenJTF, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(keyJL)
						.addComponent(keyJTF, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(29)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(miwenJL)
							.addPreferredGap(ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(jiemiJB)
								.addComponent(jiamiJL)))
						.addComponent(miwenJTF, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
		);
		contentPane.setLayout(gl_contentPane);
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324356006&siteId=291194637