您的位置:首页 > 理论基础 > 数据结构算法

MD5加密算法

2016-04-08 00:00 507 查看
package com.lc.MD5src;

import java.io.UnsupportedEncodingException;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.security.SecureRandom;

import java.util.Arrays;

public class MyMd5Class {

private static final String NUMS_STR = "0123456789ABCDEF";

private static final Integer SALT_LENGTH = 12;

private static MessageDigest md = null;

/**

* 初始化MD5

*/

public static void init() {

try {

md = MessageDigest.getInstance("MD5");

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

}

/**

* 将16进制字符串转换成字节数组

*
@param String hex

*
@return byte[] result

*/

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) (NUMS_STR.indexOf(hexChars[pos]) << 4 | NUMS_STR

.indexOf(hexChars[pos + 1]));

}

return result;

}

/**

* 将16进制字节数组转换成字符串

*
@param byte[] bytes

*
@return String sb.toString()

*/

public static String byteToHexString(byte[] bytes) {

StringBuffer sb=new StringBuffer();

for (byte b : bytes) {

String hex=Integer.toHexString(b & 0xFF);

if (hex.length()==1) {

hex="0"+hex;

}

sb.append(hex.toUpperCase());

}

return sb.toString();

}

/**

* 验证口令是否有效

*
@param password

* @param passwordInDb

* @return

* @throws UnsupportedEncodingException

*/

public static boolean validPassword(String password,String passwordInDb) throws UnsupportedEncodingException{

byte[] pwdInDb=hexStringToByte(passwordInDb);

byte[] salt=new byte[SALT_LENGTH];

System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);

init();

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 UnsupportedEncodingException

*/

public static String getEncryptedPwd(String password) throws UnsupportedEncodingException{

byte[] pwd=null;

SecureRandom random=new SecureRandom();

byte[] salt=new byte[SALT_LENGTH];

random.nextBytes(salt);

init();

md.update(salt);

md.update(password.getBytes("UTF-8"));

byte[] digest=md.digest();

pwd=new byte[digest.length+SALT_LENGTH];

System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);

System.arraycopy(digest, 0, pwd, SALT_LENGTH,digest.length );

return byteToHexString(pwd);

}

public static void main(String[] args) throws UnsupportedEncodingException {

System.out.println(getEncryptedPwd("888888"));

System.out.println(validPassword("888888", "423E1CEA748ACCC9725ABAF1AE451816DF936AC4169927DA61DC4489"));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: