md5 算法类 java

package com.sunyard.p2p.util;

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

/**
 * @author zhanghui
 * @date  2015/10/14.
 */
public class Md5Utils {
    /**
     * MD5算法
     *
     * @param data
     * @return
     */
    public final static String getMd5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void main(String[] args) {
        String content = "你好";
        System.err.println(content + "\n" + getMd5(content));
    }
}

 MD5(16位)为 7a57a5a743894a0e MD5(32位)为 21232f297a57a5a743894a0e4a801fc3 明文为 admin

posted on 2015-10-14 16:05  杭州糊涂虫  阅读(260)  评论(0)    收藏  举报

导航