package com.matrix.core.tools;
|
|
import java.io.UnsupportedEncodingException;
|
import java.security.MessageDigest;
|
import java.security.NoSuchAlgorithmException;
|
import java.util.Formatter;
|
|
/**
|
* 加密工具
|
*
|
* @author JIANGYOUYAO
|
* @email 935090232@qq.com
|
* @date 2017年11月29日
|
*/
|
public class EncrypUtil {
|
/**
|
* 字符串MD5加密
|
*
|
* @author JIANGYOUYAO
|
* @email 935090232@qq.com
|
* @date 2017年12月5日
|
* @param sourceStr
|
* @return
|
* @throws UnsupportedEncodingException
|
* @throws NoSuchAlgorithmException
|
*/
|
public static String getMD5(String sourceStr) throws UnsupportedEncodingException, NoSuchAlgorithmException {
|
|
String resultStr = "";
|
byte[] temp = sourceStr.getBytes();
|
MessageDigest md5 = MessageDigest.getInstance("MD5");
|
md5.update(temp);
|
byte[] b = md5.digest();
|
for (int i = 0; i < b.length; i++) {
|
char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
|
char[] ob = new char[2];
|
ob[0] = digit[(b[i] >>> 4) & 0X0F];
|
ob[1] = digit[b[i] & 0X0F];
|
resultStr += new String(ob);
|
}
|
return resultStr;
|
}
|
|
/**
|
* 返回SHA-1加密后的字符串
|
*
|
* @author JIANGYOUYAO
|
* @email 935090232@qq.com
|
* @date 2017年12月5日
|
* @param sourceStr
|
* @return
|
* @throws UnsupportedEncodingException
|
* @throws NoSuchAlgorithmException
|
*/
|
public static String getSha1(String sourceStr) throws UnsupportedEncodingException, NoSuchAlgorithmException {
|
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
|
crypt.reset();
|
crypt.update(sourceStr.getBytes("UTF-8"));
|
sourceStr = byteToHex(crypt.digest());
|
return sourceStr;
|
}
|
|
private static String byteToHex(final byte[] hash) {
|
Formatter formatter = new Formatter();
|
for (byte b : hash) {
|
formatter.format("%02x", b);
|
}
|
String result = formatter.toString();
|
formatter.close();
|
return result;
|
}
|
|
|
}
|