全部文档
当前文档

暂无内容

如果没有找到您期望的内容,请尝试其他搜索词

文档中心

签名机制

最近更新时间:2021-09-08 15:20:01

数据库的openAPI支持GET和POST两种HTTP方法,具体流程请参见签名机制

Python Demo

import hashlib
import hmac
import time
import urllib.request

import requests

# Python 3.9.6
def http_execute(methed, host, heads, data=None):
    url = 'https://%s/?' % host
    for key in data:
        url += urllib.request.quote(key, '~') + '=' + urllib.request.quote(str(data[key]), '~') + '&'
    response = requests.request(methed, url, headers=heads, data=None)
    return response;


# sigon方法
def sign(params, secret_key):
    str_encode = ''
    param_keys = sorted(params.keys())
    for key in param_keys:
        str_encode += urllib.request.quote(key, '~') + '=' + urllib.request.quote(str(params[key]), '~') + '&'
    return hmac.new(bytes(secret_key, 'utf-8'), bytes(str_encode[:-1], 'utf-8'), hashlib.sha256).hexdigest()


class ksyun_iam_api_tools():
    """金山云API相关"""

    def __init__(self):
        self.AK = 'your_ak'
        self.SK = 'your_sk'
        self.SERVICE = "krds"
        self.REGION = "cn-beijing-6"
        self.HOST = "%s.%s.api.ksyun.com" % (self.SERVICE, self.REGION)
        self.additional_headers = {'Accept': 'application/json'}

    def describe_db_instances(self):
        data = {
            'Accesskey': self.AK,
            'Service': 'krds',
            'Action': 'DescribeDBInstances',
            'Version': '2016-07-01',
            'Timestamp': time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),  # 使用UTC格式的时间
            'SignatureVersion': '1.0',
            'SignatureMethod': 'HMAC-SHA256',
        }
        data["Signature"] = sign(data, self.SK)
        return http_execute("GET", self.HOST, self.additional_headers, data)


if __name__ == '__main__':
    api = ksyun_iam_api_tools()
    instances = api.describe_db_instances()
    print(instances.text)


Java Demo

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// jdk1.8.0_241
public class ram_demo {
    private static final Pattern ENCODED_CHARACTERS_PATTERN;

    static {
        StringBuilder pattern = new StringBuilder();
        pattern.append(Pattern.quote("+"))
                .append("|")
                .append(Pattern.quote("*"))
                .append("|")
                .append(Pattern.quote("%7E"))
                .append("|")
                .append(Pattern.quote("%2F"));
        ENCODED_CHARACTERS_PATTERN = Pattern.compile(pattern.toString());
    }

    /**
     * 注意空格( )会编码成+号,所以+最后需要替换成%20(%20为空格)
     * 在URLEncode后需对三种字符替换:加号(+)替换成 %20、星号(*)替换成 %2A、 %7E 替换回波浪号(~)
     */
    private static String urlEncode(final String value, final boolean path) {
        if (value == null) {
            return "";
        }

        try {

            String encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.name());
            Matcher matcher = ENCODED_CHARACTERS_PATTERN.matcher(encoded);
            StringBuffer buffer = new StringBuffer(encoded.length());

            while (matcher.find()) {
                String replacement = matcher.group(0);
                if ("+".equals(replacement)) {
                    replacement = "%20";
                } else if ("*".equals(replacement)) {
                    replacement = "%2A";
                } else if ("%7E".equals(replacement)) {
                    replacement = "~";
                } else if (path && "%2F".equals(replacement)) {
                    replacement = "/";
                }

                matcher.appendReplacement(buffer, replacement);
            }
            matcher.appendTail(buffer);
            return buffer.toString();
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static String getCanonicalizedQueryString(Map<String, Object> params) {
        final Map<String, String> tmap = new TreeMap<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            String encodedParamName = urlEncode(key, false);
            String encodedValues = urlEncode(value.toString(), false);
            tmap.put(encodedParamName, encodedValues);
        }

        final StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : tmap.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(entry.getKey()).append('=').append(entry.getValue());
        }
        return sb.toString();
    }

    public static String signature(Map<String, Object> params, String secretKey) {
        String canonicalizedQueryString = getCanonicalizedQueryString(params);
        return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secretKey).hmacHex(canonicalizedQueryString);
    }

    public static String utc2Local(String utcTime, String utcTimePatten, String localTimePatten) throws ParseException {
        SimpleDateFormat utcFormater = new SimpleDateFormat(utcTimePatten);
        utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));//时区定义并进行时间获取
        Date gpsUTCDate = null;
        gpsUTCDate = utcFormater.parse(utcTime);
        SimpleDateFormat localFormater = new SimpleDateFormat(localTimePatten);
        localFormater.setTimeZone(TimeZone.getDefault());
        String localTime = localFormater.format(gpsUTCDate.getTime());
        return localTime;
    }


    public static void test1() throws IOException {
        String accesskey = "your_ak";
        String secretKey = "your_sk";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        TimeZone zone = TimeZone.getTimeZone("UTC");
        Calendar cal = Calendar.getInstance(zone);
        sdf.setTimeZone(zone);

        Map<String, Object> params = new HashMap<>();
        params.put("Accesskey", accesskey); //公共参数
        params.put("Service", "krds"); //公共参数
        params.put("Action", "DescribeDBInstances"); //公共参数
        params.put("Version", "2016-07-01"); //公共参数
        params.put("Timestamp", sdf.format(cal.getTime())); //公共参数
        params.put("SignatureVersion", "1.0"); //公共参数
        params.put("SignatureMethod", "HMAC-SHA256"); //公共参数
        params.put("Signature", signature(params, secretKey));

        String product_name = "krds";
        String region = "cn-beijing-6";

        String url = "https://" + product_name + "." + region + ".api.ksyun.com/?" + getCanonicalizedQueryString(params);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Accept", "application/json")
                .build();
        Response response = client.newCall(request).execute();

        System.out.println(new String(response.body().bytes()));
    }

    public static void main(String[] args) {
        try {
            test1();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Go Demo

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// go version go1.16.5 darwin/amd64

//获取signature签名
func sign(params url.Values, sk string) string {
	strEncode := params.Encode()
	strEncode = strings.Replace(strEncode, "+", "%20", -1)
	h := hmac.New(sha256.New, []byte(sk))
	h.Write([]byte(strEncode))
	return hex.EncodeToString(h.Sum(nil))
}

func main() {

	params := url.Values{}
	params.Add("Accesskey", "your_ak")
	params.Add("Service", "krds")
	params.Add("Action", "DescribeDBInstances")
	params.Add("Version", "2016-07-01")
	params.Add("Timestamp", time.Now().UTC().Format("2006-01-02T15:04:05Z")) //通过time.Now().UTC().Format("2006-01-02T15:04:05Z")实现
	params.Add("SignatureVersion", "1.0")
	params.Add("SignatureMethod", "HMAC-SHA256")
	sk := "your_sk"
	signature := sign(params, sk)
	params.Add("Signature", signature)

	strEncode := params.Encode()
	strEncode = strings.Replace(strEncode, "+", "%20", -1)

	url := "https://krds.cn-beijing-6.api.ksyun.com/?" + strEncode
	method := "GET"
	client := &http.Client{}
	req, _ := http.NewRequest(method, url, nil)
	req.Header.Add("Accept", "application/json")
	res, _ := client.Do(req)
	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)
	fmt.Println(string(body))
}

文档导读
纯净模式常规模式

纯净模式

点击可全屏预览文档内容
文档反馈