RSA公钥密码的实现java

实验原理
RSA公钥密码原理
任务: Alice要求Bob将信息m用RSA方法加密传送回来.
(1) 密钥生成: Alice找到大素数p,q, 令n=pq, 取e>1满足 , 再找d使得 , 然后Alice将n, e作为加密密钥(公钥)发送给Bob, 这里p, q, d, 都是私钥, 要求保密, 用作解密;
(2) 加密: Bob 将明文m<n加密得到密文 , 并将密文Em传送给 Alice;
(3) 解密: Alice收到后密文Em, 计算 , 恢复明文m.

RSA生成密钥过程



import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.math.BigInteger;
import java.security.SecureRandom;

import javax.swing.*;

public class Rsamiyao extends JFrame implements ActionListener{
	private JFrame jf;
	private JPanel jpanel;
	private JButton jb1;
	private JLabel jlbl1,jlbl2;
	private JTextArea jta = null;
	private Container contentPane;
	private Rsamiyao() {
		jf = new JFrame("RSA");
		contentPane = jf.getContentPane();
		contentPane.setLayout(new BorderLayout());
		
		jta = new JTextArea("目前暂无密钥,请点击按钮生成密钥!");
		jta.setLineWrap(true); //自动换行
		jta.setEditable(false);//模仿JLabel禁止编辑文字
		jta.setBackground(new Color(238,238,238));
		jpanel = new JPanel();
		jb1 = new JButton("生成密钥");
		jb1.addActionListener(this);//监听
		jpanel.add(jb1,BorderLayout.CENTER);
		
		contentPane.add(jta,BorderLayout.NORTH);
		contentPane.add(jb1,BorderLayout.SOUTH);
		
		jf.setSize(400, 280);  //文本框原始大小
		jf.setLocation(400, 200);
		jf.setVisible(true);
		
		jb1.setBounds(300, 200, 10, 20);
		setVisible(true);
		jf.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		
	}
	
//		覆盖接口ActionListener的方法actionPerformed
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		contentPane.remove(jpanel);
		String key[] = Rsa.Rsakey(300);
		Write.Write(key[0]+'\n', "C:\\Users\\99724\\Desktop\\password\\Bob\\gongyao.txt");
		Write.Write(key[1]+'\n', "C:\\Users\\99724\\Desktop\\password\\Bob\\gongyao.txt");
		Write.Write(key[0]+'\n', "C:\\Users\\99724\\Desktop\\password\\Bob\\siyao.txt");
		Write.Write(key[1]+'\n', "C:\\Users\\99724\\Desktop\\password\\Bob\\siyao.txt");
		Write.Write(key[2]+'\n', "C:\\Users\\99724\\Desktop\\password\\Bob\\siyao.txt");
		Write.Write(key[3]+'\n', "C:\\Users\\99724\\Desktop\\password\\Bob\\siyao.txt");
		Write.Write(key[4]+'\n', "C:\\Users\\99724\\Desktop\\password\\Bob\\siyao.txt");
		Write.Write(key[5]+'\n', "C:\\Users\\99724\\Desktop\\password\\Bob\\siyao.txt");
		jf.setSize(1000, 600);
		jta.setText("公钥e,n已存入C:\\Users\\99724\\Desktop\\password\\Bob\\gongyao.txt\r\n\r\n");
		jta.append("e:"+key[0]+"\r\n\r\n n:"+key[1]+"\r\n\r\n");
		jta.append("公钥e,n私钥d,p,q,fn已存入C:\\Users\\99724\\Desktop\\password\\Bob\\siyao.txt \r\n\r\n");
		jta.append("e:"+key[0]+"\r\n\r\n n:"+key[1]+"\r\n\r\n" +"d:"+key[2]+"\r\n\r\n p:"+key[3]+"\r\n\r\n"
				+"q:"+key[4]+"\r\n\r\n fn:"+key[5]);
	}
	
	static class Rsa{
		static String[] Rsakey(int length) {
			String key[] = new String[6];
			int tmp = length/2;
			int length_p = 0,length_q = 0;
			if(tmp%2 == 0) {
				length_p = tmp - 1;
				length_q = tmp + 1;
			}else {
				length_p = tmp;
				length_q = tmp + 2;
			}
			length_p /= 0.3;
			length_q /= 0.3;
			//获取一个随机数
			SecureRandom random = new SecureRandom();
//			通过随机函数和长度获取一个随机数
//			求e*d==1modfn
			BigInteger p = BigInteger.probablePrime(length_p, random);
			BigInteger q = BigInteger.probablePrime(length_q, random);
			BigInteger n = p.multiply(q);
			BigInteger fn = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
			BigInteger e = new BigInteger(fn.bitLength()-3,1,random);
			BigInteger d = e.modInverse(fn);
			e.toString();
			key[0] = e.toString();
			key[1] = n.toString();
			key[2] = d.toString();
			key[3] = p.toString();
			key[4] = q.toString();
			key[5] = fn.toString();
	
			return key;
			
			
		}
	}
	public static void main(String[] args) {
		new Rsamiyao();
	}
}



//读取文件类:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;	

public class Write {
	public static int Write(String tmp,String address) {
		try {
				File file = new File(address);
			if(! file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileWriter fw = new FileWriter(address,true);
			fw.write(tmp);
			fw.close();
			return 1;
		}catch(IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

}

生成密钥效果图:

在这里插入图片描述
在这里插入图片描述




//RSA加密过程


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.math.BigInteger;

import javax.swing.*;


//实现接口 ActionListener
public class Jiami implements ActionListener{

	 JFrame jf;
	 JPanel jpanel;
	 JButton jb1;
	 JLabel messageLabel,messageLabel2;
	 JTextField textbox;
	 JTextArea jta = null;
	 JScrollPane jscrollPane;
	 public Jiami() {
		 jf = new JFrame("RSA加密");
		 Container contentPane = jf.getContentPane();
		 contentPane.setLayout(new BorderLayout());
		 
		 jta = new JTextArea(10, 15);
		 jta.setTabSize(4);
		 jta.setLineWrap(true);//激活自动换行功能
		 jta.setWrapStyleWord(true);//激活断行不断字功能
		 
		 jscrollPane = new JScrollPane(jta);
		 jpanel = new JPanel();
		 jpanel.setLayout(new FlowLayout());
		 
		 messageLabel = new JLabel("请输入明文数字");
		 
		 jb1 = new JButton("加密");
		 jb1.addActionListener(this);
		 
		 jpanel.add(jb1);
		 
		 contentPane.add(messageLabel,BorderLayout.NORTH);
		 contentPane.add(jscrollPane,BorderLayout.CENTER);
		 contentPane.add(jpanel,BorderLayout.SOUTH);
		 jf.setSize(400, 300);
		 jf.setLocation(400, 200);
		 jf.setVisible(true);
		 
		 jf.addWindowListener(new WindowAdapter() {
			 public void windowClosing(WindowEvent e) {
				 System.exit(0);
			 }
		});
	 }
//	 覆盖接口ActionListener的方法actionPerformed
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == jb1) {
			String[] a = Read.Readline("C:\\Users\\99724\\Desktop\\password\\Bob\\gongyao.txt");
			BigInteger pe = new BigInteger(a[0]);
			BigInteger pn = new BigInteger(a[1]);
			BigInteger pm = new BigInteger(jta.getText());
			BigInteger tmp = rsajiami(pm,pe,pn);
			int as = Write.Write(tmp.toString()+"\n","C:\\Users\\99724\\Desktop\\password\\Alice\\miwen.txt");
			if(as == 1) {
				jta.append("\r\n");
				jta.append("加密成功!!!");
				jta.append("\r\n");
				jta.append("密文:");
				jta.append(tmp+"");
			}else {
				jta.setText("加密失败!!");
			}
		}
	}
static BigInteger rsajiami(BigInteger tmp, BigInteger e, BigInteger n) {
	// TODO Auto-generated method stub
	BigInteger c = tmp.modPow(e, n);
	return c;
}
public static void main(String[] args) {
	new Jiami();
}
}



//读取文件:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Read {
	public static String[] Readline(String file) {
		try {
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String tmp[] = new String[100];
			String str;
			int i = 0;
			while((str = br.readLine())!= null) {
				tmp[i] = str;
				i++;
				
			}
			br.close();
			fr.close();
			return tmp;
			
		}catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
}

加密效果图:在这里插入图片描述


//RSA加密过程


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.math.BigInteger;

import javax.swing.*;


public class Jiemi implements ActionListener{
	JFrame jf;
	 JPanel jpanel;
	 JButton jb1,jb2;
	 JLabel messageLabel,messageLabel2;
	 JTextField textbox;
	 JTextArea jta = null;
	 JScrollPane jscrollPane;
	 //解密构造方法
	 public Jiemi() {
		 jf = new JFrame("RSA解密");
		 Container contentPane = jf.getContentPane();
		 contentPane.setLayout(new BorderLayout());
		 
		 jta = new JTextArea(10, 15);
		 jta.setTabSize(4);
		 jta.setLineWrap(true);//激活自动换行功能
		 jta.setWrapStyleWord(true);//激活断行不断字功能
		 
		 jscrollPane = new JScrollPane(jta);
		 jpanel = new JPanel();
		 jpanel.setLayout(new FlowLayout());
		 jb1 = new JButton("读取密文");
		 jb1.addActionListener(this);
		 jb2 = new JButton("解密");
		 jb2.addActionListener(this);
		 
		 jpanel.add(jb1);
		 jpanel.add(jb2);
		 messageLabel = new JLabel("请选择操作");
		 
		 contentPane.add(messageLabel,BorderLayout.NORTH);
		 contentPane.add(jscrollPane,BorderLayout.CENTER);
		 contentPane.add(jpanel,BorderLayout.SOUTH);
		 jf.setSize(400, 300);
		 jf.setLocation(400, 200);
		 jf.setVisible(true);
		 
		 jf.addWindowListener(new WindowAdapter() {
			 public void windowClosing(WindowEvent e) {
				 System.exit(0);
			 }
		});

	 }
	 
