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

📄 proj2.java

📁 RSA加密/解密 (java实现)
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.math.*;
import java.security.*;

class Proj2 
{
	public static void main(String[] args) 
	{
		new Win("RSA Proj");
	}
}

class Win extends Frame implements ActionListener
{
	Button openFile,about,runEncrypt,runDecrypt;
	Label openFileInfo,status;
	Box baseBox ,boxV1,boxV2, baseBox2;
	TextField textp,textq,textd,texte,textdd,textdn,textn;
	Button nextp,nextq,nexte;
	Button setp,setq,sete;
	FileDialog filedialog;
	RSA rsa;

	Win(String s) {
		super(s);
		rsa = new RSA();
		Panel pNorth=new Panel();
		openFile = new Button("Choose File");
		openFileInfo = new Label("     Please choose input file name.");
		pNorth.setLayout(new BorderLayout());
		pNorth.add(openFile,BorderLayout.WEST);
		pNorth.add(openFileInfo,BorderLayout.CENTER);
		add(pNorth, BorderLayout.NORTH);

		Panel pCenter = new Panel();
		pCenter.setLayout(new BorderLayout());

		Panel pEncrypt = new Panel();
		pEncrypt.setLayout(new BorderLayout());

		Panel pnEncrypt = new Panel();
		pnEncrypt.setLayout(new BorderLayout());
		runEncrypt = new Button("Run");
		pnEncrypt.add(new Label("Encrypt"),BorderLayout.WEST);
		pnEncrypt.add(runEncrypt,BorderLayout.EAST);
		pEncrypt.add(pnEncrypt,BorderLayout.NORTH);

		textp = new TextField();
		textq = new TextField();
		texte = new TextField();
		textd = new TextField();
		textn = new TextField();

		nextp = new Button("Next");
		nextq = new Button("Next");
		nexte = new Button("Next");

		setp = new Button("Set");
		setq = new Button("Set");
		sete = new Button("Set");

		Panel pP = new Panel();
		pP.setLayout(new BorderLayout());
		pP.add(new Label("p"),BorderLayout.WEST);
		pP.add(textp,BorderLayout.CENTER);
		Panel pPeast = new Panel();
		pPeast.setLayout(new FlowLayout());
		pPeast.add(nextp);
		pPeast.add(setp);
		pP.add(pPeast,BorderLayout.EAST);
		

		Panel pQ = new Panel();
		pQ.setLayout(new BorderLayout());
		pQ.add(new Label("q"),BorderLayout.WEST);
		pQ.add(textq,BorderLayout.CENTER);
		Panel pQeast = new Panel();
		pQeast.setLayout(new FlowLayout());
		pQeast.add(nextq);
		pQeast.add(setq);
		pQ.add(pQeast,BorderLayout.EAST);

		Panel pE = new Panel();
		pE.setLayout(new BorderLayout());
		pE.add(new Label("e"),BorderLayout.WEST);
		pE.add(texte,BorderLayout.CENTER);
		Panel pEeast = new Panel();
		pEeast.setLayout(new FlowLayout());
		pEeast.add(nexte);
		pEeast.add(sete);
		pE.add(pEeast,BorderLayout.EAST);

		Panel pD = new Panel();
		pD.setLayout(new BorderLayout());
		pD.add(new Label("d"),BorderLayout.WEST);
		pD.add(textd,BorderLayout.CENTER);
		textd.setEditable(false);

		Panel pN = new Panel();
		pN.setLayout(new BorderLayout());
		pN.add(new Label("n"),BorderLayout.WEST);
		pN.add(textn,BorderLayout.CENTER);
		textn.setEditable(false);

		boxV1=Box.createVerticalBox();
	    boxV1.add(Box.createVerticalStrut(15));
	    boxV1.add(pP);
	    boxV1.add(Box.createVerticalStrut(8));
	    boxV1.add(pQ);
	    boxV1.add(Box.createVerticalStrut(8));
	    boxV1.add(pE);
		boxV1.add(Box.createVerticalStrut(8));
	    boxV1.add(pD);
		boxV1.add(Box.createVerticalStrut(8));
	    boxV1.add(pN);
		boxV1.add(Box.createVerticalStrut(20));

		baseBox=Box.createHorizontalBox();
		baseBox.add(boxV1);

		pEncrypt.add(baseBox,BorderLayout.CENTER); 

		pCenter.add(pEncrypt,BorderLayout.NORTH);

		Panel pDecrypt = new Panel();
		pDecrypt.setLayout(new BorderLayout());

		Panel pnDecrypt = new Panel();
		pnDecrypt.setLayout(new BorderLayout());
		runDecrypt = new Button("Run");
		pnDecrypt.add(new Label("Decrypt"),BorderLayout.WEST);
		pnDecrypt.add(runDecrypt,BorderLayout.EAST);
		pDecrypt.add(pnDecrypt,BorderLayout.NORTH);

		textdd = new TextField();
		textdn = new TextField();

		Panel pDD = new Panel();
		pDD.setLayout(new BorderLayout());
		pDD.add(new Label("d"),BorderLayout.WEST);
		pDD.add(textdd,BorderLayout.CENTER);
		
		Panel pDN = new Panel();
		pDN.setLayout(new BorderLayout());
		pDN.add(new Label("n"),BorderLayout.WEST);
		pDN.add(textdn,BorderLayout.CENTER);

		boxV2=Box.createVerticalBox();
	    boxV2.add(Box.createVerticalStrut(15));
	    boxV2.add(pDD);
		boxV2.add(Box.createVerticalStrut(8));
	    boxV2.add(pDN);
	    boxV2.add(Box.createVerticalStrut(20));
		baseBox2=Box.createHorizontalBox();
		baseBox2.add(boxV2);

		pDecrypt.add(baseBox2,BorderLayout.SOUTH); 

		pCenter.add(pDecrypt,BorderLayout.SOUTH);
		add(pCenter,BorderLayout.CENTER);

		Panel pSouth = new Panel();
		pSouth.setLayout(new BorderLayout());

		about = new Button("About");
		status = new Label("Please choose input file.                 ");
		pSouth.add(status,BorderLayout.CENTER);
		pSouth.add(about, BorderLayout.EAST);
		add(pSouth,BorderLayout.SOUTH);
		
		setBounds(100,100,400,440); 
		setVisible(true);
		
		addWindowListener(new WindowAdapter() 
			{public void windowClosing(WindowEvent e)
				  { setVisible(false);System.exit(0);
				  }
			});
		validate();
		about.addActionListener(this);
		openFile.addActionListener(this);
		filedialog = new FileDialog(this, "Choose input file",FileDialog.LOAD);
		filedialog.setVisible(false);
		filedialog.addWindowListener(new WindowAdapter() 
			{public void windowClosing(WindowEvent e)
				  { setVisible(false);System.exit(0);
				  }
		});

		textp.setText(rsa.getP());
		textq.setText(rsa.getQ());
		textd.setText(rsa.getD());
		texte.setText(rsa.getE());
		textdd.setText(rsa.getD());
		textdn.setText(rsa.getN());
		textn.setText(rsa.getN());
		nextp.addActionListener(this);
		nextq.addActionListener(this);
		nexte.addActionListener(this);
		setp.addActionListener(this);
		setq.addActionListener(this);
		sete.addActionListener(this);
		runEncrypt.addActionListener(this);
		runDecrypt.addActionListener(this);
	}

