根据UUID和MD5, 生成可以用作Token的字符串

时间:2022-01-05 20:11:38
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID; public class MD5Generator
{
private static final char[] hexCode = "0123456789abcdef".toCharArray(); public String generateValue(){
return generateValue(UUID.randomUUID().toString());
} public static String toHexString(byte[] data)
{
if (data == null) {
return null;
}
StringBuilder r = new StringBuilder(data.length * 2);
byte[] arrayOfByte = data; int j = data.length; for (int i = 0; i < j; i++) { byte b = arrayOfByte[i];
r.append(hexCode[(b >> 4 & 0xF)]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
} public String generateValue(String param) {
try {
MessageDigest algorithm;
algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(param.getBytes());
byte[] messageDigest = algorithm.digest();
return toHexString(messageDigest);
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage());
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} }
}