背景
按照这个链接https://cloud.baidu.com/doc/RTC/s/Qjxbh7jpu#%E5%9C%A8appserver%E4%B8%8A%E9%83%A8%E7%BD%B2token%E7%94%9F%E6%88%90%E6%9C%8D%E5%8A%A1去计算百度音视频的请求token,在使用python的样例代码https://doc.bce.baidu.com/bce-documentation/RTC/BRTC_TOKEN_Test.zip在本地测试的时候报错TypeError: key: expected bytes or bytearray, but got ‘str’,代码如下
import json
from hashlib import sha1
import hmac
import base64
import binascii
from optparse import OptionParserdef calculate_signature(app_key, app_id, ts, random_str, room_name, uid, expect_ts):data = "ACS{}{}{}{}{}{}".format(app_id, ts, random_str, room_name, uid, expect_ts)app_key = bytes(app_key, encoding='utf-8')data = bytes(data, encoding='utf-8')signature =hmac.new(app_key, data, sha1).digest()#.encode('base64').rstrip()signature = binascii.b2a_hex(signature)return signaturedef calculate_token(version, signature, ts, random_str, expect_ts):token ="{}{}{}{}{}".format(version, signature, ts, random_str, expect_ts)return tokendef handler ():rig=calculate_signature("s-jcagj2g5eewai6u3p3","app-jcagj2g5ecrqv7bn","1553144847","dabdd97c","aaa","54321","1578380254")return {"statusCode": 200,"isBase64Encoded": False,"body":calculate_token("004",rig,"1553144847","dabdd97c","1578380254"),"headers": {"Content-Type": "application/json"}}
print(handler())
原因
python2的加密和python3的不一样了
解决
import json
from hashlib import sha1
import hmac
import base64
import binascii
from optparse import OptionParserdef calculate_signature(app_key, app_id, ts, random_str, room_name, uid, expect_ts):data = "ACS{}{}{}{}{}{}".format(app_id, ts, random_str, room_name, uid, expect_ts)print(app_key)print(data)app_key = bytes(app_key, encoding='utf-8')print("piao ",app_key)data = bytes(data, encoding='utf-8')print("piao1 ",data)signature =hmac.new(app_key, data, sha1).digest()#.encode('base64').rstrip()print(signature)signature = binascii.b2a_hex(signature)print(signature)return signaturedef calculate_token(version, signature, ts, random_str, expect_ts):token ="{}{}{}{}{}".format(version, signature, ts, random_str, expect_ts)return tokendef handler ():rig=calculate_signature("s-jcagj2g5eewai6u3p3","app-jcagj2g5ecrqv7bn","1553144847","dabdd97c","aaa","54321","1578380254")return {"statusCode": 200,"isBase64Encoded": False,"body":calculate_token("004",rig,"1553144847","dabdd97c","1578380254"),"headers": {"Content-Type": "application/json"}}print(handler())
输出结果就和百度的样例一样的了
s-jcagj2g5eewai6u3p3
ACSapp-jcagj2g5ecrqv7bn1553144847dabdd97caaa543211578380254
piao b's-jcagj2g5eewai6u3p3'
piao1 b'ACSapp-jcagj2g5ecrqv7bn1553144847dabdd97caaa543211578380254'
b'\x08\xb1\xa0j\xfc\x9c\x13\x86%\xdc\x7f\xc9\xab^wp\xc5\x15o#'
b'08b1a06afc9c138625dc7fc9ab5e7770c5156f23'
{'statusCode': 200, 'isBase64Encoded': False, 'body': "004b'08b1a06afc9c138625dc7fc9ab5e7770c5156f23'1553144847dabdd97c1578380254", 'headers': {'Content-Type': 'application/json'}}
需要注意的是签名结果是b’08b1a06afc9c138625dc7fc9ab5e7770c5156f23’,这个要处理一下转成字符才能和官方说明完全一致
rig=rig.decode()