qcloud.js
1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const moment = require('moment')
const crypto = require('crypto')
const qs = require('querystring')
const url = require('url')
const _ = require('lodash')
const cdn_config = require('../config/cdn_config')
const config = cdn_config.qcloud;
module.exports = {
SHA1(str) {
return crypto.createHash('sha1').update(str).digest('hex')
},
HMACSHA1(str, secret) {
return crypto.createHmac('sha1', secret).update(str).digest('hex')
},
sort(obj){
const newData = {};
Object.keys(obj).sort().forEach(key => {
newData[key] = String(obj[key]);
});
return newData
},
sign(data) {
// https://cloud.tencent.com/document/product/614/12445
data.headers = data.headers || {}
data.headers.host = url.parse(data.baseUrl).host
data.headers = this.sort(data.headers) || {}
data.qs = this.sort(data.qs) || {}
const formatedParameters = qs.stringify(data.qs)
const formatedHeaders = qs.stringify(data.headers)
const httpRequestInfo = [data.method, data.uri, formatedParameters, formatedHeaders].join('\n') + '\n'
const qSignTime = `${moment().unix()};${moment(Date.now() + 60 * 1000).unix()}`
const stringToSign = ['sha1', qSignTime, this.SHA1(httpRequestInfo)].join('\n') + '\n'
const qKeyTime = qSignTime
const signKey = this.HMACSHA1(qKeyTime, config.SecretKey)
const signature = this.HMACSHA1(stringToSign, signKey)
const authorization = `q-sign-algorithm=sha1&q-ak=${config.SecretId}&q-sign-time=${qSignTime}&q-key-time=${qKeyTime}&q-header-list=${Object.keys(data.headers).join(';')}&q-url-param-list=${Object.keys(data.qs).join(';')}&q-signature=${signature}`
data.headers.Authorization = authorization
return data
}
}