前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >cos 请求签名(Python PHP )

cos 请求签名(Python PHP )

原创
作者头像
xunzhou
修改2021-06-17 11:55:03
1.1K1
修改2021-06-17 11:55:03
举报
文章被收录于专栏:cos_zxcos_zx
代码语言:javascript
复制
import hmac
import hashlib
import time

import datetime, time

'''
格式如下:
KeyTime = [Now];[Expires]
SignKey = HMAC-SHA1([SecretKey], KeyTime)
HttpString = [HttpMethod]\n[HttpURI]\n[HttpParameters]\n[HttpHeaders]\n
StringToSign = sha1\nKeyTime\nSHA1(HttpString)\n
Signature = HMAC-SHA1(SignKey, StringToSign)
'''
serid = ""
serkey = ""
def get_authorization(metod,key):
    q_sing = 'q-sign-algorithm=sha1'
    q_key = '&q-ak={}'.format(serid)


    StartTimestamp = int(time.time())  # UINX 时间
    print(StartTimestamp)
    # EndTimestamp = int(time.time())
    EndTimestamp = StartTimestamp + 6000 # 过期时间设置
    # print(EndTimestamp) # 当前时间戳

    KeyTime = '%s;%s' % (StartTimestamp, EndTimestamp) # 拼接key time
    print('KeyTime:',KeyTime)
    q_sign_time ='&q-sign-time=%s' % KeyTime
    q_key_time ='&q-key-time=%s' % KeyTime

    HeaderList ='&q-header-list='
    UrlParamList ='&q-url-param-list='
    sign_key = hmac.new('{}'.format(serkey).encode('utf-8'), KeyTime.encode('utf-8'), hashlib.sha1).hexdigest()
    print('sign_key',sign_key)
    HttpMethod = '{}'.format(metod)
    HttpURI = '{}'.format(key)  #替换为自己的地址
    HttpParameters = ''
    HttpHeaders = ''
    # HttpString = [HttpMethod]\n[HttpURI]\n[HttpParameters]\n[HttpHeaders]\n
    # http_str = HttpMethod + '\n' + HttpURI + '\n' + '\n'+HttpHeaders + '\n'
    http_str = HttpMethod + '\n' + HttpURI + '\n' + '\n' + '\n'

    sha1_http_string = hashlib.sha1(http_str.encode('utf-8')).hexdigest() # SHA1(HttpString)
    str_to_sign = 'sha1\n%s\n%s\n' % (KeyTime, sha1_http_string)
    sign_nature =hmac.new(sign_key.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha1).hexdigest()

    print('sign_nature',sign_nature)
    q_sign_nature = '&q-signature=%s' % sign_nature
    Authorization = q_sing +q_key +q_sign_time +q_key_time +HeaderList +UrlParamList +q_sign_nature
    print('Authorization:',Authorization)
    return Authorization

#     # request_url = url + Authorization
#     # print(request_url)
get_authorization('post',"/jobs")
# get_authorization('get','/8.jpg-100')

php:

代码语言:javascript
复制
<?php
/**
 * php 签名样例
 * @param string $method 请求类型 method
 * @param string $filename 文件名称
 * @return string 签名字符串
 */
function getAuthorization($secretid, $secretkey, $method, $filename)
{
    // 获取个人 API 密钥 https://console.qcloud.com/capi
    $SecretId = $secretid;
    $SecretKey = $secretkey;
    // 整理参数
    $queryParams = array();
    $headers = array();
    $method = strtolower($method ? $method : 'head');
    $filename = $filename ? $filename : '/';
    substr($filename, 0, 1) != '/' && ($filename = '/' . $filename);
    // 工具方法
    function getObjectKeys($obj)
    {
        $list = array_keys($obj);
        sort($list);
        return $list;
    }
    function obj2str($obj)
    {
        $list = array();
        $keyList = getObjectKeys($obj);
        $len = count($keyList);
        for ($i = 0; $i < $len; $i++) {
            $key = $keyList[$i];
            $val = isset($obj[$key]) ? $obj[$key] : '';
            $key = strtolower($key);
            $list[] = rawurlencode($key) . '=' . rawurlencode($val);
        }
        return implode('&', $list);
    }
    // 要用到的 Authorization 参数列表
    $qSignAlgorithm = 'sha1';
    $qAk = $SecretId;
    $qSignTime = (string)(time() - 60) . ';' . (string)(time() + 3600);
    $qKeyTime = $qSignTime;
    $qHeaderList = strtolower(implode(';', getObjectKeys($headers)));
    $qUrlParamList = strtolower(implode(';', getObjectKeys($queryParams)));
    // 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
    // 步骤一:计算 SignKey
    $signKey = hash_hmac("sha1", $qKeyTime, $SecretKey);
    // 步骤二:构成 FormatString
    $formatString = implode("\n", array(strtolower($method), $filename, obj2str($queryParams), obj2str($headers), ''));
    // 步骤三:计算 StringToSign
    $stringToSign = implode("\n", array('sha1', $qSignTime, sha1($formatString), ''));
    // 步骤四:计算 Signature
    $qSignature = hash_hmac('sha1', $stringToSign, $signKey);
    // 步骤五:构造 Authorization
    $authorization = implode('&', array(
        'q-sign-algorithm=' . $qSignAlgorithm,
        'q-ak=' . $qAk,
        'q-sign-time=' . $qSignTime,
        'q-key-time=' . $qKeyTime,
        'q-header-list=' . $qHeaderList,
        'q-url-param-list=' . $qUrlParamList,
        'q-signature=' . $qSignature
    ));
    return $authorization;
}

$SecretId = '';  # 你的秘钥
$SecretKey = '';
$Method = 'GET';  # 方法
$Cos_Path = '/8.jpg';  # 路径
$sign = getAuthorization($SecretId, $SecretKey, $Method, $Cos_Path);
print_r($sign);

java : 参考:https://github.com/tencentyun/cos-snippets/blob/master/Java/src/test/java/com/qcloud/cssg/GetAuthorization.java

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档