现在的位置: 首页 > 综合 > 正文

SHA和MD5加密类型源代码简单易懂,开发人员必看

2013年08月15日 ⁄ 综合 ⁄ 共 902字 ⁄ 字号 评论关闭

package md;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHAPWD {

 public static void main(String[] args) {
  getMD5("好天气好心情");
 }

 /**
  * 安全散列算法 不可逆的加密算法
  *
  * @param strmd
  *            加密字符串
  * @return
  */
 public static String getMD5(String strmd) {
  MessageDigest sha;
  String reStr = "";
  try {
  // sha = MessageDigest.getInstance("SHA");
   sha = MessageDigest.getInstance("MD5");// SHA表示算法类型,也可以写为MD5加密类型;但是界面结果不同
   sha.update(strmd.getBytes());
   byte bt[] = sha.digest();
   reStr = bytes2String(bt);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  System.out.println("安全散列发加密结果:" + reStr);
  return reStr;
 }

 private static String bytes2String(byte[] bt) {
  String hash = "";
  for (int i = 0; i < bt.length; i++) {
   int temp;
   if (bt[i] < 0) {
    temp = 256 + bt[i];
   } else {
    temp = bt[i];
   }
   if (temp < 16) {
    hash += "0";
   }
   hash += Integer.toString(temp, 16);
  }
  hash = hash.toUpperCase();
  return hash;
 }
}

抱歉!评论已关闭.