java加密算法-MD5

import java.security.MessageDigest;

public class MD5Util {
    /***
     * MD5加密 生成32位md5码
     * @param 待加密字符串
     * @return 返回32位md5码
     */
    public static String MD5(String inStr) throws Exception {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    // 一次加密两次解密
    public static String convertMD5(String inStr) {

        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;

    }
    // 可逆的加密算法
        public static String KL(String inStr) {
            // String s = new String(inStr);
            char[] a = inStr.toCharArray();
            for (int i = 0; i < a.length; i++) {
                a[i] = (char) (a[i] ^ 't');
            }
            String s = new String(a);
            return s;
        }

        // 加密后解密
        public static String JM(String inStr) {
            char[] a = inStr.toCharArray();
            for (int i = 0; i < a.length; i++) {
                a[i] = (char) (a[i] ^ 't');
            }
            String k = new String(a);
            return k;
        }

    /**
     * 测试主函数
     * 
     * @param args
     * @throws Exception
     */
    //密码先加密,然后再比较是否相等
    public static void main(String args[]) throws Exception {
        String str = new String("abc");
        System.out.println("原始:" + str);
        System.out.println("MD5后:" + MD5(str));
        System.out.println(convertMD5(str));
        System.out.println(convertMD5(convertMD5(str)));
        
        
        
        String s = new String("123123");
//        4297f44b13955235245b2497399d7a93
        System.out.println("原始:" + str);
        System.out.println("MD5后:" + MD5(str));
        System.out.println("MD5后再加密:" + KL(MD5(str)));
        System.out.println("解密为MD5后的:" + JM(KL(MD5(str))));
    }
}

 

posted @ 2017-10-27 11:20  冬天不眠  阅读(140)  评论(0编辑  收藏  举报