百度智能云生成认证签名node版

没有找到百度云签名SDK的node版本,写一个demo供使用:

const rp = require('request-promise');
const crypto = require('crypto');

// 百度云配置,改成自己所需接口的配置
const AccessKeyId = "xxxxxxx";
const SecretAccessKey = "xxxxxxx";
const Host = "xxx.baidubce.com";
const ContentType = "application/json; charset=utf-8";



// 调用百度云接口,传接口uri和json参数
async function apiAction(uri, params) {
  let timestamp = getTimestampString();
  let queryString = getQueryString(params);
  let Authorization = getAuthString(uri, queryString, timestamp);
  let res = await rp({
    url: "https://" + Host + uri + "?" + queryString,
    method: "POST",
    json: true,
    body: params,
    headers: {
      "Authorization": Authorization,
      "Content-Type": ContentType,
      "Host": Host,
      "x-bce-date": timestamp
    }
  });
  return res;
}

// 获取UTC时间
function getTimestampString() {
  return new Date().toISOString().replace(/\.\d*/, '');
}

// 获取参数拼接字符串
function getQueryString(params) {
  let queryString = "";
  let paramKeyArray = [];
  if (params) {
    for (let key in params) {
      paramKeyArray.push(key);
    }
    paramKeyArray = paramKeyArray.sort();
  }
  if (paramKeyArray && paramKeyArray.length > 0) {
    for (let key of paramKeyArray) {
      queryString += encodeURIComponent(key) + "=" +
        encodeURIComponent(params[key]) +
        "&";
    }
    queryString = queryString.substr(0, queryString.length - 1);
  }
  return queryString;
}

// 签名
function getAuthString(CanonicalURI, CanonicalQueryString, timestamp) {
  // 1
  const expirationPeriodInSeconds = 120;
  let authStringPrefix = `bce-auth-v1/${AccessKeyId}/${timestamp}/${expirationPeriodInSeconds}`;
  // 2
  let signedHeaders = 'host;x-bce-date';
  let CanonicalHeaders = encodeURIComponent("host") + ":" + encodeURIComponent(Host) +
    "\n" +
    encodeURIComponent('x-bce-date') + ":" + encodeURIComponent(timestamp);
  let Method = 'POST';
  let CanonicalRequest = Method + '\n' + CanonicalURI + '\n' + CanonicalQueryString + '\n' + CanonicalHeaders;
  // 3
  let SigningKey = crypto
    .createHmac('sha256', SecretAccessKey)
    .update(authStringPrefix)
    .digest()
    .toString('hex');
  // 4
  let Signature = crypto
    .createHmac('sha256', SigningKey)
    .update(CanonicalRequest)
    .digest()
    .toString('hex');
  // 5
  let authorization = `${authStringPrefix}/${signedHeaders}/${Signature}`;
  return authorization;
}

你可能感兴趣的:(javascript,百度云,node.js)