From 52af1b9254714241cc2dc81b997ccea1fb5ecc6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=BE=B7=E5=8D=8E?= <2211960228@qq.com> Date: Tue, 6 Sep 2022 01:02:53 +0800 Subject: [PATCH] add qiniu_live.ts sign.ts --- src/utils/externalUpload/qiniu_live.ts | 56 ++++++++++++++++++++++++++ src/utils/sign.ts | 15 +++++++ 2 files changed, 71 insertions(+) create mode 100644 src/utils/externalUpload/qiniu_live.ts create mode 100644 src/utils/sign.ts diff --git a/src/utils/externalUpload/qiniu_live.ts b/src/utils/externalUpload/qiniu_live.ts new file mode 100644 index 000000000..fca4b5549 --- /dev/null +++ b/src/utils/externalUpload/qiniu_live.ts @@ -0,0 +1,56 @@ +import {base64ToUrlSafe, hmacSha1, urlSafeBase64Encode} from '../sign'; + +export default class qiniuLiveInstance { + accessKey: string; + secretKey: string; + host: string; // 请求域名, + method: 'GET' | 'POST' | 'PUT' | 'DELETE'; + path: string; // 请求路径 实际的请求路径详见各七牛直播云接口说明的请求包 + rawQuery?: string; + contentType?: string; + contentLength?: string; + bodyStr?: string; + constructor(config: { + accessKey: string; + secretKey: string; + host: string; + method: 'GET' | 'POST' | 'PUT' | 'DELETE'; + path: string; + rawQuery?: string; + contentType?: string; + bodyStr?: string; + contentLength?: string; + }) { + const { accessKey, secretKey, host, method, path, rawQuery, contentType, bodyStr, contentLength } = config; + this.accessKey = accessKey; + this.secretKey = secretKey; + this.host = host; + this.method = method; + this.path = path; + this.rawQuery = rawQuery; + this.contentType = contentType; + this.bodyStr = bodyStr; + this.contentLength = contentLength; + } + + getToken() { + const {method, path, rawQuery, host, contentType, contentLength, bodyStr, accessKey, secretKey} = this; + // 1. 添加 Path + let data = `${method} ${path}` + if (rawQuery) { + data += `?${rawQuery}` + } + data += `\nHost: ${host}` + if (contentType) { + data += `\nContent-Type: ${contentType}` + } + data += "\n\n" + if(contentLength && bodyStr && contentType && contentType !== "application/octet-stream") { + data+=bodyStr; + } + const sign = hmacSha1(data, secretKey); + const encodedSign = urlSafeBase64Encode(sign); + const toke = "Qiniu " + accessKey + ":" + encodedSign; + return toke; + } +} diff --git a/src/utils/sign.ts b/src/utils/sign.ts new file mode 100644 index 000000000..8fb27992c --- /dev/null +++ b/src/utils/sign.ts @@ -0,0 +1,15 @@ +import crypto from 'crypto'; +import { Buffer } from 'buffer'; +export function base64ToUrlSafe(v: string) { + return v.replace(/\//g, '_').replace(/\+/g, '-'); +} + +export function hmacSha1(encodedFlags: any, secretKey: string) { + const hmac = crypto.createHmac('sha1', secretKey); + hmac.update(encodedFlags); + return hmac.digest('base64'); +} +export function urlSafeBase64Encode(jsonFlags: string) { + const encoded = Buffer.from(jsonFlags).toString('base64'); + return base64ToUrlSafe(encoded); +}