当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现MD5加密及解密的代码实例分享

Java实现MD5加密及解密的代码实例分享

2019年07月22日  | 移动技术网IT编程  | 我要评论

基础:messagedigest类的使用

其实要在java中完成md5加密,messagedigest类大部分都帮你实现好了,几行代码足矣:

/**
 * 对字符串md5加密
 *
 * @param str
 * @return
 */
import java.security.messagedigest;
public static string getmd5(string str) {
 try {
 // 生成一个md5加密计算摘要
 messagedigest md = messagedigest.getinstance("md5");
 // 计算md5函数
 md.update(str.getbytes());
 // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
 // biginteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
 return new biginteger(1, md.digest()).tostring(16);
 } catch (exception e) {
 throw new speedexception("md5加密出现错误");
 }
}

进阶:加密及解密类
java实现md5加密以及解密类,附带测试类,具体见代码。

md5加密解密类——mymd5util,代码如下

package com.zyg.security.md5;

import java.io.unsupportedencodingexception;
import java.security.messagedigest;
import java.security.nosuchalgorithmexception;
import java.security.securerandom;
import java.util.arrays;

public class mymd5util {
 
 private static final string hex_nums_str="0123456789abcdef";
 private static final integer salt_length = 12;
 
 /** 
 * 将16进制字符串转换成字节数组 
 * @param hex 
 * @return 
 */
 public static byte[] hexstringtobyte(string hex) {
 int len = (hex.length() / 2);
 byte[] result = new byte[len];
 char[] hexchars = hex.tochararray();
 for (int i = 0; i < len; i++) {
 int pos = i * 2;
 result[i] = (byte) (hex_nums_str.indexof(hexchars[pos]) << 4 
 | hex_nums_str.indexof(hexchars[pos + 1]));
 }
 return result;
 }

 
 /**
 * 将指定byte数组转换成16进制字符串
 * @param b
 * @return
 */
 public static string bytetohexstring(byte[] b) {
 stringbuffer hexstring = new stringbuffer();
 for (int i = 0; i < b.length; i++) {
 string hex = integer.tohexstring(b[i] & 0xff);
 if (hex.length() == 1) {
 hex = '0' + hex;
 }
 hexstring.append(hex.touppercase());
 }
 return hexstring.tostring();
 }
 
 /**
 * 验证口令是否合法
 * @param password
 * @param passwordindb
 * @return
 * @throws nosuchalgorithmexception
 * @throws unsupportedencodingexception
 */
 public static boolean validpassword(string password, string passwordindb)
 throws nosuchalgorithmexception, unsupportedencodingexception {
 //将16进制字符串格式口令转换成字节数组
 byte[] pwdindb = hexstringtobyte(passwordindb);
 //声明盐变量
 byte[] salt = new byte[salt_length];
 //将盐从数据库中保存的口令字节数组中提取出来
 system.arraycopy(pwdindb, 0, salt, 0, salt_length);
 //创建消息摘要对象
 messagedigest md = messagedigest.getinstance("md5");
 //将盐数据传入消息摘要对象
 md.update(salt);
 //将口令的数据传给消息摘要对象
 md.update(password.getbytes("utf-8"));
 //生成输入口令的消息摘要
 byte[] digest = md.digest();
 //声明一个保存数据库中口令消息摘要的变量
 byte[] digestindb = new byte[pwdindb.length - salt_length];
 //取得数据库中口令的消息摘要
 system.arraycopy(pwdindb, salt_length, digestindb, 0, digestindb.length);
 //比较根据输入口令生成的消息摘要和数据库中消息摘要是否相同
 if (arrays.equals(digest, digestindb)) {
 //口令正确返回口令匹配消息
 return true;
 } else {
 //口令不正确返回口令不匹配消息
 return false;
 }
 }


 /**
 * 获得加密后的16进制形式口令
 * @param password
 * @return
 * @throws nosuchalgorithmexception
 * @throws unsupportedencodingexception
 */
 public static string getencryptedpwd(string password)
 throws nosuchalgorithmexception, unsupportedencodingexception {
 //声明加密后的口令数组变量
 byte[] pwd = null;
 //随机数生成器
 securerandom random = new securerandom();
 //声明盐数组变量
 byte[] salt = new byte[salt_length];
 //将随机数放入盐变量中
 random.nextbytes(salt);

 //声明消息摘要对象
 messagedigest md = null;
 //创建消息摘要
 md = messagedigest.getinstance("md5");
 //将盐数据传入消息摘要对象
 md.update(salt);
 //将口令的数据传给消息摘要对象
 md.update(password.getbytes("utf-8"));
 //获得消息摘要的字节数组
 byte[] digest = md.digest();

 //因为要在口令的字节数组中存放盐,所以加上盐的字节长度
 pwd = new byte[digest.length + salt_length];
 //将盐的字节拷贝到生成的加密口令字节数组的前12个字节,以便在验证口令时取出盐
 system.arraycopy(salt, 0, pwd, 0, salt_length);
 //将消息摘要拷贝到加密口令字节数组从第13个字节开始的字节
 system.arraycopy(digest, 0, pwd, salt_length, digest.length);
 //将字节数组格式加密后的口令转化为16进制字符串格式的口令
 return bytetohexstring(pwd);
 }
}

测试类——client,代码如下:

package com.zyg.security.md5;

import java.io.unsupportedencodingexception;
import java.security.nosuchalgorithmexception;
import java.util.hashmap;
import java.util.map;

public class client {
 private static map users = new hashmap();
 
 public static void main(string[] args){
 string username = "zyg";
 string password = "123";
 registeruser(username,password);
 
 username = "changong";
 password = "456";
 registeruser(username,password);
 
 string loginuserid = "zyg";
 string pwd = "1232";
 try {
 if(loginvalid(loginuserid,pwd)){
 system.out.println("欢迎登陆!!!");
 }else{
 system.out.println("口令错误,请重新输入!!!");
 }
 } catch (nosuchalgorithmexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 } catch (unsupportedencodingexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 } 
 }
 
 /**
 * 注册用户
 * 
 * @param username
 * @param password
 */
 public static void registeruser(string username,string password){
 string encryptedpwd = null;
 try {
 encryptedpwd = mymd5util.getencryptedpwd(password);
 
 users.put(username, encryptedpwd);
 
 } catch (nosuchalgorithmexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 } catch (unsupportedencodingexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 }
 
 /**
 * 验证登陆
 * 
 * @param username
 * @param password
 * @return
 * @throws unsupportedencodingexception 
 * @throws nosuchalgorithmexception 
 */
 public static boolean loginvalid(string username,string password) 
 throws nosuchalgorithmexception, unsupportedencodingexception{
 string pwdindb = (string)users.get(username);
 if(null!=pwdindb){ // 该用户存在
 return mymd5util.validpassword(password, pwdindb);
 }else{
 system.out.println("不存在该用户!!!");
 return false;
 }
 }
}

ps:这里再为大家提供2款md5加密工具,感兴趣的朋友可以参考一下:

md5在线加密工具:

在线md5/hash/sha-1/sha-2/sha-256/sha-512/sha-3/ripemd-160加密工具:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网