	void reload() {
		textp.setText(rsa.getP());
		textq.setText(rsa.getQ());
		textd.setText(rsa.getD());
		texte.setText(rsa.getE());
		textdd.setText(rsa.getD());
		textdn.setText(rsa.getN());
		textn.setText(rsa.getN());
	}

	public void actionPerformed(ActionEvent e) { 
		if (e.getSource()==about)
		{
			JOptionPane.showMessageDialog(this,  "UG Course: Information Security, Proj 2: RSA\nby ZOU,Tao (0572194)",  "About", JOptionPane.INFORMATION_MESSAGE); 
		}
		if (e.getSource() == openFile)
		{
			filedialog.setVisible(true);
			String name = filedialog.getFile();
			if (name!=null)
			{
				openFileInfo.setText(name);
				status.setText("Please Run Encrypt or Decrypt.");
			}
		}
		if (e.getSource()== nextp)
		{
			rsa.nextP();
			reload();
		}
		if (e.getSource()== nextq)
		{
			rsa.nextQ();
			reload();
		}
		if (e.getSource()== nexte)
		{
			rsa.nextE();
			reload();
		}
		if (e.getSource() == setp)
		{
			if (!rsa.setP(textp.getText()))
			{
				status.setText("Error in input p!");	
			}
			else status.setText("Set p successfully!");
			reload();
		}
		if (e.getSource() == setq)
		{
			if (!rsa.setQ(textq.getText()))
			{
				status.setText("Error in input q!");	
			}
			else status.setText("Set q successfully!");
			reload();
		}
		if (e.getSource() == sete)
		{
			if (!rsa.setE(texte.getText()))
			{
				status.setText("Error in input e!");	
			}
			else 
				status.setText("Set e successfully!");
			reload();
		}
		if (e.getSource() == runEncrypt)
		{
			status.setText(rsa.Encrypt(filedialog.getDirectory()+filedialog.getFile()));
		}
		if (e.getSource()== runDecrypt)
		{
			status.setText(rsa.Decrypt(filedialog.getDirectory()+filedialog.getFile(), new BigInteger(textdd.getText()), new BigInteger(textdn.getText())));
		}
	}
}

class RSA {
 BigInteger p,q,e,d,n,phi_n;
 SecureRandom random = new SecureRandom();
 BigInteger BigTwo;

 RSA(){
	BigTwo = new BigInteger("2");
	p = BigInteger.probablePrime(64,random);
	q = BigInteger.probablePrime(64,random);
	n = p.multiply(q);
	phi_n = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
	do
	{
		 e = BigInteger.probablePrime(50,random);
	}
	while (e.gcd(phi_n).compareTo(BigInteger.ONE) != 0 || e.compareTo(p) != -1 || e.compareTo(q) != -1);

	d = e.modInverse(phi_n);
 }

