MD5加密

阅读更多

在一些第三方测评公司,密码必须加密,而加密的规则没要求,在此,我用上了MD5加密,也是最常见的一种加密手段

需求:在服务端接收到数据时(密码)是不能直接赋给一个变量,而是要通过加密,才能进行赋值

 

package com.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*
 * MD5 加密
*/
public class MD5 {
    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public MD5() {
    }
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }
    private static String byteToNum(byte bByte) {
        int iRet = bByte;
        System.out.println("iRet1=" + iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        return String.valueOf(iRet);
    }
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String GetMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteToString(md.digest(strObj.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }
    public static void main(String[] args) {
		System.out.println(GetMD5Code("123"));
    }
    
}

  GetMD5Code是静态的方法,所以在拿到的密码外部把这MD5.GetMD5Code(password)即可。

 

你可能感兴趣的:(java,md5)