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

📄 rsa.java

📁 RSA的JAVA实现,界面很简洁,就三个按钮:生成密钥对,加密文件,解密文件.可以导入文件,但文件长度有限制,这是由于密钥长度而限制的
💻 JAVA
字号:
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;
import java.io.*;
import java.awt.*;
import java.awt.event.* ;

class cryp{
	int keysize=1024;
	public cryp()
	{
		}
		
    public int keypair() throws Exception
    {//生成一个密钥对
    KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
    kpg.initialize(keysize);//
    KeyPair kp=kpg.genKeyPair();
    PublicKey pbkey=kp.getPublic();
    PrivateKey prkey=kp.getPrivate();
    
    FileOutputStream f1=new FileOutputStream("Skey_pub.dat");
    ObjectOutputStream b1=new ObjectOutputStream(f1);
     b1.writeObject(pbkey);
     b1.close();

    FileOutputStream f2=new FileOutputStream("Skey_priv.dat");
    ObjectOutputStream b2=new ObjectOutputStream(f2);
    b2.writeObject(prkey);
    b2.close();
    return(1);
  	}
   
	public int encrypt(TextArea form,String filename,String keyname) throws Exception
	{//加密
	File fileurl=new File(filename);
	File keyurl=new File(keyname);
	FileInputStream gf=new FileInputStream(fileurl);
	BufferedReader inm= 
      new BufferedReader(new InputStreamReader(gf));
    
    String s=inm.readLine();//读入明文
    form.setText("明文:\n"+s+"\n");
   	FileInputStream f=new FileInputStream(keyurl);//读入公钥
    ObjectInputStream b=new ObjectInputStream(f);
   	RSAPublicKey pbk=(RSAPublicKey)b.readObject( );
 	b.close();
   	BigInteger e=pbk.getPublicExponent();
   	BigInteger n=pbk.getModulus();
    
	byte ptext[]=s.getBytes("UTF8");
   	BigInteger m=new BigInteger(ptext);
	BigInteger c=m.modPow(e,n); //加密
   	String cs=c.toString( );
   	form.append("密文:\n"+cs+"\n");
    
   	BufferedWriter out= 
      	new BufferedWriter(new OutputStreamWriter(
        	new FileOutputStream("RSA_Secrit_file.dat")));
   	out.write(cs,0,cs.length( ));
    out.close( );
    return(1);
	}
    
    public int decrypt(TextArea form,String filename,String keyname) throws Exception
    {//解密  
    File fileurl=new File(filename);
	File keyurl=new File(keyname);
    BufferedReader inc= 
      new BufferedReader(new InputStreamReader(new FileInputStream(fileurl)));
    String ctext=inc.readLine();//读入密文
    form.setText("密文:\n"+ctext+"\n");
    inc.close();
    BigInteger cc=new BigInteger(ctext);
    FileInputStream ff=new FileInputStream(keyurl);//读入私钥
    ObjectInputStream bb=new ObjectInputStream(ff);
    RSAPrivateKey prk1=(RSAPrivateKey)bb.readObject( );
    bb.close();
    BigInteger dd=prk1.getPrivateExponent();
    BigInteger nn=prk1.getModulus();
    BigInteger mm=cc.modPow(dd,nn);//解密
     byte[] mt=mm.toByteArray();
     char[] mtext=new char[mt.length];
     for(int i=0;i<mt.length;i++)
     	mtext[i]=(char)mt[i];
   BufferedWriter out= 
      new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream("RSA_M_file.txt")));
    out.write(mtext,0,mtext.length);
    out.close( );
    BufferedReader inm=
      new BufferedReader(new InputStreamReader(new FileInputStream("RSA_M_file.txt")));
    String mstring=inm.readLine();
    form.append("明文:\n"+mstring+"\n");
   return(1);
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
class dialog extends Dialog implements ActionListener {
	Button yes=new Button("确定");
	Button no=new Button("取消");
	Button scan1=new Button("浏览");
	Button scan2=new Button("浏览");
	Label datafile=new Label("数据文件");
	Label keyfile=new Label("密钥文件");
	TextField datatext=new TextField(25);
	TextField keytext=new TextField(25);
	Panel pan1=new Panel();
	Panel pan2=new Panel();
	Panel pan3=new Panel();
	rsa parent;
	int tag;
	FileDialog fd;
	public dialog(Frame form, String title,int i)
	{
		super(form, title, true);
		parent=(rsa)form;
		tag=i;
		setLayout(new GridLayout(3,1));
		setSize(100,200);
		setResizable(false);
		datafile.setBackground(Color.lightGray);
		keyfile.setBackground(Color.lightGray);
		add(pan1);
		add(pan2);
		add(pan3);
		pan1.setLayout(new FlowLayout());
		pan1.add(datafile);
		pan1.add(datatext);
		pan1.add(scan1);
		pan2.setLayout(new FlowLayout());
		pan2.add(keyfile);
		pan2.add(keytext);
		pan2.add(scan2);
		pan3.setLayout(new FlowLayout());
		pan3.add(yes);
		pan3.add(no);
		yes.addActionListener(this);
		no.addActionListener(this);
		scan1.addActionListener(this);
		scan2.addActionListener(this);
		datatext.addActionListener(this);
		keytext.addActionListener(this);
		pack();
		show();
		}
	public void actionPerformed(ActionEvent event) {
		Object source=event.getSource();
		if(source==yes|source==datatext|source==keytext)
		{//按确定或者回车
			if((datatext.getText())==""|(keytext.getText())=="");
			else if(tag==0)
			{//加密
				parent.m_file=datatext.getText();
				parent.pb_key=keytext.getText();
				setVisible(false);}	
			else if(tag==1)
			{//解密
				parent.c_file=datatext.getText();
				parent.pr_key=keytext.getText();
				setVisible(false);}
		}
		if(source==no)this.setVisible(false);//按取消
		if(source==scan1)
		{//导入明文/密文
			fd=new FileDialog(this,"导入明文");
			fd.setVisible(true);
			datatext.setText(fd.getDirectory()+fd.getFile());}
		if(source==scan2)
		{//导入公钥/私钥
			fd=new FileDialog(this,"导入密文");
			fd.setVisible(true);
			keytext.setText(fd.getDirectory()+fd.getFile());
			}
		}
	}