 boolean update() {
	n = p.multiply(q);
	phi_n = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
	int time = 0;
	while (e.gcd(phi_n).compareTo(BigInteger.ONE) != 0 || e.compareTo(p) != -1 || e.compareTo(q) != -1) {
		e = BigInteger.probablePrime(50,random);
		time ++ ;
		if (time > 1000)return false;
	}
    d = e.modInverse(phi_n);
	return true;
 }

 void nextP() {
	p = BigInteger.probablePrime(64,random);
	update();
 }

 void nextQ() {
	q = BigInteger.probablePrime(64,random);
	update();
 }

 boolean setP(String t) {
	 p = new BigInteger(t);
	 return update();
 }

 boolean setQ(String t) {
	 q = new BigInteger(t);
	 return update();
 }

 boolean setE(String t) {
	 try
	 {
		 e = new BigInteger(t);
		 d = e.modInverse(phi_n);
	 }
	 catch (ArithmeticException ee)
	 {
		 return false;
	 }
	 return true;
 }

 void nextE() {
	do
	{
		 e = BigInteger.probablePrime(50,random);
	}
	while (e.gcd(phi_n).compareTo(BigInteger.ONE) != 0 || e.compareTo(p) != -1 || e.compareTo(q) != -1);
    d = e.modInverse(phi_n);
 }

 String getP() {
	 return p.toString();
 }

 String getQ() {
	 return q.toString();
 }

 String getE() {
	 return e.toString();
 }

 String getD() {
	 return d.toString();
 }

 String getN() {
	 return n.toString();
 }

 String Encrypt(String filename) {
	FileInputStream istream;
	FileOutputStream ostream;
	try
	{
		istream = new FileInputStream(filename);	
	    ostream = new FileOutputStream("Encrypt.txt");
	}
	catch (FileNotFoundException e)
	{
		return "File not found.";
	}


	byte c[] = new byte[100];
	byte o[] = new byte[128];
	int len = 0;
	while (true)
	{
		int count = -1;
		try
		{
			count = istream.read(c, 0, 100);			
		}
		catch (IOException e) {}

		if (count == -1) break;
		
		BigInteger sum = new BigInteger("0");

		for (int i = 0; i < count; i++)
		{
			if (c[i] == '1') sum = sum.add(BigInteger.ONE);
			if (i < (count -1) )
			{
				sum = sum.multiply(BigTwo);
			}
		}

		sum = sum.modPow(e,n);

		for (int i = 127; i >= 0; i-- )
		{
			if (sum.mod(BigTwo).compareTo(BigInteger.ONE) == 0) o[i]='1';
			else o[i]='0';
			sum = sum.divide(BigTwo);
		}

		try
		{
			ostream.write(o,0,128);
		}
		catch (IOException e){}
	
		len = count;
		if (count != 100) break;
	}

	for (int i = 9; i >= 0; i-- )
	{
		if (len % 2 == 1) {
			o[i]='1';
		}
		else 
			o[i]='0';
		len/=2;
	}
	
	try
	{
		ostream.write(o,0,10);
		ostream.close();
	}

	catch (IOException e){}
	return "The result is in Encrypt.txt.";
 }

 String Decrypt(String filename, BigInteger d, BigInteger n) {
	FileInputStream istream;
	FileOutputStream ostream;
	try
	{
		istream = new FileInputStream(filename);	
	    ostream = new FileOutputStream("Decrypt.txt");
	}
	catch (FileNotFoundException ee)
	{
		return "File not found.";
	}

	byte c[] = new byte[128];
	byte o[] = new byte[100];
	byte o1[] = new byte[100];
	boolean first = true;
	while (true)
	{
		int count = -1;
		try
		{
			count = istream.read(c, 0, 128);			
		}
		catch (IOException ee) {}

		if (count == -1) break;

		BigInteger sum = new BigInteger("0");

		if (count != 128)
		{
			int len = 0;
			for (int i = 0; i < count ; i++)
			{
				if (c[i] == '1') len = len+1;
				if (i < (count - 1))
					len *= 2;
			}
			try
			{
				ostream.write(o1,100 - len, len);
			}
			catch (IOException ee){}

			break;
		}

		for (int i = 0; i < 128; i++)
		{
			if (c[i] == '1') sum = sum.add(BigInteger.ONE);
			if (i < 127)
				sum = sum.multiply(BigTwo);
		}
		sum = sum.modPow(d,n);

		for (int i = 99; i >= 0; i-- )
		{
			if (sum.mod(BigTwo).compareTo(BigInteger.ONE) == 0) o[i]='1';
			else o[i]='0';
			sum = sum.divide(BigTwo);
		}

		if (first) first = false;
		else {
			try
			{
				ostream.write(o1,0,100);
			}
			catch (IOException ee){}
		}

		for (int i = 0; i < 100 ; i++)
		{
			o1[i] = o[i];
		}
	}

	try
	{
		ostream.close();
	}
	catch (IOException ee){}
	return "The result is in Decrypt.txt.";
 }
}

⌨️ 快捷键说明

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