智能图像签名生成脚本

2019-03-21 16:48:12 浏览数 (1)

参考签名文档:

https://cloud.tencent.com/document/product/867/17719


代码示例:

python3:

代码语言:python代码运行次数:0复制
import time
import random
import hmac
import hashlib
import binascii
import base64

class Auth(object):
    def __init__(self, appid, sid, skey):
        self._appid, self._secretid, self._secretkey = str(appid), str(sid), str(skey)

    def get_sign(self, bucket, howlong=864000):
        """ GET REUSABLE SIGN

        :param bucket: 图片处理所使用的 bucket
        :param howlong: 签名的有效时长,单位 秒

        :return: 签名字符串
        """

        if howlong <= 0:
            raise Exception('Param howlong must be great than 0')

        now = int(time.time())
        rdm = random.randint(0, 999999999)

        text = 'a='   self._appid   '&b='   bucket   '&k='   self._secretid   '&e='   str(now   howlong)   '&t='   str(
            now)   '&r='   str(rdm)   '&f='
        hexstring = hmac.new(self._secretkey.encode('utf-8'), text.encode('utf-8'), hashlib.sha1).hexdigest()
        binstring = binascii.unhexlify(hexstring)
        return base64.b64encode(binstring   text.encode('utf-8')).rstrip(),text

if __name__ == '__main__':
    a = Auth('125xxxxx','AKIDxxxxxxxxxxxx','3JXxxxxxxxxxxxxx') ## API密钥获取https://console.cloud.tencent.com/cam/capi
    sign,text = a.get_sign('person-check')
    print("签名(使用单引号中间的部分):",sign)

php:

代码语言:php复制
<?php 
$appid = "YOUR APPID_ID"; 
$secret_id = "YOUR SECRET_ID"; 
$secret_key = "YOUR SECRET_KEY"; 
$expired = time()   2592000; 
$onceExpired = 0; 
$current = time(); 
$rdm = rand(); 
$userid = "0"; 
$fileid = "tencentyunSignTest";

$srcStr = 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$expired.'&t='.$current.'&r='.$rdm.'&f=';

$srcWithFile = 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$expired.'&t='.$current.'&r='.$rdm.'&f='.$fileid;

$srcStrOnce= 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$onceExpired .'&t='.$current.'&r='.$rdm 
.'&f='.$fileid;

$signStr = base64_encode(hash_hmac('SHA1', $srcStr, $secret_key, true).$srcStr);

$srcWithFile = base64_encode(hash_hmac('SHA1', $srcWithFile , $secret_key, true).$srcWithFile );

$signStrOnce = base64_encode(hash_hmac('SHA1',$srcStrOnce,$secret_key, true).$srcStrOnce);

echo $signStr."n";

?>

0 人点赞