伊人博客 一款有技术又有生活的博客

java程序MD5加密时前边不显示0问题解决代码

发布时间:2017-04-17 18:23:25 标签:加密算法 | 阅读(6957)

不知道从哪儿复制的MD5算法,竟然多次使用后出现前边为0直接不显示的情况,导致MD5加密结果不一致问题,简直是个大坑啊,直接复制百度真的不是一件好事啊,先记录下来,改天再好好研究一下

把代码贴下边,以帮助后来的同志

偶尔出现错误的代码如下:

public static String md5(String str){
  MessageDigest md;
  try {
    md = MessageDigest.getInstance("MD5");
  } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
    return null;
  }
  // 计算md5函数
  md.update(str.getBytes());
  //digest()最后确定返回md5 hash值,返回值为8为字符串。
  //因为md5hash值是16位的hex值,实际上就是8位的字符
  //BigInteger函数则将8位的字符串转换成16位hex值,
  //用字符串来表示;得到字符串形式的hash值
  return new BigInteger(1, md.digest())
                .toString(16).toUpperCase();
}

比较正确的MD5加密方法代码如下:

public static String md5(String str){
  MessageDigest md5 = null;  
  try{  
     md5 = MessageDigest.getInstance("MD5");  
  }catch (Exception e){  
    System.out.println(e.toString());  
    e.printStackTrace();  
    return "";  
  }  
  char[] charArray = str.toCharArray();  
  byte[] byteArray = new byte[charArray.length];
  for (int i = 0; i < charArray.length; i++)  
    byteArray[i] = (byte) charArray[i];  
  byte[] md5Bytes = md5.digest(byteArray);  
  StringBuffer hexValue = new StringBuffer();  
  for (int i = 0; i < md5Bytes.length; i++){  
    int val = ((int) md5Bytes[i]) & 0xff;  
    if (val < 16)  
      hexValue.append("0");  
    hexValue.append(Integer.toHexString(val));  
  }  
  return hexValue.toString().toUpperCase();
}


原创文章如转载,请注明出处“伊人博客

站内搜索
关注公众号(随时搜索)
文章归档
热门推荐
随机推荐
冷门晾晒