简易版
private static String convertMD5(String key){
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update((key+partnerId).getBytes());
String md5Check = new BigInteger(1, md.digest()).toString(16);
return md5Check;
}catch(Exception e){
logger.error(e.getMessage(), e);
return "";
}
}
TB版
private static String convertMD5(String key){
key = key+partnerId;
MessageDigest md5 = null;
try{
md5 = MessageDigest.getInstance("MD5");
}catch (Exception e){
logger.error(" md5 validate error: " + key, e);
return "";
}
char[] charArray = key.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++){
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
JJE版
public class MD5Utils {
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public static String generatePassword(String inputString) {
return encodeByMD5(inputString);
}
public static String generateHexString(byte[] inputByte) {
return encodeByMD5(inputByte);
}
private static String encodeByMD5(byte[] originByte) {
if (originByte != null) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] results = md.digest(originByte);
String resultString = byteArrayToHexString(results);
String pass = resultString.toUpperCase();
return pass;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
private static String encodeByMD5(String originString) {
if (originString != null) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] results = md.digest(originString.getBytes());
String resultString = byteArrayToHexString(results);
String pass = resultString.toUpperCase();
return pass;
} catch (Exception ex) {
ex.printStackTrace();//TODO change to use logger?
}
}
return null;
}
private static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static void main(String[] args){
System.out.println(generatePassword("182529217120001034991800"));
}
}