password技術應用設計實踐-安全信息傳輸系統(SITS)(用Java實現DES、RSA、MD5算法)

本系統包含五個模塊,註冊模塊、登陸模塊、RSA算法模塊、DES算法模塊、MD5算法模塊。java

這五個模塊每一個實現不一樣的功能。算法

註冊模塊實現將username和password寫入文件裏,登陸模塊則負責將其讀入並且推斷其是否正確。RSA算法模塊實現生成密鑰對、加密和解密功能。app

DES算法模塊實現加密和解密功能。MD5算法模塊是實現生成摘要的功能dom

(1)、首先爲註冊界面:ssh

package test;
import javax.swing.*;

import java.awt.*;   //導入必要的包
import java.awt.event.*;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;

public class regist {
    public static void main(String[] args){
        register a = new register();
       
    }
}
class register extends JFrame {
    JTextField jTextField ;//定義文本框組件
    JPasswordField jPasswordField;//定義password框組件
    
    public register(){
        
        jTextField = new JTextField(12);
        jPasswordField = new JPasswordField(12);
        JLabel jLabel1,jLabel2;
        JPanel jp1,jp2,jp3;
        JButton jb1,jb2; //建立button
        jLabel1 = new JLabel("username");
        jLabel2 = new JLabel("密    碼");
        jb1 = new JButton("註冊");
        jb2 = new JButton("取消");
        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();      
        
        jb1.addActionListener(  
             new ActionListener(){  
             public void actionPerformed(ActionEvent e) {  
                 Jb1_actionPerformed();
            }  
        });  
        jb2.addActionListener(  
            new ActionListener(){  
            public void actionPerformed(ActionEvent e) {  
                Jb2_actionPerformed();
            }  
        });
        //設置佈局
        this.setLayout(new GridLayout(3,1));
                    
        jp1.add(jLabel1); 
        jp1.add(jTextField);//第一塊麪板加入username和文本框 
                    
        jp2.add(jLabel2);
        jp2.add(jPasswordField);//第二塊面板加入password和password輸入框
                    
        jp3.add(jb1);
        jp3.add(jb2); //第三塊面板加入確認和取消
                    
        //jp3.setLayout(new FlowLayout());    //因爲JPanel默認佈局方式爲FlowLayout,因此可以註銷這段代碼.
        this.add(jp1);
        this.add(jp2);
        this.add(jp3);  //將三塊面板加入到登錄框上面
        //設置顯示
        this.setBounds(300, 300, 400, 300);
        //this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        this.setVisible(true);
        this.setTitle("用戶註冊界面");
        
    }
    //點擊註冊時發生的結果
    public void Jb1_actionPerformed( ){
        <span style="font-family:宋體;">//推斷username和password是否爲空</span>
        if(jTextField.getText().length()== 0){
            JOptionPane.showOptionDialog(this, "username不能爲空","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
            
        }
        else if(jPasswordField.getPassword().length== 0){
            JOptionPane.showOptionDialog(this, "password不能爲空","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
        }
        if((jTextField.getText().length()!= 0)&&(jPasswordField.getPassword().length!= 0)){
            /*System.out.println(jTextField.getText());
            System.out.println(jPasswordField.getPassword());*/
            String str1=jTextField.getText();
            String user = MD5.getMD5Str(str1);
            char[] str2 = jPasswordField.getPassword();
            String str = String.valueOf(str2);
            String pwd = MD5.getMD5Str(str);
            FileWriter writer;         
            try {            
                writer = new FileWriter("d:/abc.txt");
                writer.write(user); 
                writer.write(" ");
                writer.write(pwd);
                writer.flush();             
                writer.close();
            } catch (IOException e) { 
                e.printStackTrace();
            } 
            this.dispose();
           // new denglu();//進入登陸頁面
        }
    }
    
    //點擊取消,產生的結果
    public void Jb2_actionPerformed(){
        this.dispose();
       // new index();//進入主頁面
    }
                
}

註冊界面如圖所看到的,註冊後會在D盤生成一個abc.txt的文件,會將password用MD5加密後再存入文件裏。

(2)、第二步爲註冊界面:函數

註冊界面執行和登陸頁面類似。將username和password輸入後,將username和用MD5加密後的password與文件裏讀取的username和MD5加密後的password進行對照。假設相等則進入算法界面,不然,不能進入。佈局

package test;
import javax.swing.*;

import java.awt.*;   //導入必要的包
import java.awt.event.*;
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//主函數
public class login {
	public static void main(String[] args){
		denglu a = new denglu();

	}
}
//頁面顯示內容
class denglu extends JFrame {
	JTextField jTextField ;//定義文本框組件
	JPasswordField jPasswordField;//定義password框組件

	public denglu(){

		jTextField = new JTextField(12);
		jPasswordField = new JPasswordField(12);
		JLabel jLabel1,jLabel2;
		JPanel jp1,jp2,jp3;
		JButton jb1,jb2; //建立button
		jLabel1 = new JLabel("username");
		jLabel2 = new JLabel("密    碼");
		jb1 = new JButton("登陸");
		jb2 = new JButton("取消");
		jp1 = new JPanel();
		jp2 = new JPanel();
		jp3 = new JPanel();	  

		jb1.addActionListener(  
				new ActionListener(){  
					public void actionPerformed(ActionEvent e) {  
						Jb1_actionPerformed();
					}  
				});  
		jb2.addActionListener(  
				new ActionListener(){  
					public void actionPerformed(ActionEvent e) {  
						Jb2_actionPerformed();
					}  
				});
		//設置佈局
		this.setLayout(new GridLayout(3,1));

		jp1.add(jLabel1); 
		jp1.add(jTextField);//第一塊麪板加入username和文本框 

		jp2.add(jLabel2);
		jp2.add(jPasswordField);//第二塊面板加入password和password輸入框

		jp3.add(jb1);
		jp3.add(jb2); //第三塊面板加入確認和取消

		//        jp3.setLayout(new FlowLayout());    //因爲JPanel默認佈局方式爲FlowLayout,因此可以註銷這段代碼.
		this.add(jp1);
		this.add(jp2);
		this.add(jp3);  //將三塊面板加入到登錄框上面
		//設置顯示
		this.setBounds(300, 300, 400, 300);
		//this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		this.setVisible(true);
		this.setTitle("用戶登錄界面");
	}

	//控制登陸button的監聽器
	public void Jb1_actionPerformed( ){
		String name = jTextField.getText();
		String user = MD5.getMD5Str(name);
		//因爲password框獲取的值是亂碼,因此用String.valueOf將他轉換成字符串
		String password = String.valueOf(jPasswordField.getPassword());
		String pwd = MD5.getMD5Str(password);
		/*System.out.println("name="+name);
		System.out.println("password="+password);*/
		//推斷username和password是否爲空
		if(name.length()== 0){
			JOptionPane.showOptionDialog(this, "username不能爲空","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
		}else if(password.length() == 0){
			JOptionPane.showOptionDialog(this, "password不能爲空","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
		}
		//讀取文件
		if((name.length()!= 0)&&(password.length() != 0)){
			try { 
				Scanner in = new Scanner(new File("d:/abc.txt")); 
				String str = in.nextLine(); 
				String strr = str.trim(); 
				String[] abc = strr.split("[\\p{Space}]+"); //以空格來分
				String str1 = abc[0];//獲得的是文件裏的username
				String str2 = abc[1]; //獲得的是文件裏的password
				if(abc[1] != null){
					Pattern p = Pattern.compile("\n");
					Matcher m = p.matcher(abc[1]);
					str2 = m.replaceAll("");
				}
				//用來測試查看文件裏讀取的字符串與表單中的字符串是否相等
				/*System.out.println("比較username="+name.equals(str1));
				System.out.println("比較password="+password.equals(str2));*/

				//推斷輸入的username與文件裏獲得的username是否一樣
				if(user.equals(str1)){

					//推斷輸入的password與文件裏獲得的password是否一樣
					if(pwd.equals(str2)){
						this.dispose();
						new Algorithm();
					}else{
						JOptionPane.showOptionDialog(this, "password錯誤","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
					}
				}else{
					JOptionPane.showOptionDialog(this, "username錯誤","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
				}
			} catch (FileNotFoundException e) { 
				e.printStackTrace(); 
			}
		}

	}
	//控制取消button的監聽器
	public void Jb2_actionPerformed(){
		this.dispose();
		//new index();//<span style="font-family:宋體;">返回主頁面</span> 
	}

}


(3)、RSA算法

1)設計密鑰:post

(a) 在離線方式下。先產生兩個足夠大的強質數pqthis

(b) n=pq。計算歐拉函數f(n)=(p-1)×(q-1)加密

(c) 選取一個與f(n)互素的奇數e,稱e爲公開指數。

(d) 依據e×d=1 mod(f(n))。找出d

(e) 捨棄p(但毫不能泄露) ,公開(ne),公鑰;

(f) 保密(nd) 。私鑰。

2)加密:

   對於明文M,用公鑰 (ne) 加密可獲得密文C

 

         C = Me mod (n)

3)解密:

   對於密文C,用私鑰(nd)解密可獲得明文M

       M = Cd mod (n) 

首先生成公私密鑰對的代碼:

package test;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;   

import javax.swing.*;

import java.awt.*;   //導入必要的包
import java.awt.event.*;
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class rsakeypair {  
		
	public static void main(String []args)throws Exception { 
		
		new keypair();
	}  
}


class keypair extends JFrame{
	JTextField t1,t2,t3;
	JButton b1,b2,b3;
	JLabel l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,l13; 
	JPanel p1,p2,p3,p4,p5,p6;
	public static  long p; 
	public static long q; 
	public static long e;
	public static long d; 
	public static long n; 
	public static long m;     
	
	//求最大公約數  
	public long gcd(long a,long b) {  
		long gcd; 
		if(b==0) gcd=a; 
		else  gcd=gcd(b,a%b);  
		return gcd;  
	}
	
	public long getd(long e ,long m) {  
		long value=1; 
		long d = 0;
		for(int i=1;;i++) {  
			value=i * m+1;  
			/*System.out.println("value:  "+value); */ 
			if((value%e==0)&& (value/e < m)) {  
				d= value/e; 
				break;
			} 
		}  
		return d;
	}
	//推斷是否爲素數  
		public boolean primenumber(long t) {  
			long k=0;  
			k=(long)Math.sqrt((double)t); 
			boolean flag=true;  
			outer:for(int i=2;i<=k;i++) {  
				if((t%i)==0) {  
					flag = false; break outer; 
				} 
			}  
			return flag; 
		} 
		
	public keypair(){
		t1 = new JTextField(12);
		t2 = new JTextField(12);
		t3 = new JTextField(12);
		b1 = new JButton("生成公鑰");
		b2 = new JButton("生成私鑰");
		b3 = new JButton("返回");
		l1 = new JLabel("輸入p:");
		l2 = new JLabel("輸入q:");
		l3 = new JLabel("輸入e:");
		l4 = new JLabel();
		l5 = new JLabel();
		l6 = new JLabel("(");
		l7 = new JLabel(",");
		l8 = new JLabel(")");
		l9 = new JLabel("(");
		l10 = new JLabel(",");
		l11 = new JLabel(")");
		l12 = new JLabel();
		l13 = new JLabel();
		p1 = new JPanel();
		p2 = new JPanel();
		p3 = new JPanel();
		p4 = new JPanel();
		p5 = new JPanel();
		p6 = new JPanel();
		
		this.setLayout(new GridLayout(6,1));
		
		p1.add(l1);
		p1.add(t1);
		
		p2.add(l2);
		p2.add(t2);
		
		p3.add(l3);
		p3.add(t3);
		
		p4.add(b1);
		p4.add(l6);
		p4.add(l4);
		p4.add(l7);
		p4.add(l12);
		p4.add(l8);
		
		p5.add(b2);
		p5.add(l9);
		p5.add(l13);
		p5.add(l10);
		p5.add(l5);
		p5.add(l11);
		
		p6.add(b3);
				
		b1.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 B1_actionPerformed();
					 
				}  
		});
		b2.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 B2_actionPerformed();
				}  
		});
		b3.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 B3_actionPerformed(); 
				}  
		});
		
		this.add(p1);
		this.add(p2);
		this.add(p3);
		this.add(p4);
		this.add(p5);
		this.add(p6);
		this.setBounds(300, 300, 400, 300);
		//this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.setVisible(true);
		this.setTitle("生成密鑰對");
	}
	public void B1_actionPerformed(){
		p = Integer.parseInt(t1.getText());
		q = Integer.parseInt(t2.getText());
		e = Integer.parseInt(t3.getText());
		n = p * q ;
		m = (p-1)*(q-1);
		d = getd(e,m);
		String x = String.valueOf(n);
		String y = String.valueOf(e);
		
		if(!primenumber(p)){
			JOptionPane.showOptionDialog(this, "輸入p不合法","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
		}else{
			if(!primenumber(q)){
				JOptionPane.showOptionDialog(this, "輸入q不合法","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
			}else{
				if((e >= m) || (gcd (m,e)!=1)){
					JOptionPane.showOptionDialog(this, "輸入e不合法","錯誤信息", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
				}else{
					l4.setText(x);
					l12.setText(y);
				}
			}
		}
		
	}
	public void B2_actionPerformed(){
		p = Integer.parseInt(t1.getText());
		q = Integer.parseInt(t2.getText());
		e = Integer.parseInt(t3.getText());
		n = p * q ;
		m = (p-1)*(q-1);
		d = getd(e,m);
		String x = String.valueOf(n);
		String y = String.valueOf(d);
		l13.setText(x);
		l5.setText(y);
	}
	
	public void B3_actionPerformed(){
		this.dispose();
		 new rsashow();
	}
	
}



RSA算法中的加密算法:

package test;

import java.awt.*;   //導入必要的包
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.InputStreamReader;
import java.math.*;
import java.util.Scanner; 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

public class rsaencryption {
	public static void main (String args[]){
		new encryption();
	}
	
}

class encryption extends JFrame{
	JTextField t1,t2,t3;
	JButton b1,b2;
	JLabel l1,l2,l3,l4; 
	JPanel p1,p2,p3,p4,p5;
	public static BigInteger n ;
	public static int e;
	public static BigInteger ming;
	
	/*
	 * A測試數據:
	 * p=13171
	 * q= 35911
	 * n = 472983781
	 * e= 17149
	 * d=281295349
	 * 明文:88888888
	 * 密文:347002949
	 * qq號:348257309
	 * qq號加密後:410467256
	 */
	
	//加密、解密計算  
	public BigInteger colum(BigInteger y,BigInteger n,int key) {  
		BigInteger mul= BigInteger.ONE ;
		y = y.remainder(n);
		while(key > 0){
			if(key %2 == 1){
				mul = mul.multiply(y).remainder(n);
			}
			key = key/2;
			y = y.multiply(y).remainder(n);
		}
		return mul; 
	}    
   
	public encryption(){
		t1 = new JTextField(12);
		t2 = new JTextField(12);
		t3 = new JTextField(12);
		b1 = new JButton("加密");
		b2 = new JButton("返回");
		l1 = new JLabel("輸入公鑰中的第一個數n:");
		l2 = new JLabel("輸入公鑰中的第二個數e:");
		l3 = new JLabel("輸入明文:");
		l4 = new JLabel();
		
		p1 = new JPanel();
		p2 = new JPanel();
		p3 = new JPanel();
		p4 = new JPanel();
		p5 = new JPanel();
		
		this.setLayout(new GridLayout(5,1));
		
		p1.add(l1);
		p1.add(t1);
		
		p2.add(l2);
		p2.add(t2);
		
		p3.add(l3);
		p3.add(t3);
		
		p4.add(b1);
		p4.add(l4);
		
		p5.add(b2);
		
		b1.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 B1_actionPerformed();
					 
				}  
		});
		b2.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 B2_actionPerformed();
				}  
		});
		
		this.add(p1);
		this.add(p2);
		this.add(p3);
		this.add(p4);
		this.add(p5);
		
		this.setBounds(300, 300, 400, 300);
		//this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.setVisible(true);
		this.setTitle("加密算法");
	}
	
	public void B1_actionPerformed(){
		long a = Integer.parseInt(t1.getText());
		long c = Integer.parseInt(t3.getText());
		n = BigInteger.valueOf(a);
		e = Integer.parseInt(t2.getText());
		ming = BigInteger.valueOf(c);
		BigInteger secretword=colum(ming,n,e);
		String x = String.valueOf(secretword);
		l4.setText(x);
	}
	
	public void B2_actionPerformed(){
		this.dispose();
		new rsashow();
	}
}

