CodeZLei

  博客园 :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::
public class SignGenerateUtils {

    private static final String ACCESS_KEY = "ACCESS_KEY";
    private static final String SECRET_KEY = "SECRET_KEY";

    public static void main(String[] args) {

//        String timestamp = System.currentTimeMillis() + "";
        String timestamp = "1592469343750";

        String requestBody = "";
        signGenerate(ACCESS_KEY, SECRET_KEY, timestamp, requestBody);
    }


    private static void signGenerate(String accessKey, String secretKey, String timestamp, String requestBody) {

        String rawValue = timestamp + "";
        if (StringUtils.isNotEmpty(requestBody)) {
            rawValue = rawValue + "$" + requestBody;
        }
        System.out.println("accessKey: " + accessKey);
        System.out.println("secretKey: " + secretKey);

        System.out.println("timestamp: " + timestamp);
        System.out.println("sign: " + buildSign(secretKey, rawValue));
        System.out.println("requestBody: " + requestBody);
        System.out.println("rawValue: " + rawValue);
    }

    /**
     * get sign
     *
     * @param secretKey
     * @param rawValue
     * @return
     */
    private static String buildSign(String secretKey, String rawValue) {
        Mac sha256_HMAC = null;
        try {
            sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            try {
                return URLEncoder.encode(Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(rawValue.getBytes(StandardCharsets.UTF_8))),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

posted on 2020-07-27 10:43  CodeZLei  阅读(180)  评论(0编辑  收藏  举报