<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>&nbsp; public MD5Encrypt() {<BR>&nbsp; }</P>
<P>&nbsp; private final static String[] hexDigits = {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "0", "1", "2", "3", "4", "5", "6", "7",<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "8", "9", "a", "b", "c", "d", "e", "f"};</P>
<P>&nbsp; /**<BR>&nbsp;&nbsp; * 转换字节数组为16进制字串<BR>&nbsp;&nbsp; * @param b 字节数组<BR>&nbsp;&nbsp; * @return 16进制字串<BR>&nbsp;&nbsp; */<BR>&nbsp; public static String byteArrayToString(byte[] b) {<BR>&nbsp;&nbsp;&nbsp; StringBuffer resultSb = new StringBuffer();<BR>&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; b.length; i++) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //resultSb.append(byteToHexString(b[i]));//若使用本函数转换则可得到加密结果的16进制表示,即数字字母混合的形式<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; resultSb.append(byteToNumString(b[i]));//使用本函数则返回加密结果的10进制数字字串,即全数字形式<BR>&nbsp;&nbsp;&nbsp; }<BR>&nbsp;&nbsp;&nbsp; return resultSb.toString();<BR>&nbsp; }</P>
<P>&nbsp; private static String byteToNumString(byte b) {</P>
<P>&nbsp;&nbsp;&nbsp; int _b = b;<BR>&nbsp;&nbsp;&nbsp; if (_b &lt; 0) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _b = 256 + _b;<BR>&nbsp;&nbsp;&nbsp; }</P>
<P>&nbsp;&nbsp;&nbsp; return String.valueOf(_b);<BR>&nbsp; }</P>
<P>&nbsp; private static String byteToHexString(byte b) {<BR>&nbsp;&nbsp;&nbsp; int n = b;<BR>&nbsp;&nbsp;&nbsp; if (n &lt; 0) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; n = 256 + n;<BR>&nbsp;&nbsp;&nbsp; }<BR>&nbsp;&nbsp;&nbsp; int d1 = n / 16;<BR>&nbsp;&nbsp;&nbsp; int d2 = n % 16;<BR>&nbsp;&nbsp;&nbsp; return hexDigits[d1] + hexDigits[d2];<BR>&nbsp; }</P>
<P>&nbsp; public static String MD5Encode(String origin) {<BR>&nbsp;&nbsp;&nbsp; String resultString = null;</P>
<P>&nbsp;&nbsp;&nbsp; try {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; resultString = new String(origin);<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; MessageDigest md = MessageDigest.getInstance("MD5");<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; resultString =<BR>byteArrayToString(md.digest(resultString.getBytes()));<BR>&nbsp;&nbsp;&nbsp; }<BR>&nbsp;&nbsp;&nbsp; catch (Exception ex) {</P>
<P>&nbsp;&nbsp;&nbsp; }<BR>&nbsp;&nbsp;&nbsp; return resultString;<BR>&nbsp; }</P>
<P>&nbsp; public static void main(String[] args) {<BR>&nbsp;&nbsp;&nbsp; MD5Encrypt md5encrypt = new MD5Encrypt();<BR>&nbsp;&nbsp;&nbsp; System.out.println(MD5Encode("10000000"));<BR>&nbsp; }<BR>}<BR></P>
posted on 2005-11-04 20:20
R.Zeus 阅读(238)
评论(0) 编辑 收藏 所属分类:
J2SE