MD5加密工具類
阿新 • • 發佈:2022-03-08
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * MD5加密 * @author lyn */ public class Md5Utils { /** * MD5加密 * * @param str * @return */ public final static String encode(String str) { try { //建立具有指定演算法名稱的摘要MessageDigest md = MessageDigest.getInstance("MD5"); //使用指定的位元組陣列更新摘要 md.update(str.getBytes()); //進行雜湊計算並返回一個位元組陣列 byte mdBytes[] = md.digest(); String hash = ""; //迴圈位元組陣列 for (int i = 0; i < mdBytes.length; i++) {int temp; //如果有小於0的位元組,則轉換為正數 if (mdBytes[i] < 0) { temp = 256 + mdBytes[i]; } else { temp = mdBytes[i]; } if (temp < 16) { hash += "0"; }//將位元組轉換為16進位制後,轉換為字串 hash += Integer.toString(temp, 16); } return hash; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } public static String encodeWithSalt(String numStr, String salt) { return encode(encode(numStr) + salt); } public static void main(String[] args) { System.out.println(encode("test")); System.out.println(encodeWithSalt("123456", "gyhfis")); } }