|
| 1 | +#! /usr/bin/python |
| 2 | +# coding:utf-8 |
| 3 | + |
| 4 | + |
| 5 | +import hmac |
| 6 | +import hashlib |
| 7 | +import base64 |
| 8 | +import zlib |
| 9 | +import json |
| 10 | +import time |
| 11 | + |
| 12 | + |
| 13 | +def base64_encode_url(data): |
| 14 | + """ base url encode 实现""" |
| 15 | + base64_data = base64.b64encode(data) |
| 16 | + base64_data_str = bytes.decode(base64_data) |
| 17 | + base64_data_str = base64_data_str.replace('+', '*') |
| 18 | + base64_data_str = base64_data_str.replace('/', '-') |
| 19 | + base64_data_str = base64_data_str.replace('=', '_') |
| 20 | + return base64_data_str |
| 21 | + |
| 22 | + |
| 23 | +def base64_decode_url(base64_data): |
| 24 | + """ base url decode 实现""" |
| 25 | + base64_data_str = bytes.decode(base64_data) |
| 26 | + base64_data_str = base64_data_str.replace('*', '+') |
| 27 | + base64_data_str = base64_data_str.replace('-', '/') |
| 28 | + base64_data_str = base64_data_str.replace('_', '=') |
| 29 | + raw_data = base64.b64decode(base64_data_str) |
| 30 | + return raw_data |
| 31 | + |
| 32 | + |
| 33 | +class TLSSigAPI: |
| 34 | + __sdkappid = 0 |
| 35 | + __version = '2.0' |
| 36 | + __key = "" |
| 37 | + |
| 38 | + def __init__(self, sdkappid, key): |
| 39 | + self.__sdkappid = sdkappid |
| 40 | + self.__key = key |
| 41 | + |
| 42 | + def __hmacsha256(self, identifier, curr_time, expire): |
| 43 | + """ 通过固定串进行 hmac 然后 base64 得的 sig 字段的值""" |
| 44 | + raw_content_to_be_signed = "TLS.identifier:" + str(identifier) + "\n"\ |
| 45 | + + "TLS.sdkappid:" + str(self.__sdkappid) + "\n"\ |
| 46 | + + "TLS.time:" + str(curr_time) + "\n"\ |
| 47 | + + "TLS.expire:" + str(expire) + "\n" |
| 48 | + return base64.b64encode(hmac.new(self.__key.encode('utf-8'), |
| 49 | + raw_content_to_be_signed.encode('utf-8'), |
| 50 | + hashlib.sha256).digest()) |
| 51 | + |
| 52 | + def gen_sig(self, identifier, expire=180*86400): |
| 53 | + """ 用户可以采用默认的有效期生成 sig """ |
| 54 | + curr_time = int(time.time()) |
| 55 | + m = dict() |
| 56 | + m["TLS.ver"] = self.__version |
| 57 | + m["TLS.identifier"] = str(identifier) |
| 58 | + m["TLS.sdkappid"] = int(self.__sdkappid) |
| 59 | + m["TLS.expire"] = int(expire) |
| 60 | + m["TLS.time"] = int(curr_time) |
| 61 | + m["TLS.sig"] = bytes.decode(self.__hmacsha256(identifier, curr_time, expire)) |
| 62 | + |
| 63 | + raw_sig = json.dumps(m) |
| 64 | + print(raw_sig) |
| 65 | + sig_cmpressed = zlib.compress(raw_sig.encode('utf-8')) |
| 66 | + base64_sig = base64_encode_url(sig_cmpressed) |
| 67 | + return base64_sig |
| 68 | + |
| 69 | + |
| 70 | +def main(): |
| 71 | + api = TLSSigAPI(1400000000, '5bd2850fff3ecb11d7c805251c51ee463a25727bddc2385f3fa8bfee1bb93b5e') |
| 72 | + sig = api.gen_sig("xiaojun") |
| 73 | + print(sig) |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + main() |
0 commit comments