Information Security Internship: Internship 3 Swing Interface Based on RSA Public Key Encryption (Report + Detailed Code)

The purpose of the internship

  1. Understand public key cryptographic algorithms, familiar with common cryptographic algorithms: RSA, elliptic curve cryptosystem;

  2. Taking the RSA encryption algorithm as an example, master the realization of the encryption and decryption process of the public key encryption algorithm.

2. Implementation requirements

1. Carefully preview the relevant content of Chapter 6 before the internship;

2. Familiar with related classes in java.security.* and java.crypto.* in java.

3. Internship content

  1. [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) Simulate two users with two local directories to realize basic RSA encrypted communication, and the imported packages are specific to the class;

(2) For the RSA encryption implementation graphical interface, the user can input the plaintext and 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) Use SOCKET to establish a secure communication process;

(5) Migrate the program to a web application.

2. [implementation hints]

(1) You can use the KeypairGenerator class in java to create a public key pair, and the static method getInstance() of the factory class KeypairGenerator can obtain the KeypairGenerator type object.

(2) The parameter of the method getInstance() is a string type, specifying the name of the encryption algorithm such as: RSA.

(3) Create a cipher using the object of the factory class Cipher. Similarly, the parameter of getInstance() is a string type, specifying the name of the encryption algorithm.

(4) JSDK1.2 only implements the creation of RSA keys, but does not implement the RSA algorithm. Therefore, it is necessary to install the software packages of other encryption software providers to directly use the Cipher class to perform encryption and decryption.

(5) The RSA algorithm uses integers for encryption operations. The public key of RSA contains two pieces of information: the integer e corresponding to the public key and the integer n used for modulo. The formula for calculating ciphertext for plaintext m is me mod n. The modPow() method defined in the BigInteger class in java can calculate me mod n.

(6) The private key of RSA contains two pieces of information: the integer d corresponding to the private key and the integer n used for modulo. The formula for calculating the plaintext is: Ce mod n.

4. Experimental Design

1. Basic idea

The implementation of the RSA algorithm needs to define a total of three classes. First, define the SKey_RSA class, which is mainly used to generate a public key pair. Use the KeyPairGenerator class in java to create a public key pair, and the static method getInstance() of the factory class KeyPairGenerator can obtain the KeyPairGenerator type object. Specify the key length, generate a key pair, and output its public key and private key to a file respectively

Skey_RSA_pub.dat and Skey_RSA_priv.dat. Next, define the Enc_RSA class and perform encryption. In the main function, first enter a string plaintext and then read the file Skey_RSA_pub.dat to obtain the public key, and then obtain the public key parameters (the integer e corresponding to the public key and the integer used for modulo n), write the encrypted cache to the file Enc_RSA.dat. The last is to define the Dec_RSA class, which is based on RSA decryption. First obtain the file Enc_RSA.dat, read the contents of the file in turn, read the private key stored in the Skey_RSA_priv.dat file, and then obtain the private key parameters (the integer e corresponding to the private key and the integer n used for modulus), Output the decrypted content.

2. Class diagram design

3. Core method flow chart design

V. Test of experimental results

1. Encryption

2. Decryption

 3. Encryption GUI

4. Decrypt the graphical interface

code 

 

package work3;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.security.interfaces.RSAPrivateKey;

public class Dec_RSA {

	public static void main(String[] args) throws Exception {
		@SuppressWarnings("resource")
		BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream("Enc_RSA.dat")));
        String ctext=in.readLine();
        BigInteger c=new BigInteger(ctext);
        FileInputStream f=new FileInputStream("Skey_RSA_priv.dat");
        @SuppressWarnings("resource")
		ObjectInputStream b=new ObjectInputStream(f);
        RSAPrivateKey prk=(RSAPrivateKey)b.readObject();
		BigInteger d=prk.getPrivateExponent();
        BigInteger n=prk.getModulus();
        System.out.println("d="+d);
        System.out.println("n="+n);
        BigInteger m=c.modPow(d, n);
        System.out.println("m="+m);
        byte[] mt=m.toByteArray();
        System.out.println("PlainTwxt is");
        for(int i=0;i<mt.length;i++){
        	 System.out.print((char)mt[i]);
        }
	}

}

 

package work3;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;


public class Enc_RSA {

	public static void main(String[] args) throws Exception {
		String s="Hello World!";
		FileInputStream f=new FileInputStream("Skey_RSA_pub.dat");
		@SuppressWarnings("resource")
		ObjectInputStream b=new ObjectInputStream(f);
		RSAPublicKey pbk=(RSAPublicKey)b.readObject();
		BigInteger e=pbk.getPublicExponent();
        BigInteger n=pbk.getModulus();
        System.out.println("e="+e);
        System.out.println("n="+n);
        byte ptext[]=s.getBytes("UTF-8");
        BigInteger m=new BigInteger(ptext);
        BigInteger c=m.modPow(e, n);
        System.out.println("c="+c);
        String cs=c.toString();
        BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Enc_RSA.dat")));
        out.write(cs,0,cs.length());
        out.close();
        
	}

}

 

package work3;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class RSA_Encrypt {
    /** 指定加密算法为DESede */
    private static String ALGORITHM = "RSA";
    /** 指定key的大小 */
    private static int KEYSIZE = 1024;
    /** 指定公钥存放文件 */
    private static String PUBLIC_KEY_FILE = "PublicKey";
    /** 指定私钥存放文件 */
    private static String PRIVATE_KEY_FILE = "PrivateKey";

    /**
     * 生成密钥对
     */
    private static void generateKeyPair() throws Exception {
        /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom sr = new SecureRandom();
        /** 为RSA算法创建一个KeyPairGenerator对象 */
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        kpg.initialize(KEYSIZE, sr);
        /** 生成密匙对 */
        KeyPair kp = kpg.generateKeyPair();
        /** 得到公钥 */
        Key publicKey = kp.getPublic();
        /** 得到私钥 */
        Key privateKey = kp.getPrivate();
        /** 用对象流将生成的密钥写入文件 */
        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
        ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
        oos1.writeObject(publicKey);
        oos2.writeObject(privateKey);
        /** 清空缓存,关闭文件输出流 */
        oos1.close();
        oos2.close();
    }

    /**
     * 加密方法 source: 源数据
     */
    public static String encrypt(String source) throws Exception {
        generateKeyPair();
        /** 将文件中的公钥对象读出 */
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
        Key key = (Key) ois.readObject();
        ois.close();
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] b = source.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(b1);
    }

    /**
     * 解密算法 cryptograph:密文
     */
    public static String decrypt(String cryptograph) throws Exception {
        /** 将文件中的私钥对象读出 */
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
        Key key = (Key) ois.readObject();
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b1 = decoder.decodeBuffer(cryptograph);
        /** 执行解密操作 */
        byte[] b = cipher.doFinal(b1);
        return new String(b);
    }

    public static void main(String[] args) throws Exception {

        JFrame frame = new JFrame("RSA加密解密");
        // Button名称
        JButton button1 = new JButton("加密");
        JButton button2 = new JButton("解密");
        // JTextField名称
        final JTextField content = new JTextField();
        final JTextField pass = new JTextField();
        final JTextField dpass = new JTextField();

        // JLabel
        JLabel view = new JLabel("明文", JLabel.CENTER);
        view.setFont(new java.awt.Font("明文", 1, 15));
        view.setOpaque(true);
        view.setBackground(Color.WHITE);
        view.setForeground(Color.BLACK);

        // 画布布局
        JPanel contentPane = new JPanel();
        contentPane.add(button1);
        contentPane.add(button2);
        contentPane.add(content);
        contentPane.add(pass);
        contentPane.add(dpass);
        contentPane.add(view);
        frame.setContentPane(contentPane);
        contentPane.setLayout(null);

        // 大小设置
        view.setBounds(250, 0, 80, 30);
        content.setBounds(50, 0, 200, 30);
        pass.setBounds(50, 50, 200, 30);
        button1.setBounds(250, 50, 80, 30);
        dpass.setBounds(50, 100, 200, 30);
        button2.setBounds(250, 100, 80, 30);
        frame.setSize(400, 300);
        frame.setVisible(true);

        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String str1 = content.getText().toString();
                try {
                    pass.setText(encrypt(str1));
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });

        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String str2 = content.getText().toString();
                try {
                    dpass.setText(str2);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}

 

package work3;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

public class SKey_RSA {

	public static void main(String[] args) throws Exception {
		KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
		kpg.initialize(1024);
		KeyPair kp=kpg.genKeyPair();
		PublicKey pbkey=kp.getPublic();
		PrivateKey prkey=kp.getPrivate();
		FileOutputStream f1=new FileOutputStream("Skey_RSA_pub.dat");
		@SuppressWarnings("resource")
		ObjectOutputStream b1=new ObjectOutputStream(f1);
		b1.writeObject(pbkey);
		FileOutputStream f2=new FileOutputStream("Skey_RSA_priv.dat");
		@SuppressWarnings("resource")
		ObjectOutputStream b2=new ObjectOutputStream(f2);
		b2.writeObject(prkey);
	}

}

 

Guess you like

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