java原生自带MD5加密

java原生自带MD5加密

public class Demo1 {
    
    public static void main(String[] args) throws Exception {
        
        //获取md5签名工具实例
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        
        //添加一组字节数据,可以多次调用
        messageDigest.update("javaweb.io".getBytes());
        
        //对添加的字节数据进行md5运算,返回运算结果
        byte[] digest = messageDigest.digest();
        
        //把字节结果转换为16进制字符串
        System.out.println(encodeHex(digest));        //0a473d1c44fbccb8f58c7401c5f04a3d
    }
    
    public static String encodeHex(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for(byte bin : bytes) {
            int result = bin & 0xFF;
            if(result < 0x10) {
                stringBuilder.append("0");
            }
            stringBuilder.append(Integer.toHexString(result));
        }
        return stringBuilder.toString();
    }
}
Last modification:November 23rd, 2019 at 11:37 pm
如果觉得这篇技术文章对你有用,请随意赞赏

Leave a Comment