package io.renren.rest.tool;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5加密工具
*
*
* @email
*
* @date 2017年8月8日 下午5:17:34
*/
public class MD5Utils {
private static final String SALT = "1qazxsw2";
private static final String ALGORITH_NAME = "md5";
private static final int HASH_ITERATIONS = 2;
private static String hash(String plainText, String salt) throws NoSuchAlgorithmException {
if (StringUtils.isBlank(plainText)) {
return "";
}
if (StringUtils.isBlank(salt)) {
salt = SALT;
}
MessageDigest digest = MessageDigest.getInstance(ALGORITH_NAME);
digest.reset();
digest.update(salt.getBytes(StandardCharsets.UTF_8));
byte[] hashed = digest.digest(plainText.getBytes(StandardCharsets.UTF_8));
int iterations = HASH_ITERATIONS - 1;
for (int i = 0; i < iterations; i++) {
digest.reset();
hashed = digest.digest(hashed);
}
return Hex.encodeHexString(hashed);
}
/**
* 使用md5生成加密后的密码
* @param pswd
* @return
*/
public static String encrypt(String pswd) {
String hashedStr = null;
try {
hashedStr = hash(pswd, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hashedStr;
}
/**
* 使用md5生成加密后的密码
* @param username
* @param pswd
* @return
*/
public static String encrypt(String username, String pswd) {
String hashedStr = null;
try {
hashedStr = hash(pswd, username + SALT);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hashedStr;
}
public static void main(String[] args) {
System.out.println(encrypt("admin", "bobo123"));
}
}