ITPub博客

首页 > 应用开发 > Java > java md5加密的方法代码

java md5加密的方法代码

Java 作者:ytbo123 时间:2014-10-28 11:15:53 0 删除 编辑

  java md5加密的方法代码,在程序开发中很多重要的信息,密码等都要用md5加密,什么,你还自己研究怎么写代码,不用了,直接复制过去用就可以了,省时省力。

  public class MD5Encode {

  private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",

  "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

  /**

  * 转换字节数组为16进制字串

  *

  * @param b

  * 字节数组

  * @return 16进制字串

  */

  public static String byteArrayToHexString(byte[] b) {

  StringBuffer resSb = new StringBuffer();

  for (int i = 0; i < b.length; i++) {

  resSb.append(byteToHexString(b[i]));

  }

  return resSb.toString();

  }

  private static String byteToHexString(byte b) {

  int n = b;

  if (n < 0)

  n = 256 + n;

  int d1 = n / 16;

  int d2 = n % 16;

  return hexDigits[d1] + hexDigits[d2];

  }

  public static String getMD5Str(String str) {

  String resStr = "";

  try {

  MessageDigest md = MessageDigest.getInstance("MD5");

  resStr = byteArrayToHexString(md.digest(str.getBytes()));

  } catch (Exception ex) {

  // PTK.inst().wWarn(PTK.getExceptionFullStr(ex));

  }

  return resStr;

  }

  public static String encodePWD(String userid, String pwd) {

  return getMD5Str(userid.toUpperCase() + ":" + pwd);

  }

  public static String getFileMD5(String fn) {

  return getFileMD5(new File(fn));

  }

  public static String getFileMD5(File file) {

  FileInputStream fis = null;

  try {

  MessageDigest md = MessageDigest.getInstance("MD5");

  fis = new FileInputStream(file);

  byte[] buffer = new byte[8192];

  int length = -1;

  while ((length = fis.read(buffer)) != -1) {

  md.update(buffer, 0, length);

  }

  return byteArrayToHexString(md.digest());

  } catch (Exception ex) {

  return null;

  } finally {

  // UnZipUtil.closeStream(fis);

  }

  }

  public static void main(String[] args) {

  System.out.println("mohwst=" + encodePWD("1", "demo112233"));

  }

  }

(文章来源:http://www.mfqyw.com/)


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29987420/viewspace-1311583/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 没有了~
下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2014-10-28

  • 博文量
    1
  • 访问量
    3648