RSA算法中解密算法的代碼:

package test;

import java.awt.*;   //導入必要的包
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Scanner; 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

public class rsadecrypt {
	public static void main (String args[]){
		new decrypt();
	}
	
}

class decrypt extends JFrame{
	JTextField t1,t2,t3;
	JButton b1,b2;
	JLabel l1,l2,l3,l4; 
	JPanel p1,p2,p3,p4,p5;
	public static BigInteger n ;
	public static int d;
	public static BigInteger mi;
	/*
	 * B測試數據:
	 p:17327
	 q:11311
	 n:195985697
	 e:73559
	 d:153728219
	 明文:88888888
	 密文:141349150
	 */
	
	
	//加密、解密計算  
	public BigInteger colum(BigInteger y,BigInteger n,int key) {  
		BigInteger mul= BigInteger.ONE ;
		y = y.remainder(n);
		while(key > 0){
			if(key %2 == 1){
				mul = mul.multiply(y).remainder(n);
			}
			key = key/2;
			y = y.multiply(y).remainder(n);
		}
		return mul; 
	}    
   
	public decrypt(){
		t1 = new JTextField(12);
		t2 = new JTextField(12);
		t3 = new JTextField(12);
		b1 = new JButton("解密");
		b2 = new JButton("返回");
		l1 = new JLabel("輸入私鑰中的第一個數n:");
		l2 = new JLabel("輸入私鑰中的第二個數d:");
		l3 = new JLabel("輸入密文:");
		l4 = new JLabel();
		
		p1 = new JPanel();
		p2 = new JPanel();
		p3 = new JPanel();
		p4 = new JPanel();
		p5 = new JPanel();
		
		this.setLayout(new GridLayout(5,1));
		
		p1.add(l1);
		p1.add(t1);
		
		p2.add(l2);
		p2.add(t2);
		
		p3.add(l3);
		p3.add(t3);
		
		p4.add(b1);
		p4.add(l4);
		
		p5.add(b2);
		
		b1.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 B1_actionPerformed();
					 
				}  
		});
		b2.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 B2_actionPerformed();
				}  
		});
		
		this.add(p1);
		this.add(p2);
		this.add(p3);
		this.add(p4);
		this.add(p5);
		
		this.setBounds(300, 300, 400, 300);
		//this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.setVisible(true);
		this.setTitle("解密算法");
	}
	
	public void B1_actionPerformed(){
		long a = Integer.parseInt(t1.getText());
		//long b = Integer.parseInt(t2.getText());
		long c = Integer.parseInt(t3.getText());
		n = BigInteger.valueOf(a);
		d = Integer.parseInt(t2.getText());
		mi = BigInteger.valueOf(c);
		BigInteger word=colum(mi,n,d);
		String x = String.valueOf(word);
		l4.setText(x);
	}
	
	public void B2_actionPerformed(){
		this.dispose();
		new rsashow();
	}
}

