`
annan211
  • 浏览: 447983 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

java MD5加密

阅读更多
 package export.util;

import java.security.MessageDigest;

public class Util
{
/**
     * MD5运算
     * @param password  原字符串
     * @return  MD5运算后的字符串
     */
    public static String md5(String password)
    {
        /*
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] mdtemp = md.digest(ori.getBytes());
            String ret = "";
            for (int i = 0; i < mdtemp.length; i++) {
                ret += Integer.toHexString(mdtemp[i] + 512).substring(1);
            }
            return ret.toUpperCase();
        } catch (NoSuchAlgorithmException nsae) {
            System.err.println(nsae.getMessage());
            return ori;
        }*/

        byte[] unencodedPassword = password.getBytes();

        MessageDigest md = null;

        try {
            // first create an instance, given the provider
            md = MessageDigest.getInstance("MD5");
        } catch (Exception e) {

            return password;
        }

        md.reset();

        // call the update method one or more times
        // (useful when you don't know the size of your data, eg. stream)
        md.update(unencodedPassword);

        // now calculate the hash
        byte[] encodedPassword = md.digest();

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                buf.append("0");
            }

            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }

        return buf.toString();
    }

    public static String nvl(String szSource, String szDef) {
        if (szSource == null || szSource.trim().equals("")) {
            return szDef;
        }
        return szSource;
    }

    public static String nvl(int iSource, String szDef) {
        if (iSource == 0) {
            return szDef;
        }
        return Integer.toString(iSource);
    }}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics