第六章:md5混合加密

来源:互联网 发布:cnki中国期刊数据库 编辑:程序博客网 时间:2024/05/29 18:42

一、md5混合加密:

首先我们创建java工程:data_15_08_01。这里为了方便,将所有类写在一个包(cn.edu.hpu.acm.demo02)下面,真正web开发,不应该这样乱放类,不过这里为了方便就这样吧!
其次我们需要调用系统自带的md5算法,这个算法windows里都有,貌似Linux也有,具体不知道!
代码如下:
</pre><pre name="code" class="java">package cn.edu.hpu.acm.demo02;import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5util {/** * 使用md5的算法进行加密 */public static String md5(String plainText) {//声明byte数组byte[] secretBytes = null;try {//调用系统自带md5算法secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());} catch (NoSuchAlgorithmException e) {throw new RuntimeException("没有md5这个算法!");}//进行加密运算String md5code = new BigInteger(1, secretBytes).toString(16);//如果不够32位在后面加0for (int i = 0; i < 32 - md5code.length(); i++) {md5code = "0" + md5code;}//返回加密之后的值return md5code;}

接下来我们要建立User类,这里为了方便,仅仅只写了一个Password属性,为了后面可以测试,写了含参构造方法,以及set、get方法,
代码如下:
package cn.edu.hpu.acm.demo02;public class User {//声明属性private String password;//构造方法public User(String password){this.setPassword(password);}//set、get方法和外类取得联系public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}

然后我们要建立一个加密类,调用前两个类的方法进行加密
代码如下:
package cn.edu.hpu.acm.demo02;public class Encryption {public String encryption(User u){String password = u.getPassword();//得到一次加密String password1 = MD5util.md5(password);//建Buffer类StringBuffer sb = new StringBuffer();//for循环截取字符串for(int i=0;i<password1.length();i++){//截取Password1的1,3,5,....位if(i%2==0){sb.append(password1.charAt(i));}}//System.out.println(sb);String password2 = sb.toString();//再次调用md5算法加密String password3 = MD5util.md5(password2);return password3;}}

再接下来就是最后一步测试,我们建立Test类,为了方便一次可以多次实验,我在这里对方法进行了封装处理。
代码如下:
package cn.edu.hpu.acm.demo02;import java.util.Scanner;public class Test {public static void main(String[] args) {// TODO Auto-generated method stubtest();}public static void test(){//实例化EncryptionEncryption e = new Encryption();Scanner input = new Scanner(System.in);System.out.println("请输入密码");String pw = input.next();//实例化UserUser u = new User(pw);//输出最后结果System.out.println(e.encryption(u));System.out.println("是否想再次实验Yes Or No!");String s = input.next();//判断程序是否循环if("Yes".equalsIgnoreCase(s)){test();}else if("No".equalsIgnoreCase(s)){System.exit(1);}else{System.out.println("你输入的信息不正确!系统退出!");System.exit(1);}}}

测试结果为下图:


0 0
原创粉丝点击