MD5加密算法

package com.util;  // 包名
/**
 *MD5密码加密类
 *
 */
import java.security.*;  // 引入java.security包下的所有类
import java.security.spec.*; 
public final class MD5 { // 命名类
 
 public final static String MD5(String s){ // 静态 final 方法
  char hexDigits[] = { 
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 
  'e', 'f'};  // char类型数组,变量名为hexDigits
  try { 
   byte[] strTemp = s.getBytes();  // 把参数 s 转换成byte类型数组
   MessageDigest mdTemp = MessageDigest.getInstance("MD5");  // 得到一个MessageDigest 类型的变量mdTemp,提供

信息摘要算法的功能
   mdTemp.update(strTemp);  // 更新摘要
   byte[] md = mdTemp.digest();  // 这个方法应该是加密后返回的byte数组
   int j = md.length; // 记录md的长度
   char str[] = new char[j * 2];  // 存储结果用
   int k = 0; 
   for (int i = 0; i < j; i++) { 
    byte byte0 = md[i]; 
    str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // hexDigits 数组中对应的十六进制数放入str中
    str[k++] = hexDigits[byte0 & 0xf];  
   } 
   return new String(str); // 返回加密后的字符串
  } 
  catch (Exception e){ 
   return null;  // 如果有异常返回null
  } 
 }
}
1.hexDigits长度是16需要注意,这也是利用0xf的原因[十六进制]即[1111]二进制表示;
2.hexDigits[byte0 >>> 4 & 0xf] ,byte0无符右移4位,取与获得高四位(<=15),
同理hexDigits[byte0 & 0xf]获取低四位,这也是char str[] = new char[j * 2];的原因,
这两条语句其实是进行加噪音.

猜你喜欢

转载自blog.csdn.net/frozenkevin/article/details/53470494