MD5加密工具類--備忘

暴力小夥發表於2014-05-28

package com.cnpc.framework.utils;

import java.security.MessageDigest;

/**
 * @author bin
 * MDS加密工具類
 */
public class MD5Util {

 

 // 該方法將你輸入的字串,通過md5加密,返回一個加密後的字串
 public static String MD5Encrypt(String inStr) {
      MessageDigest md = null;
      String outStr = null;
      try {

       md = MessageDigest.getInstance("MD5"); // 可以選中其他的演算法如SHA
       byte[] digest = md.digest(inStr.getBytes("UTF-8"));
       //返回的是byte[],要轉化為String儲存比較方便
       outStr = bytetoString(digest);
      } catch (Exception nsae) {
        nsae.printStackTrace();
      } 
      return outStr;
 }

 public static String bytetoString(byte[] digest) {
  String str = "";
  String tempStr = "";
  for (int i = 0; i < digest.length; i++) {
   tempStr = (Integer.toHexString(digest[i] & 0xff));
   //System.out.println(padLeft(tempStr, 2,'0'));
      str = str + padLeft(tempStr, 2,'0');
  }
  return padLeft(str,32,'0');
 }

 private static String padLeft(String input, int size, char symbol) {
  while (input.length() < size) {
   input = symbol + input;
  }
  return input;
 }

}

相關文章