Skip to main content

🥑 AK/SK加密说明

在通过email认证并且成功申请AK/SK之后, 您可以通过访问http://turboapi.dhx.icu/来调用接口服务。

加密算法

  • 访问控制:AccessKey(访问密钥)和SecretKey(秘钥)是用于访问远程API的身份验证凭证。
  • 随机数(Nonce):随机数用于每个请求生成一个唯一标识,以确保每次请求的签名都是不同的。这有助于防止重放攻击,即攻击者尝试重复发送已经捕获的请求或伪造请求。
  • 时间戳(Timestamp):时间戳用于标记请求发起的时间,调用服务端的身份验证时,可以使用时间戳来验证此请求是否在有效时间内发起。可防止重放攻击和时序攻击。
  • 生成签名:将请求体内容与SecretKey连接,然后对连接后的内容进行SHA256加密,并以十六进制字符串返回结果。

下面是不同版本的加密算法实现示例:

Java版本🥐


public class Demo {

private String accessKey = "YOUR ACCESS KEY";
private String secretKey = "YOUR SECRET KEY";

private void call() {
String result = HttpRequest
.get("http://turboapi.dhx.icu/api/v1/common/poet/random")
.addHeaders(getHeaderMap())
.execute().body();
}

private Map<String, String> getHeaderMap() {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("accessKey", accessKey);
hashMap.put("nonce", RandomUtil.randomNumbers(6));
hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
hashMap.put("sign", genSign("", secretKey));
return hashMap;
}

private String genSign(String body, String secretKey) {
Digester md5 = new Digester(DigestAlgorithm.SHA256);
String content = body + "." + secretKey;
return md5.digestHex(content);
}

}

Python 版本🥨



import requests
import time
import hashlib
import random
from typing import Dict

class Demo:
def __init__(self, access_key, secret_key):
self.access_key = access_key
self.secret_key = secret_key


def call(self):
headers = self._get_header_map()
response = requests.get("http://turboapi.dhx.icu/api/v1/common/poet/random", headers=headers)
result = response.text
return result


def _get_header_map(self) -> Dict[str, str]:
header_map = {}
header_map["accessKey"] = self.access_key
header_map["nonce"] = ''.join(random.choices('0123456789', k=6))
header_map["timestamp"] = str(int(time.time()))
header_map["sign"] = self._gen_sign("", self.secret_key)
return header_map


def _gen_sign(self, body, secret_key):
content = body + "." + secret_key
return hashlib.sha256(content.encode('utf-8')).hexdigest()

Golang 版本🥫


package main

import (
"fmt"
"math/rand"
"net/http"
"strconv"
"time"
)

type Demo struct {
AccessKey string
SecretKey string
}

func (d Demo) Call() string {
headers := d.getHeaderMap()
resp, _ := http.Get("http://turboapi.dhx.icu/api/v1/common/poet/random")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return string(body)
}

func (d Demo) getHeaderMap() map[string]string {
headerMap := make(map[string]string)
headerMap["accessKey"] = d.AccessKey
headerMap["nonce"] = strconv.Itoa(rand.Intn(1000000))
headerMap["timestamp"] = strconv.Itoa(int32(time.Now().Unix()))
headerMap["sign"] = genSign("", d.SecretKey)
return headerMap
}

func genSign(body, secretKey string) string {
content := body + "." + secretKey
h := sha256.New()
h.Write([]byte(content))
return hex.EncodeToString(h.Sum(nil))
}




JavaScript 版本🧂


const fetch = require('node-fetch');
const crypto = require('crypto');

class Demo {
constructor(accessKey, secretKey) {
this.accessKey = accessKey;
this.secretKey = secretKey;
}

async call() {
const headers = this.getHeaderMap();
const response = await fetch('http://turboapi.dhx.icu/api/v1/common/poet/random', {headers});
const result = await response.text();
return result;
}

getHeaderMap() {
const headerMap = {};
headerMap["accessKey"] = this.accessKey;
headerMap["nonce"] = Math.floor(100000 + Math.random() * 900000);
headerMap["timestamp"] = Math.floor(Date.now() / 1000);
headerMap["sign"] = this.genSign("", this.secretKey);
return headerMap;
}

genSign(body, secretKey) {
const content = body + "." + secretKey;
const hash = crypto.createHash('sha256');
hash.update(content);
return hash.digest('hex');
}
}

鉴权失败说明

如果鉴权失败,则根据不同错误类型返回不同code状态码,同时携带错误描述信息,详细错误说明如下:

HTTP Code说明错误描述信息解决方法
401缺少参数{"message":"Unauthorized"}检查是否在请求中添加了key信息, 具体参考上面的算法说明以及示例代码
401签名参数解析失败{“message”:”HMAC signature cannot be verified”}检查签名的各个参数是否有缺失是否正确,特别确认下复制的AK/SK是否正确
401签名校验失败{“message”:”HMAC signature does not match”}签名验证失败,可能原因有很多。 1. 检查access_key,secret_key是否正确。 2.检查计算签名的参数,nonce , timestamp是否按照协议要求拼接。
403时钟偏移校验失败{“message”:”HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication”}检查服务器时间是否标准,相差5分钟以上会报此错误