/*class setkeysize extends Dialog implements ActionListener{
	Panel pan1=new Panel();
	Panel pan2=new Panel();
	Label l1=new Label("请输入密钥的长度:");
	Label l2=new Label("(512-2048)");
	TextField t=new TextField(20);
	Button yes=new Button("确定");
	Button no=new Button("取消");
	rsa parent;
	
	public setkeysize(Frame dw, String title)
	{
		super(dw, title, false);
		parent=(rsa)dw;
		setLayout(new GridLayout(2,1));
		setSize(100,200);
		setResizable(false);
		l1.setBackground(Color.lightGray);
		l2.setBackground(Color.lightGray);
		pan1.setLayout(new FlowLayout());
		pan1.add(l1);
		pan1.add(t);
		pan1.add(l2);
		pan2.setLayout(new FlowLayout());
		pan2.add(yes);
		pan2.add(no);
		add(pan1);
		add(pan2);
		pack();
		show();
		}
		public void actionPerformed(ActionEvent event) {
	    Object source = event.getSource();
        if ( (source == yes)|(source == t)) 
        {
        	//String str=t.getText();
        	//str.getChars(0,str.length(),ss,0);
        }
	}
}*/
public class rsa extends Frame implements ActionListener,WindowListener{
	
	 Button b1=new Button("生成密钥对");
     Button b2=new Button("加密文件");
     Button b3=new Button("解密文件");
     Panel pan = new Panel();
     TextArea view=new TextArea("",0,100,3);
     String m_file,c_file,pb_key,pr_key;
     int size;
     public rsa() 
	 {
	 super("Cryp_Easy");
     setLayout(new BorderLayout());
     setResizable(false);
     view.setBackground(Color.white);
  	 add(view,"North");
  	 view.setEditable(false);
  	 pan.setSize(150,50);
     pan.setLayout(new GridLayout(0,3));
     b1.addActionListener(this);
     b2.addActionListener(this);
     b3.addActionListener(this);
     pan.add(b1);
     pan.add(b2);
     pan.add(b3);
     add(pan,"South");
     pack();
     show();
  	}
  	public void actionPerformed(ActionEvent e){
  		int result;
		if(e.getSource()==b1)
		{//生成密钥对
			try
			{
				cryp sample=new cryp();
				result=sample.keypair();
				if(result==1)
				{
					view.setText("成功生成密钥对!\n公钥文件:Skey_pub.dat\n私钥文件:Skey_priv.dat\n");
					view.append("公钥文件用于对外发布,私钥文件必须保密,请妥善保管!");}
			}
			catch(Exception e1)
				{System.out.print(e1.toString());}
		}
		if(e.getSource()==b2)
		{//加密
			try
			{
				dialog choice=new dialog(this,"导入文件",0);
				cryp sample=new cryp();
				result=sample.encrypt(view,m_file,pb_key);
				if(result==1)
				{
					view.append("加密成功!\n生成的密文文件:RSA_Secrit_file.dat\n");}
			}
			catch(Exception e2)
				{view.append(e2.toString()+"\n加密未能完成!\n");}
		}
		if(e.getSource()==b3)
		{//解密
			try
			{
				dialog choice=new dialog(this,"导入文件",1);
				cryp sample=new cryp();
				result=sample.decrypt(view,c_file,pr_key);
				if(result==1)
				{
					view.append("解密成功!\n生成的明文文件:RSA_M_file.txt\n");}
			}
			catch(Exception e3)
			{view.append(e3.toString()+"\n解密未能完成!\n");}
		}
		}
		
	public void windowClosing(WindowEvent ex) { 
    	System.exit(0);}	
	public void windowClosed(WindowEvent e) { }
    public void windowOpened(WindowEvent e) { }
    public void windowIconified(WindowEvent e) { }
    public void windowDeiconified(WindowEvent e) { }
    public void windowActivated(WindowEvent e) { }
    public void windowDeactivated(WindowEvent e) { }
 	
    public static void main(String args[]) throws Exception{
  	 rsa window=new rsa();
  	 window.addWindowListener(window);
  	}
}

⌨️ 快捷键说明

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