MD5加密原理和使用

MD5

Message Digest algorithm 5

非对称加密,不可逆(因为会将原文部分信息丢失),长度固定
哈希算法的一种


加密工具类

public class MD5 {
    public static String md5(String content) {
        byte[] hash;
        try {
            // MessageDigest.getInstance("MD5") 通过信息摘要单例的构造函数获取信息摘要对象md5
            // content.getBytes("UTF-8") 获取字符串的字节数组.
            // .digest()对字节数组进行摘要,得到摘要字节数组:
            hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("NoSuchAlgorithmException",e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UnsupportedEncodingException", e);
        }
        // 把摘要数组中的每一个字节转换成16进制,并拼在一起就得到了MD5值. 
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10){
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_37577039/article/details/79788644
今日推荐