package com.house365.web.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 2017/2/20</p>
 *
 * @author XN
 * @version 1.0
 */
public class CheckUrlSignUtil {

    /**
     * 获取私钥key
     */
    private static final String PRIVATE_KEY = "00BE62C08DE8A6395D467D6555C268HH";

    /**
     * check sign is valid
     *
     * @param url
     * @param sign
     * @return
     */
    public static Boolean checkSign(String url, String sign) {
        // 兼顾两种编码方式的hash值
        String encryptUrlDecoded = null;
        Boolean flag = Boolean.FALSE;
        try {
            encryptUrlDecoded = encrypt(url, true);
            String encryptUrl = encrypt(url, false);
            if (sign.equals(encryptUrl) || sign.equals(encryptUrlDecoded)) {
                return true;
            } else {
                System.out.println("sign check fail !!! ");
                return false;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 功能描述: 接口参数排序加密算法<br>
     * 〈功能详细描述〉
     *
     * @param url
     * @return
     * @throws UnsupportedEncodingException
     * @author jiangzhou
     * @version [版本号, 2015年10月31日]
     * @since [产品/模块版本](可选)
     */
    public static String encrypt(String url, boolean isUrlDecoded) throws UnsupportedEncodingException {
        if (isUrlDecoded) {
            url = URLDecoder.decode(url, "UTF-8");
        }
        // url参数排序
        String sortUrl = UrlSortUtils.sort(url);
        // 拼接秘钥
        sortUrl += "&key=" + PRIVATE_KEY;
        System.out.println("--" + sortUrl);
        // MD5加密
        String encryptUrl = DigestUtils.md5Hex(sortUrl).toUpperCase();
        return encryptUrl;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        CheckUrlSignUtil ok = new CheckUrlSignUtil();
        //        String str = "serviceCode=Cm&serviceName=GetUploadUserPhotoCredits&userId=2447&userCityKey=nj&useridType=1&userPhoto=http://img12.house365.com/njbbsavatar/2014/12/16/2447_avatar_middle.jpg";
        String str = "actId=1&bizContent={}&city=nj&notifyUrl=http://172.17.1.196/mobileadmin/api.php?method=cashinnotify&payeeAccount=og3N5jgyjANasGygp7scm0RXF2Lo&phone=15261805182&remark=%E9%82%80%E8%AF%B7%E9%80%81%E7%8E%B0%E9%87%91&serviceCode=pay&serviceName=createOrder&tradeNo=2017062613002415261805182&userId=1567253&userRealName=ChauvetMa&version=1.0";
        String std = ok.encrypt(str, false);
        String stdf = ok.encrypt(str, true);
        System.out.println(std + "," + stdf);

    }
}
