sign-post-object-api.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (C) 2020 Tencent Cloud.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. 'use strict';
  17. const crypto = require('crypto');
  18. const { secretId, secretKey } = require('../config');
  19. const { bucket, region, expires } = require('./config');
  20. /**
  21. * 为腾讯云COS的POST Object API进行签名
  22. * 更多信息请访问 https://cloud.tencent.com/document/product/436/14690
  23. * @return {object} 上传URL以及其它签名信息
  24. */
  25. function signPostObjectAPI() {
  26. // 配置校验
  27. if (!secretId || !secretKey) {
  28. throw new Error('请云函数配置文件中配置secretId和secretKey');
  29. }
  30. if (!bucket || !region) {
  31. throw new Error('请在云函数COS模块中配置bucket和region');
  32. }
  33. if (isNaN(expires) || expires <= 0) {
  34. throw new Error('请在云函数COS模块中配置有效的expires');
  35. }
  36. // 生成签名信息
  37. const currentDate = new Date();
  38. const expirationDate = new Date(currentDate.getTime() + expires * 1000);
  39. const keyTime = `${Math.floor(currentDate.getTime() / 1000)};${Math.floor(expirationDate.getTime() / 1000)}`;
  40. const policy = JSON.stringify({
  41. expiration: expirationDate.toISOString(),
  42. conditions: [{ 'q-sign-algorithm': 'sha1' }, { 'q-ak': secretId }, { 'q-sign-time': keyTime }]
  43. });
  44. const signKey = crypto.createHmac('sha1', secretKey).update(keyTime).digest('hex');
  45. const stringToSign = crypto.createHash('sha1').update(policy).digest('hex');
  46. const signature = crypto.createHmac('sha1', signKey).update(stringToSign).digest('hex');
  47. return {
  48. host: `https://${bucket}.cos.${region}.myqcloud.com`,
  49. signAlgorithm: 'sha1',
  50. ak: secretId,
  51. keyTime,
  52. signature,
  53. policy: Buffer.from(policy).toString('base64')
  54. };
  55. }
  56. module.exports = signPostObjectAPI;