package com.hdl.photovoltaic.utils;
|
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.math.BigInteger;
|
import java.nio.charset.StandardCharsets;
|
import java.security.MessageDigest;
|
import java.security.NoSuchAlgorithmException;
|
|
public class Md5Utils {
|
|
|
/**
|
* MD5转字符串
|
*/
|
public static String encodeMD5(byte[] f) {
|
try {
|
MessageDigest digest = MessageDigest.getInstance("MD5");
|
digest.update(f);
|
byte[] messageDigest = digest.digest();
|
return toHexString(messageDigest);
|
} catch (NoSuchAlgorithmException e) {
|
e.printStackTrace();
|
}
|
return "";
|
}
|
|
|
private static String toHexString(byte[] keyData) {
|
if (keyData == null) {
|
return null;
|
}
|
int expectedStringLen = keyData.length * 2;
|
StringBuilder sb = new StringBuilder(expectedStringLen);
|
for (byte keyDatum : keyData) {
|
String hexStr = Integer.toString(keyDatum & 0x00FF, 16);
|
if (hexStr.length() == 1) {
|
hexStr = "0" + hexStr;
|
}
|
sb.append(hexStr);
|
}
|
return sb.toString();
|
}
|
|
/**
|
* MD5转字符串
|
*/
|
public static String encodeMD5(String s) {
|
try {
|
MessageDigest digest = MessageDigest.getInstance("MD5");
|
digest.update(s.getBytes(StandardCharsets.UTF_8));
|
byte[] messageDigest = digest.digest();
|
return toHexString(messageDigest);
|
} catch (NoSuchAlgorithmException e) {
|
e.printStackTrace();
|
}
|
return "";
|
}
|
|
/**
|
* MD5转字符串
|
* 额外值
|
*/
|
public static String encodeMD52(String s) {
|
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
|
try {
|
byte[] btInput = s.getBytes(StandardCharsets.UTF_8);
|
MessageDigest digest = MessageDigest.getInstance("MD5");
|
digest.update(btInput);
|
byte[] md = digest.digest();
|
int j = md.length;
|
char[] str = new char[j * 2];
|
int k = 0;
|
for (byte byte0 : md) {
|
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
|
str[k++] = hexDigits[byte0 & 0xf];
|
}
|
return new String(str);
|
} catch (Exception e) {
|
e.printStackTrace();
|
return null;
|
}
|
}
|
|
/**
|
* MD5文件转字符串
|
*/
|
public static String encodeMD5(File f) {
|
if (!f.isFile()) {
|
return null;
|
}
|
MessageDigest digest;
|
byte[] buffer = new byte[1024];
|
int len;
|
try {
|
digest = MessageDigest.getInstance("MD5");
|
FileInputStream in = new FileInputStream(f);
|
while ((len = in.read(buffer, 0, 1024)) != -1) {
|
digest.update(buffer, 0, len);
|
}
|
in.close();
|
} catch (Exception e) {
|
e.printStackTrace();
|
return null;
|
}
|
BigInteger bigInt = new BigInteger(1, digest.digest());
|
return bigInt.toString(16);
|
}
|
|
// /**
|
// * MD5文件转字符串
|
// */
|
// public static String encodeMD5(byte[] f) {
|
// MessageDigest digest;
|
// try {
|
// digest = MessageDigest.getInstance("MD5");
|
// digest.update(f);
|
// } catch (Exception e) {
|
// e.printStackTrace();
|
// return null;
|
// }
|
// BigInteger bigInt = new BigInteger(1, digest.digest());
|
// return bigInt.toString(16);
|
// }
|
|
|
}
|