快手闪电API使用JSON Web令牌(JWT)来验证您的账户级访问权限。使用该令牌可以建立安全的服务器到服务器的身份验证,请传输带有您账户API SecretId和SecretKey的签名。
一个账户只有一个API SecretId和SecretKey密钥对。请联系您的业务对接员获取密钥对。
调用方根据私钥(SecretKey)和请求参数计算签名,并设置在请求头X-Q-Signature中,发送请求时携带签名。
签名内容
参数名 | 参数解释 | 参数示例 | 备注说明 |
---|---|---|---|
RequestMethod | http请求方法 | GET/POST | |
ReuqestUri | http请求Uri | /rest/v1/qarth/conference/start | |
RequestHeader | http请求Header | k1=v1&k2=v2 | 除了X-Q-Signature和cookie所有简单Header参数参与签名,如参数有多个,需先按key字典序后拼接,形如"k1=v1&k2=v2" |
RequestParamter | http请求Query参数 | k1=v1&k2=v2 | 如有多个参数,需先按key字典序后拼接,形如"k1=v1&k2=v2" |
签名算法
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class SignatureUtil {
private static final String HMAC_ALGORITHM = "HmacSHA256";
/**
* 生成签名
*
* @param secretKey 邮件下发的secret_key
* @param httpMethod http请求方法 GET/POST等
* @param requestUri http请求uri,eg:/rest/v1/qarth/conference/start
* @param requestHeader http请求header,除了X-Q-Signature和cookie所有简单header参数都参与算签,key字典序后拼接,形如"k1=v1&k2=v2"
* @param requestParameter http请求Query参数,key字典序后拼接,形如"k1=v1&k2=v2"
* @return 签名,需要设置在请求头X-Q-Signature中
* @throws InvalidKeyException e
* @throws NoSuchAlgorithmException e
*/
static String sign(String secretKey, String httpMethod, String requestUri, String requestHeader, String requestParameter)
throws InvalidKeyException, NoSuchAlgorithmException {
String tobeSig = httpMethod + "\n" + requestUri + "\n" + requestHeader + "\n" + requestParameter;
return signMessageByHmacSHA256(secretKey, tobeSig);
}
static String signMessageByHmacSHA256(String secretKey, String tobeSig)
throws NoSuchAlgorithmException, InvalidKeyException {
byte[] byteKey = secretKey.getBytes(StandardCharsets.UTF_8);
SecretKeySpec keySpec = new SecretKeySpec(byteKey, HMAC_ALGORITHM);
Mac hmac = Mac.getInstance(HMAC_ALGORITHM);
hmac.init(keySpec);
byte[] binaryToken = hmac.doFinal(tobeSig.getBytes(StandardCharsets.UTF_8));
return (Base64.getEncoder().encodeToString(binaryToken).replaceAll("\\s*", ""));
}
}