MD5 加密 工具类

本文介绍了如何在Java中使用MD5算法对字符串进行加密,包括实例化MessageDigest对象、处理异常以及生成安全的哈希值。作者还展示了如何将MD5用于生成随机盐并应用于密码哈希。
摘要由CSDN通过智能技术生成

import lombok.extern.slf4j.Slf4j;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Slf4j
public class MD5Utils {
    
    
    public static String md5(String source) {

        // 1.判断 source 是否有效
        if (source == null || source.length() == 0) {
            // 2.如果不是有效的字符串抛出异常
            throw new RuntimeException("字符串不可为空");
        }
        try {
            // 3.获取 MessageDigest 对象
            String algorithm = "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            // 4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();
            //执行加密
            byte[] output = messageDigest.digest(input);
            // 6.创建 BigInteger 对象
//            设置 通过MD5加密后的符号
//              signum : 1: 正数
//                       -1: 负数
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);
            // 7.按照 16 进制将 bigInteger 的值转换为大写字符串
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.error("e:{}", e);
            return null;
        }
    }

    public static void main(String[] args) {
        String    salt =    UUID.randomUUID().toString().replace("-" , "");
        String pwd = MD5Utils.md5("123456w." + salt);
        System.out.println(pwd);
        // 在线MD5 破解工具 https://www.cmd5.com/


//

    }
}

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值