Halo
发布于 2024-03-01 / 90 阅读 / 0 评论 / 0 点赞

腾讯云api签名

import { sha256 } from 'js-sha256';

const SECRET_ID = "";
const SECRET_KEY = "";

function getDate(timestamp) {
  const date = new Date(timestamp * 1000);
  const year = date.getUTCFullYear();
  const month = ('0' + (date.getUTCMonth() + 1)).slice(-2);
  const day = ('0' + date.getUTCDate()).slice(-2);
  return `${year}-${month}-${day}`;
}

function getAuthorization(endpoint, action, contentType, payload, timestamp){
    const service = endpoint.substr(0, 3);
    const date = getDate(timestamp);

    console.log(payload);
    const hashedRequestPayload = sha256(payload);
    const httpRequestMethod = "POST";
    const canonicalUri = "/";
    const canonicalQueryString = "";
    const canonicalHeaders = "content-type:" + contentType + "\n"
        + "host:" + endpoint + "\n"
        + "x-tc-action:" + action.toLowerCase() + "\n";
    const signedHeaders = "content-type;host;x-tc-action";

    const canonicalRequest = httpRequestMethod + "\n"
                         + canonicalUri + "\n"
                         + canonicalQueryString + "\n"
                         + canonicalHeaders + "\n"
                         + signedHeaders + "\n"
                         + hashedRequestPayload;
    console.log(canonicalRequest);

    const algorithm = "TC3-HMAC-SHA256";
    const hashedCanonicalRequest = sha256(canonicalRequest);
    const credentialScope = date + "/" + service + "/" + "tc3_request"
    const stringToSign = algorithm + "\n" +
                    timestamp + "\n" +
                    credentialScope + "\n" +
                    hashedCanonicalRequest;
    console.log(stringToSign);

    const kDate = sha256.hmac.digest('TC3' + SECRET_KEY, date);
    const kService = sha256.hmac.digest(kDate, service);
    const kSigning = sha256.hmac.digest(kService, 'tc3_request');
    let signature = sha256.hmac(kSigning, stringToSign);
    console.log(signature);

    const authorization = algorithm + " " +
                    "Credential=" + SECRET_ID + "/" + credentialScope + ", " +
                    "SignedHeaders=" + signedHeaders + ", " +
                    "Signature=" + signature;
    return authorization;
}

module.exports = {
  getAuthorization
}

评论