(4)、DES算法

package test;

//加密隨機類
import java.security.SecureRandom;




//提供加密和解密加密
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.swing.*;

import java.awt.*;   //導入必要的包
import java.awt.event.*;

public class destest {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO 本身主動生成的方法存根
        //待加密內容
       /* String str = "kale123456789";
        //密碼。長度要是8的倍數
        String password = "12345678";
        byte[] result = null;
        try{
            result = DES.desLock(str.getBytes(),password);
            System.out.println("加密後內容爲:"+new String(result));
        }
        catch(Exception e){
            System.out.println("加密失敗。");
        }
        
        //解密
        try {
            byte[] unLockResult = DES.desUnclock(result, password);
            System.out.println("解密後內容爲:"+new String(unLockResult));
        } 
        catch (Exception e1) {
            //e1.printStackTrace();
            System.out.println("密鑰錯誤。沒法解密!");
        }*/
    	new desshow();
    }


}

class desshow extends JFrame{
	JTextField t1,t2;
	JButton b1,b2,b3;
	JLabel l1,l2,l3,l4,l5,l6; 
	JPanel p1,p2,p3,p4,p5;
	public desshow(){
		t1 = new JTextField(12);
		t2 = new JTextField(12);
		b1 = new JButton("加密");
		b2 = new JButton("解密");
		b3 = new JButton("返回");
		l1 = new JLabel("輸入明文:");
		l2 = new JLabel("輸入密鑰:");//加密密鑰和解密密鑰(加密密鑰和解密密鑰是同樣的)
		l3 = new JLabel("加密後的結果:");
		l4 = new JLabel();
		l5 = new JLabel("解密後的結果:");
		l6 = new JLabel();
		
		p1 = new JPanel();
		p2 = new JPanel();
		p3 = new JPanel();
		p4 = new JPanel();
		p5 = new JPanel();
		
		this.setLayout(new GridLayout(5,1));
		
		p1.add(l1);
		p1.add(t1);
		p2.add(l2);
		p2.add(t2);
		
		p3.add(b1);
		p3.add(l3);
		p3.add(l4);
		
		p4.add(b2);
		p4.add(l5);
		p4.add(l6);
		
		p5.add(b3);
		
		b1.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 J1_actionPerformed();
				}  
		});
		b2.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 J2_actionPerformed();
				}  
		});
		b3.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 J3_actionPerformed();
				}  
		});
		
		this.add(p1);
		this.add(p2);
		this.add(p3);
		this.add(p4);
		this.add(p5);
		this.setBounds(100, 100, 300, 300);
		//this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.setVisible(true);
		this.setTitle("des算法");
	}
	//待加密內容
	String str ;
    //密碼,長度要是8的倍數
   String password ;
   public byte[] result = null;
   public void J1_actionPerformed(){
		str = t1.getText();
		password = t2.getText();
        
        try{
            result = DES.desLock(str.getBytes(),password);
            //System.out.println("加密後內容爲:"+new String(result));
            l4.setText(new String(result));
        }
        catch(Exception e){
            //System.out.println("加密失敗!");
        	l4.setText("加密失敗");
        }
	}
	//byte[] result2= DES.desLock(str.getBytes(),password);
	public void J2_actionPerformed(){
		try {
            byte[] unLockResult = DES.desUnclock(result, password);
            //System.out.println("解密後內容爲:"+new String(unLockResult));
            l6.setText(new String(unLockResult));
        } 
        catch (Exception e1) {
            //e1.printStackTrace();
            //System.out.println("密鑰錯誤,沒法解密!");
        	l6.setText("密鑰錯誤。沒法解密。");
        }
	}
	public void J3_actionPerformed(){
		this.dispose();
		new Algorithm();
	}
}

/*
 * DES加密介紹
    DES是一種對稱加密算法,所謂對稱加密算法即:加密和解密使用一樣密鑰的算法。

DES加密算法出自IBM的研究。後來被美國政府正式採用,以後開始普遍流傳,但是近些年使用愈來愈少。 因爲DES使用56位密鑰,以現代計算能力。24小時內就能夠被破解。儘管如此,在某些簡單應用中,咱們仍是可 以 使用DES加密算法,本文簡單解說DES的JAVA實現。 */ class DES{ /** * 加密過程,密鑰長度都必須是8的倍數 * @param datasource * @param password * @return 加密後的結果 */ public static byte[] desLock(byte[] datasource, String password) { try{ SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(password.getBytes()); //建立一個密匙工廠。而後用它把DESKeySpec轉換成 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); //Cipher對象實際完畢加密操做 Cipher cipher = Cipher.getInstance("DES"); //用密匙初始化Cipher對象 cipher.init(Cipher.ENCRYPT_MODE, securekey, random); //現在。獲取數據並加密 //正式運行加密操做 return cipher.doFinal(datasource); }catch(Throwable e){ e.printStackTrace(); } return null; } /** * 解密過程,密鑰長度都必須是8的倍數 * @param src * @param password * @return 解密後的內容 * @throws Exception */ public static byte[] desUnclock(byte[] src, String password) throws Exception { // DES算法要求有一個可信任的隨機數源 SecureRandom random = new SecureRandom(); // 建立一個DESKeySpec對象 DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 建立一個密匙工廠 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // 將DESKeySpec對象轉換成SecretKey對象 SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher對象實際完畢解密操做 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher對象 cipher.init(Cipher.DECRYPT_MODE, securekey, random); // 真正開始解密操做 return cipher.doFinal(src); } }


(5)、MD5算法

package test;

import javax.swing.*;

import java.awt.*;   //導入必要的包
import java.awt.event.*;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.swing.JTextField;

/*
 * 數據:helloworld
 * 摘要:38a57032085441e7
 * qq號:348257309
 * * qq號加密後:410467256
 * */
public class md5test {

    /**
     * @param args
     */
    public static void main(String[] args) {
       /* String password = "123456789";
        String result = MD5.getMD5Str(password);
        System.out.println(result.toLowerCase());*/
    	new md5show();
    }

}

class md5show extends JFrame{
	JTextField jTextField = new JTextField(12);
	JLabel jl1,jl2 ;
	JPanel p1,p2,p3;
	JButton j1,j2;
	public  md5show(){
		
	    jl1= new JLabel("請輸入要生成摘要的數據:");
	    jl2 =new JLabel();
	    p1 = new JPanel();
	    p2 = new JPanel();
	    p3 = new JPanel();
	    
	    this.setLayout(new GridLayout(3,1));
		p1.add(jl1);
		p1.add(jTextField);
		
		j1 = new JButton("生成摘要");
		j2 = new JButton("返回");
		p2.add(j1);
		p2.add(jl2);
		
		p3.add(j2);
		
		j1.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 J1_actionPerformed();
				}  
		});
		j2.addActionListener(  
				 new ActionListener(){  
				 public void actionPerformed(ActionEvent e) {  
					 J2_actionPerformed();
				}  
		});
		this.add(p1);
		this.add(p2);
		this.add(p3);
		this.setBounds(300, 300, 400, 300);
		//this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.setVisible(true);
		this.setTitle("MD5算法");
		
	}
	
	public void J1_actionPerformed(){
		String password = jTextField.getText();
        String result = MD5.getMD5Str(password);
        jl2.setText(result.toLowerCase());
	}
	public void J2_actionPerformed(){
		this.dispose();
		new Algorithm();
	}
	
}

class MD5 {  
    /*
       * MD5加密
       */
      public static String getMD5Str(String str) {     
          MessageDigest messageDigest = null;     
       
          try {     
              messageDigest = MessageDigest.getInstance("MD5");     
       
              messageDigest.reset();     
       
              messageDigest.update(str.getBytes("UTF-8"));     
          } catch (NoSuchAlgorithmException e) {     
              System.out.println("NoSuchAlgorithmException caught!");     
              System.exit(-1);     
          } catch (UnsupportedEncodingException e) {     
              e.printStackTrace();     
          }     
       
          byte[] byteArray = messageDigest.digest();     
       
          StringBuffer md5StrBuff = new StringBuffer();     
          
          for (int i = 0; i < byteArray.length; i++) {                 
              if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)     
                  md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));     
              else     
                  md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));     
          }     
          //16位加密,從第9位到25位
          return md5StrBuff.substring(8, 24).toString().toUpperCase();    
      }  
}



源碼:

http://download.csdn.net/detail/bluedream1219/8906279

相關文章
相關標籤/搜索