	 @Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			if(e.getSource() == jb1) {
				String tmp[] = Read.Readline("C:\\Users\\99724\\Desktop\\password\\Alice\\miwen.txt");
				jta.append(tmp[0]);
			}else if(e.getSource()== jb2) {
				String[] a = Read.Readline("C:\\Users\\99724\\Desktop\\password\\Bob\\siyao.txt");
				BigInteger pd = new BigInteger(a[2]);
				BigInteger pn = new BigInteger(a[1]);
				BigInteger pm = new BigInteger(jta.getText());
				BigInteger tmp = rsajiami(pm,pd,pn);
				int as = Write.Write(tmp.toString()+"\n","C:\\Users\\99724\\Desktop\\password\\Alice\\jiemiwen.txt");
				jta.append("\r\n");
				jta.append("这是明文!");
				jta.append("\r\n");
				jta.append(tmp.toString());
			}
				
			
		}

	static BigInteger rsajiami(BigInteger tmp, BigInteger d, BigInteger n) {
		// TODO Auto-generated method stub
		BigInteger c = tmp.modPow(d, n);
		return c;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Jiemi();
	}
}

解密效果图:
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA 公钥密码是一种非对称加密算法,其中加密和解密使用不同的密钥。在 RSA 加密过程中,使用一个公钥对数据进行加密,但要解密该数据,则需要使用其相应的私钥。以下是 Java 实现 RSA 公钥密码的示例代码: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import javax.crypto.Cipher; public class RSAEncryptionExample { public static void main(String[] args) throws Exception { // 生成 RSA 密钥对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom secureRandom = new SecureRandom(); keyPairGenerator.initialize(2048, secureRandom); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 获取公钥和私钥 PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); String plainText = "Hello, world!"; // 使用公钥加密明文 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedMessage = cipher.doFinal(plainText.getBytes()); System.out.println("Encrypted message: " + new String(encryptedMessage)); // 使用私钥解密密文 cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedMessage = cipher.doFinal(encryptedMessage); System.out.println("Decrypted message: " + new String(decryptedMessage)); } } ``` 在此示例中,我们使用 `KeyPairGenerator` 生成一个 RSA 密钥对。然后我们使用公钥加密明文,并使用私钥解密密文。在加密和解密过程中,我们使用 `Cipher` 类。使用 `Cipher.getInstance("RSA")` 创建一个 RSA 加密器/解密器实例。使用 `cipher.init(Cipher.ENCRYPT_MODE, publicKey)` 初始化加密器,使用 `cipher.init(Cipher.DECRYPT_MODE, privateKey)` 初始化解密器。最后,我们将加密后的密文和解密后的明文打印到控制台上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值