1. 程式人生 > 其它 >MD5加密演算法工具類建立

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
    }
}