public class MD5_Test {
    public static String md5_1(String oldStr) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] oldBytes = oldStr.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(oldBytes);
            byte[] newBytes = md.digest();
            char newStr[] = new char[32];
            for (int i = 0; i < 16; i++) {
                byte tmp = newBytes[i];
                newStr[2 * i] = hexDigits[tmp >>> 4 & 0xf];
                newStr[2 * i + 1] = hexDigits[tmp & 0xf];
            }
            return new String(newStr);
        } catch (Exception e) {
            return null;
        }
    }

    public static String md5_2(String oldStr) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] bs = digest.digest(oldStr.getBytes());
            String hexString = "";
            for (byte b : bs) {
                int temp = b & 255;
                if (temp < 16 && temp >= 0) {
                    hexString = hexString + "0" + Integer.toHexString(temp);
                } else {
                    hexString = hexString + Integer.toHexString(temp);
                }
            }
            return hexString;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String md5_3(String plainText) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(plainText.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));
        }
        return buf.toString();
        // System.out.println("result: " + buf.toString());//32位的加密
        // System.out.println("result: " + buf.toString().substring(8,24));//16位的加密
    }

    public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        // 确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        // 加密后的字符串
        String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));

        return newstr;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        System.out.println(md5_1("1"));
        System.out.println(md5_2("1"));
        System.out.println(md5_2("1"));
    }
}

输出结果:

转载于:https://www.cnblogs.com/convict/p/8834855.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