天行健,君子以自强不息

BlogJava 首页 新随笔 联系 聚合 管理
  12 Posts :: 0 Stories :: 2 Comments :: 0 Trackbacks
package com.yill;

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

/**
 * MD5 encrypt class, returns a MD5-encrypted hex string.
 * 
 * 
@author yill
 * 
@version 2008-2-26
 * 
@since 1.0
 
*/

public class YillMD5
{
    
/**
     * The hex digits.
     
*/

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

    
/**
     * Transform the byte array to hex string.
     * 
     * 
@param b
     * 
@return
     
*/

    
public static String byteArrayToHexString(byte[] b)
    
{
        StringBuffer resultSb 
= new StringBuffer();
        
for (int i = 0; i < b.length; i++)
        
{
            resultSb.append(byteToHexString(b[i]));
        }

        
return resultSb.toString();
    }


    
/**
     * Transform a byte to hex string.
     * 
     * 
@param b
     * 
@return
     
*/

    
private static String byteToHexString(byte b)
    
{
        
int n = b;
        
if (n < 0)
            n 
= 256 + n;

        
// get the first four bit
        int d1 = n / 16;

        
// get the second four bit
        int d2 = n % 16;

        
return hexDigits[d1] + hexDigits[d2];
    }


    
/**
     * Get the MD5 encrypt hex string of the origin string. <br/>The origin
     * string won't validate here, so who use the API should validate by
     * himself.
     * 
     * 
@param origin
     * 
@return
     * 
@throws NoSuchAlgorithmException
     
*/

    
public static String MD5Encode(String origin)
            
throws NoSuchAlgorithmException
    
{
        MessageDigest md 
= MessageDigest.getInstance("MD5");
        
return byteArrayToHexString(md.digest(origin.getBytes()));
    }


    
public static void main(String[] args)
    
{
        
try
        
{
            System.out
                    .println(
"The MD5 encrypt code of http://www.blogjava.net/yill/ is: "
                            
+ YillMD5
                                    .MD5Encode(
"http://www.blogjava.net/yill/"));
        }

        
catch (NoSuchAlgorithmException e)
        
{
            e.printStackTrace();
        }

    }

}

posted on 2008-03-18 23:42 yill 阅读(438) 评论(0)  编辑  收藏

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


网站导航: