password技术应用设计实践-安全信息传输系统(SITS)(用Java实现DES、RSA、MD5算法)

本系统包含五个模块,注冊模块、登录模块、RSA算法模块、DES算法模块、MD5算法模块。

这五个模块每个实现不同的功能。

注冊模块实现将username和password写入文件里,登录模块则负责将其读入而且推断其是否正确。RSA算法模块实现生成密钥对、加密和解密功能。

DES算法模块实现加密和解密功能。MD5算法模块是实现生成摘要的功能。

(1)、首先为注冊界面:

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)设计密钥:

(a) 在离线方式下。先产生两个足够大的强质数p、q;

(b) 令n=p*q。计算欧拉函数f(n)=(p-1)×(q-1);

(c) 选取一个与f(n)互素的奇数e,称e为公开指数。

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

(e) 舍弃p和q (但绝不能泄露) ,公开(n,e),公钥;

(f) 保密(n。d) 。私钥。

(2)加密:

对于明文M,用公钥 (n。e) 加密可得到密文C。

 

C = Me mod (n)

(3)解密:

对于密文C,用私钥(n,d)解密可得到明文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

上一篇:【密码学】MD5算法原理


下一篇:eclipse maven tomcat7 热部署