package com.cool.store.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SecureUtil {
    private static final String API_KEY = "c344cbe01972777dcfe7f9767e3d2e7f";
    private static final String API_SECRET = "fAIgCJc3kPmSzD3SgEHU";

    /**
     * 利用java原生的摘要实现SHA256加密
     * @param source 加密内容
     * @param salt 盐
     * @return
     */
    public static String sha256(String source, String salt) {
        String encodeStr = "";
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            if (salt != null) {
                digest.reset();
                digest.update(salt.getBytes("UTF-8"));
            }
            digest.update(source.getBytes("UTF-8"));
            encodeStr = byte2Hex(digest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     * 将byte转为16进制
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0;i<bytes.length;i++) {
            String temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                // 一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    public static String getSignature(long timestamp) {
        return SecureUtil.sha256(timestamp + "$%^&" + API_KEY, API_SECRET);
    }

    public static void main(String[] args) {
        long timestamp = System.currentTimeMillis();
        System.out.println(getSignature(timestamp));
    }

}

