import com.yutu.util.MessageUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
public class MD5Test {
private static final String UTF8 = StandardCharsets.UTF_8.name();
/**
* 使用codec实现MD5编码
*/
@Test
public void S() throws Exception{
String str = "使用codec实现md5加密";
System.out.println(DigestUtils.md5Hex(str.getBytes(UTF8)));
}
/**
* 使用jdk原生的api实现md5
* @throws Exception
*/
@Test
public void test1() throws Exception{
String str = "乐之者java";
String algorithm = "MD5";//算法名对象
String hexStr = MessageUtils.doDigest(str,algorithm);
System.out.println("hexStr: " + hexStr);
}
/**
* 把字节数组转为16进制字符串,如果一个字节数组转为16进制不足两位,则前面补0
* @param digestBytes
* @return
*/
private String convert(byte[] digestBytes) {
StringBuilder sb = new StringBuilder();
for (byte b: digestBytes){
//进行与运算,为了获取b的补码的后8位
String hex = Integer.toHexString(((int)b)&0xff);
if (hex.length() == 1){
hex = "0" + hex;
}
sb.append(hex);
}
return sb.toString();
}
}
将原先的编码方法以及转换方法抽取为工具类,如下:
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
public class MessageUtils {
private static final String UTF8 = StandardCharsets.UTF_8.name();
/**
* 执行消息摘要
* @param originalContent 原始字符串
* @param algorithm 算法名,如MD5
* @return 摘要内容
*/
public static String doDigest(String originalContent,String algorithm){
try{
//获取消息摘要算法对象
MessageDigest md = MessageDigest.getInstance(algorithm);
//获取原始内容的字节数组
byte[] bytes = originalContent.getBytes(UTF8);
//获取摘要结果
byte[] digestBytes = md.digest(bytes);
String hexStr = HexUtils.covertBytes2HexStr(digestBytes);
return hexStr;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
import org.apache.commons.codec.binary.Hex;
public class HexUtils {
/**
* 使用codec工具类
*/
public static String covertHexStr(byte[] digestBytes){
return Hex.encodeHexString(digestBytes);
}
/**
* 把字节数组转为16进制字符串,如果一个字节数组转为16进制不足两位,则前面补0
* @param digestBytes
* @return
*/
public static String covertBytes2HexStr(byte[] digestBytes){
StringBuilder sb = new StringBuilder();
for (byte b: digestBytes){
//进行与运算,为了获取b的补码的后8位
String hex = Integer.toHexString(((int)b)&0xff);
if (hex.length() == 1){
hex = "0" + hex;
}
sb.append(hex);
}
return sb.toString();
}
}