SDK
Java
json
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class demo {
public static void main(String[] args) {
//通过客户端申请获取自己团队的ak、sk,然后将yourAccessKey和yourSecretKey替换成自己的ak、sk
String accessKey = "yourAccessKey";
String secretKey = "yourSecretKey";
try {
Map<String, String> header = new HashMap<>();
// 获取秒级时间戳,向下取一分钟的整倍数
long currentTime = Instant.now().getEpochSecond();
currentTime = currentTime - (currentTime % 60);
// 构建待签名的字符串
String stringToSign = accessKey + ":" + currentTime;
// 使用HMAC-SHA256进行签名
Mac sha256HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256HMAC.init(secretKeySpec);
byte[] hash = sha256HMAC.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
// 将字节数组转换为base64字符串
String expectedSignature = Base64.getEncoder().encodeToString(hash);
// 放入 header
header.put("pmock-access-key", accessKey);
header.put("pmock-access-token", expectedSignature);
} catch (Exception e) {
throw new RuntimeException("生成签名失败", e);
}
}
}Php
php
<?php
// 替换成你自己的
$accessKey = "yourAccessKey";
$secretKey = "yourSecretKey";
// 获取秒级时间戳,向下取整到分钟
$currentTime = time();
$currentTime = $currentTime - ($currentTime % 60);
// 构建待签名字符串
$stringToSign = $accessKey . ":" . $currentTime;
// HMAC-SHA256 并进行 Base64
$rawHash = hash_hmac('sha256', $stringToSign, $secretKey, true);
$accessToken = base64_encode($rawHash);
$headers = [
"pmock-access-key" => $accessKey,
"pmock-access-token" => $accessToken
];Go
Go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"time"
)
func main() {
accessKey := "yourAccessKey"
secretKey := "yourSecretKey"
// 获取秒级时间戳,向下取整到分钟
currentTime := time.Now().Unix()
currentTime = currentTime - (currentTime % 60)
// 构建待签名字符串
stringToSign := fmt.Sprintf("%s:%d", accessKey, currentTime)
// HMAC-SHA256
mac := hmac.New(sha256.New, []byte(secretKey))
mac.Write([]byte(stringToSign))
hash := mac.Sum(nil)
// Base64 编码
accessToken := base64.StdEncoding.EncodeToString(hash)
headers := map[string]string{
"pmock-access-key": accessKey,
"pmock-access-token": accessToken,
}
}Python
Python
import time
import hmac
import hashlib
import base64
# 替换成你自己的
access_key = "yourAccessKey"
secret_key = "yourSecretKey"
# 获取秒级时间戳,向下取整到分钟
current_time = int(time.time())
current_time = current_time - (current_time % 60)
# 构建待签名字符串
string_to_sign = f"{access_key}:{current_time}"
# HMAC-SHA256
signature = hmac.new(
secret_key.encode("utf-8"),
string_to_sign.encode("utf-8"),
hashlib.sha256
).digest()
# Base64 编码
access_token = base64.b64encode(signature).decode("utf-8")
headers = {
"pmock-access-key": access_key,
"pmock-access-token": access_token
}