阿里云openApi签名实现代码基于(NodeJS)

strToSign的构造过程以如下流程简要说明:
阿里云openApi签名实现代码基于(NodeJS)

var HmacSha1 = require('crypto-js/hmac-sha1');
var Base64 = require('crypto-js/enc-base64');
var Moment = require('moment');
var Uuid = require('uuid');
var Urlencode = require('urlencode');

//AccessKeySecret
var accesskeysecret = 'yourAccessKeySecret'+'&';
//获取timestamp
var timeStamp = Moment(new Date().get).utcOffset(0).format();
//获取signatureNorce
var signatureNorce = Uuid.v4();
var params = {"Format":"JSON","Version":"2017-03-21","SignatureMethod":"HMAC-SHA1","SignatureNonce":signatureNorce,"SignatureVersion":"1.0","AccessKeyId":"yourAccessKeyId","Timestamp":timeStamp,"Action":"GetVideoPlayAuth","VideoId":"f10d3a6c9b3d4881b91da0f8d7d90d09"};
//对各个参数进行字典序升序排序
function sortObjectKeys(obj){
    var tmp={};
    Object.keys(obj).sort().forEach(function(k){tmp[k]=obj[k]});
    return tmp;
}
params = sortObjectKeys(params);
//对排序之后的参数进行urlEncode
for(var i in params){
    params[i] = Urlencode(params[i]);
}
//对urlencode之后的特殊字符进行替换
for(var k in params){
    if(params[i].indexOf('+')){
        params[i].replace("+","%20");
    }else if(params[i].indexOf('*')){
        params[i].replace("*","%2A");
    }else if(params[i].indexOf('%7E')){
        params[i].replace("%7E","~");
    }
}

//拼接strToSign
var strToSign = '';
for(var ii in params){
    strToSign += ii +'='+ params[ii]+'&';
}
strToSign = strToSign.substr(0,strToSign.length-1);
strToSign = "GET&"+Urlencode('/')+'&' + Urlencode(strToSign);
//计算签名
params['Signature'] = Base64.stringify(HmacSha1(strToSign,accesskeysecret));

var url = 'http://vod.cn-shanghai.aliyuncs.com?';
for(var param in params){
    url += param +'='+ params[param]+'&';
}

console.log(url.substr(0,url.length-1));
上一篇:【阿里云ACE成长记第5期】分布式链路追踪系统架构设计的经验分享


下一篇:十万亿级OLAP引擎解读-AnalyticDB如何支撑数据银行超大规模低成本实时分析