package com.bootdo.util;

import java.security.MessageDigest;

/**
 * 
 * MD5加密工具(是基于hash算法实现,不可逆)
 * 
 * @author xuyi3
 * @2016年7月13日 @下午3:10:54
 * @Md5Utils
 * @功能说明:<br>
 * @春风十里不如你
 * @备注
 */
public class Md5Utils {

    /** 16进制的字符数组 */
    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
            "e", "f" };

    /**
     * 
     * 
     * @param source
     *            需要加密的原字符串
     * @param encoding
     *            指定编码类型
     * @param uppercase
     *            是否转为大写字符串
     * @return
     */
    public static String MD5Encode(String source, String encoding, boolean uppercase) {
        String result = null;
        try {
            result = source;
            // 获得MD5摘要对象
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 使用指定的字节数组更新摘要信息
            messageDigest.update(result.getBytes(encoding));
            // messageDigest.digest()获得16位长度
            result = byteArrayToHexString(messageDigest.digest());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return uppercase ? result.toUpperCase() : result;
    }

    /**
     * 转换字节数组为16进制字符串
     * 
     * @param bytes
     *            字节数组
     * @return
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (byte tem : bytes) {
            stringBuilder.append(byteToHexString(tem));
        }
        return stringBuilder.toString();
    }

    /**
     * 转换byte到16进制
     * 
     * @param b
     *            要转换的byte
     * @return 16进制对应的字符
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }


    public static String getResponse(String username, String realm, String password, String method, String url, String nonce, String nc, String cnonce, String qop) {
        //        HA1 = md5("username:realm:password");
        String Ha1str = username+":"+realm+":"+password;
        String resHa1 = MD5Encode(Ha1str,"utf-8",false);

//        HA2 = md5("method:uri");
        String Ha2str = method+":"+url;
        String resHa2 = MD5Encode(Ha2str,"utf-8",false);


//        response = md5("HA1:nouce:nc:cnonce:qop:HA2");
        String responsestr = resHa1+":"+nonce+":"+nc+":"+cnonce+":"+qop+":"+resHa2;
        String responseHa2 = MD5Encode(responsestr,"utf-8",false);
//        188ffa2b22cb3b0cf20d5c05131953fe
        return responseHa2;
    }


}




//备注:其实apache commones Codec包中有常用的一些加密算法实现
