一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java 实现MD5加密算法的简单实例

时间:2022-06-29 01:20:21 编辑:袖梨 来源:一聚教程网

java 实现MD5加密算法的简单实例

实现代码:

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加密算法是不可逆的,破解的难度很高。

热门栏目