home » 编程开发 » java相关 » java实现的MD5

以前用PHP写小程序时,实现MD5很简单,直接调用内置函数md5()就可以了。
如今来学习java却发现没有这样的方法。
网上搜索了些代码,对其做了写修改实现了一个java MD5 类

package net.cyang.util;

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

public class Md5 {

 private final static String[] NOSTR = { “0″, “1″, “2″, “3″, “4″, “5″,
   ”6″, “7″, “8″, “9″, “a”, “b”, “c”, “d”, “e”, “f” };

 public Md5() {

 }

 private String byteToArrayString(byte bByte) {
  if (bByte < 0) {
   bByte += 256;
  }
  int iD1 = bByte / 16;
  int iD2 = bByte % 16;
  return NOSTR[iD1] + NOSTR[iD2];
 }

 private String byteToString(byte[] bByte) {
  StringBuffer sBuffer = new StringBuffer();
  for (int i = 0; i < bByte.length; i++) {
   sBuffer.append(byteToArrayString(bByte[i]));
  }
  return sBuffer.toString();
 }

 public String getMd5(String str) {
  String result = null;
  MessageDigest md;
  try {
   md = MessageDigest.getInstance(“MD5″);
   result = byteToString(md.digest(str.getBytes()));
  } catch (NoSuchAlgorithmException ex) {
   ex.printStackTrace();
  }

  return result;
 }

 public static void main(String[] args) {
  Md5 md5 = new Md5();
  System.out.print(md5.getMd5(“hahah”));//hahah 为要进行MD5加密的字符串
 }

}

Eclipse执行run as java application 结果:
44bea1375d673dacfa7038a2a6896ae6

Tags: 标签:,
本博客所有文章如果没加特殊说明均为原创,如需转载引用请注明出处
[重阳博客:http://www.99xunle.com/archives/737]
随机文章 相关文章

8 Responses to “java实现的MD5”

  1. JAVA竟然没有内部MD5函数….想不到

    Reply

  2. 自己动手,丰衣足食。

    Reply

  3. 你牛X

    Reply

  4. 灰过,支持

    Reply

    重阳  2009-10-27   回复:

    “fei” 和 “hui” 怎么都不可能发一样的音 :margin:

    Reply

    不死鸟  2009-10-28   回复:

    不好意思,我fu nan的

    Reply

  5. 看不懂,晕。

    Reply

    重阳  2009-10-27   回复:

    调用这个类的 String getMd5(String str) 方法就可以了,不过还是php的方便 直接md5(“password”);就行了

    Reply

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>