Java完成MD5加密的辦法。本站提示廣大學習愛好者:(Java完成MD5加密的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java完成MD5加密的辦法正文
本文實例講述了Java完成MD5加密的辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5HashUtil { private MessageDigest md = null; private static MD5HashUtil md5 = null; private static final char[] hexChars ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; /** * Constructor is private so you must use the getInstance method */ private MD5HashUtil() throws NoSuchAlgorithmException { md = MessageDigest.getInstance("MD5"); } /** * This returns the singleton instance */ public static MD5HashUtil getInstance()throws NoSuchAlgorithmException { if (md5 == null) { md5 = new MD5HashUtil(); } return (md5); } public static String hashCode(String dataToHash) throws NoSuchAlgorithmException{ return getInstance().hashData(dataToHash.getBytes()); } public static String hashCode(byte[] dataToHash) throws NoSuchAlgorithmException{ return getInstance().hashData(dataToHash); } public String hashData(byte[] dataToHash) { return hexStringFromBytes((calculateHash(dataToHash))).toLowerCase(); } private byte[] calculateHash(byte[] dataToHash) { md.update(dataToHash, 0, dataToHash.length); return (md.digest()); } public String hexStringFromBytes(byte[] b) { String hex = ""; int msb; int lsb = 0; int i; // MSB maps to idx 0 for (i = 0; i < b.length; i++) { msb = ((int)b[i] & 0x000000FF) / 16; lsb = ((int)b[i] & 0x000000FF) % 16; hex = hex + hexChars[msb] + hexChars[lsb]; } return(hex); } public static void main(String args[]) throws NoSuchAlgorithmException { String string = "my name is zhangli"; System.out.println(string); System.out.println(hashCode(string)); } }
如上代碼為java說話完成md5加密算法,輸入為加密後的密文!
平日將加密後的密文保留在數據庫中,假如須要比擬只比擬他們的用md5加密事後的密文。
同時,md5加密算法是弗成逆的,破解的難度很高,固然有人破解了md5,然則他們所用的硬件情況不是我們通俗的盤算機所比較的,山年夜的一名很牛的女傳授也破解了md5,不外不怎樣懂得
願望本文所述對年夜家的java法式設計有所贊助。