MD5加密算法工具类创建

直接上代码

/**
 * 通用方法工具类
 */
public class CrowdUtil {


   /**
    * 对明文字符串进行MD5加密
    * @param source
    * @return
    */
   public static String md5(String source){

      //1.判断source是否有效
      if (source == null || source.length() == 0){
         //无效则抛出异常
         throw new RuntimeException(CorwdConstant.MESSAGE_STRING_INVALIDATE);
      }
      try {
         //3.获取MessageDigest对象
         String algorithm = "md5";
         MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

         //4.获取字符串对应的字符数组
         byte[] bytes = source.getBytes();

         //5.执行加密

         byte[] output = messageDigest.digest(bytes);
         //6.创建BigInterger对象
         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();
      }
      return null;
   }

测试

public class StringTest {
    @Test
    public void testMD5(){
        String source = "123456789";

        String md5 = CrowdUtil.md5(source);

        System.out.println("md5 = " + md5);//25F9E794323B453885F5181F1B624D0B
    }
}

posted @ 2022-04-15 11:28  锅巴编程  阅读(64)  评论(1)    收藏  举报