VIRGIN FOREST OF JAVA
不要埋头苦干,要学习,学习,再学习。。。。。
powered by R.Zeus
<P>常有人问及MD5算法为何有些程序片断返回完全数字型结果而有些返回数字与字母的混合字串。</P> <P>其实两种返回结果只是因为加密结果的不同显示形式,Blog中已经有.Net的实现,在此附加JAVA实现,供参考。</P> <P>JAVA的标准类库理论上功能也很强大,但由于虚拟机/运行时的实现太多,加之版本差异,有些代码在不同环境下运行会出现奇怪的异常结果,尤其以涉及字符集的操作为甚。</P> <P>package com.bee.framework.common;</P> <P>import java.security.MessageDigest;</P> <P>public class MD5Encrypt {<BR>  public MD5Encrypt() {<BR>  }</P> <P>  private final static String[] hexDigits = {<BR>      "0", "1", "2", "3", "4", "5", "6", "7",<BR>      "8", "9", "a", "b", "c", "d", "e", "f"};</P> <P>  /**<BR>   * 转换字节数组为16进制字串<BR>   * @param b 字节数组<BR>   * @return 16进制字串<BR>   */<BR>  public static String byteArrayToString(byte[] b) {<BR>    StringBuffer resultSb = new StringBuffer();<BR>    for (int i = 0; i < b.length; i++) {<BR>      //resultSb.append(byteToHexString(b[i]));//若使用本函数转换则可得到加密结果的16进制表示,即数字字母混合的形式<BR>      resultSb.append(byteToNumString(b[i]));//使用本函数则返回加密结果的10进制数字字串,即全数字形式<BR>    }<BR>    return resultSb.toString();<BR>  }</P> <P>  private static String byteToNumString(byte b) {</P> <P>    int _b = b;<BR>    if (_b < 0) {<BR>      _b = 256 + _b;<BR>    }</P> <P>    return String.valueOf(_b);<BR>  }</P> <P>  private static String byteToHexString(byte b) {<BR>    int n = b;<BR>    if (n < 0) {<BR>      n = 256 + n;<BR>    }<BR>    int d1 = n / 16;<BR>    int d2 = n % 16;<BR>    return hexDigits[d1] + hexDigits[d2];<BR>  }</P> <P>  public static String MD5Encode(String origin) {<BR>    String resultString = null;</P> <P>    try {<BR>      resultString = new String(origin);<BR>      MessageDigest md = MessageDigest.getInstance("MD5");<BR>      resultString =<BR>byteArrayToString(md.digest(resultString.getBytes()));<BR>    }<BR>    catch (Exception ex) {</P> <P>    }<BR>    return resultString;<BR>  }</P> <P>  public static void main(String[] args) {<BR>    MD5Encrypt md5encrypt = new MD5Encrypt();<BR>    System.out.println(MD5Encode("10000000"));<BR>  }<BR>}<BR></P>
posted on 2005-11-04 20:20 R.Zeus 阅读(233) 评论(0)  编辑  收藏 所属分类: J2SE

只有注册用户登录后才能发表评论。


网站导航: