现在的位置: 首页 > 综合 > 正文

JAVA 笔记 MD5加密

2013年03月24日 ⁄ 综合 ⁄ 共 1166字 ⁄ 字号 评论关闭

       简单的MD5加密代码:

package com.test.md5;

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

public class MD5Parase {
    public static String autType="MD5";
    
    public static String hash(String data){
        try{
            return hash(data.getBytes("UTF-8"));
        }
        catch(Exception ex){
            return null;
        }
    }
    
    public static String hash(byte[] bytes){
        synchronized(autType.intern()){
            MessageDigest digest;
            try {
                digest=MessageDigest.getInstance(autType);
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                return null;
            }
            digest.update(bytes);
            return encodeHex(digest.digest());
        }        
    }
    
    private static String encodeHex(byte[]bytes){
        StringBuilder buf= new StringBuilder(bytes.length*2);
        int i;
        for(i=0;i<bytes.length;i++){
            if(((int) bytes[i] & 0xff)<0x10){
                buf.append("0");
            }
            buf.append(Long.toString((int)bytes[i] & 0xff,16));
        }
        return buf.toString();
    }
    
}

抱歉!评论已关闭.