SocialSisterYi / bilibili-API-collect

哔哩哔哩-API收集整理【不断更新中....】
https://socialsisteryi.github.io/bilibili-API-collect/
Other
14.87k stars 1.69k forks source link

WBI 签名疑问 #843

Closed z0z0r4 closed 12 months ago

z0z0r4 commented 1 year ago

image

如图,实在想不懂哪里出问题了,一直 w_rid 对不上

from functools import reduce
from hashlib import md5
import urllib.parse
import time
import requests

mixinKeyEncTab = [
    46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
    33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40,
    61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11,
    36, 20, 34, 44, 52
]

def getMixinKey(orig: str):
    '对 imgKey 和 subKey 进行字符顺序打乱编码'
    return reduce(lambda s, i: s + orig[i], mixinKeyEncTab, '')[:32]

def encWbi(params: dict, img_key: str, sub_key: str):
    '为请求参数进行 wbi 签名'
    mixin_key = getMixinKey(img_key + sub_key)
    # curr_time = round(time.time())
    curr_time = 1697289578
    params['wts'] = curr_time                                   # 添加 wts 字段
    params = dict(sorted(params.items()))                       # 按照 key 重排参数
    # 过滤 value 中的 "!'()*" 字符
    params = {
        k : ''.join(filter(lambda chr: chr not in "!'()*", str(v)))
        for k, v 
        in params.items()
    }
    query = urllib.parse.urlencode(params)                      # 序列化参数
    wbi_sign = md5((query + mixin_key).encode()).hexdigest()    # 计算 w_rid
    params['w_rid'] = wbi_sign
    return params

def getWbiKeys() -> tuple[str, str]:
    '获取最新的 img_key 和 sub_key'
    resp = requests.get('https://api.bilibili.com/x/web-interface/nav')
    resp.raise_for_status()
    json_content = resp.json()
    img_url: str = json_content['data']['wbi_img']['img_url']
    sub_url: str = json_content['data']['wbi_img']['sub_url']
    img_key = img_url.rsplit('/', 1)[1].split('.')[0]
    sub_key = sub_url.rsplit('/', 1)[1].split('.')[0]
    return img_key, sub_key

img_key, sub_key = getWbiKeys()

signed_params = encWbi(
    params={"oid": 999323914,
    "type": 1,
    "mode": 3,
    "pagination_str": '{"offset":""}',
    "plat": 1,
    "seek_rpid": 0
    },
    img_key=img_key,
    sub_key=sub_key
)
query = urllib.parse.urlencode(signed_params)
print(signed_params)
print(query)
{'mode': '3', 'oid': '999323914', 'pagination_str': '{"offset":""}', 'plat': '1', 'seek_rpid': '0', 'type': '1', 'wts': '1697289578', 'w_rid': 'ab25ec39d6d5616d70da598dbd903cd2'}

mode=3&oid=999323914&pagination_str=%7B%22offset%22%3A%22%22%7D&plat=1&seek_rpid=0&type=1&wts=1697289578&w_rid=ab25ec39d6d5616d70da598dbd903cd2

catlair commented 12 months ago

image

灯下黑?

z0z0r4 commented 12 months ago

image

灯下黑?

web location 也算吗?我之前都最后加的

z0z0r4 commented 12 months ago

试了下好像确实是