原文链接: B站 av和bv号互转 py和js版 bigint
参考
https://www.zhihu.com/question/381784377/answer/1099438784
py的可以直接使用
1table='fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF' 2tr={} 3for i in range(58): 4 tr[table[i]]=i 5s=[11,10,3,8,4,6] 6xor=177451812 7add=8728348608 8 9def dec(x): 10 r=0 11 for i in range(6): 12 r+=tr[x[s[i]]]*58**i 13 return (r-add)^xor 14 15def enc(x): 16 x=(x^xor)+add 17 r=list('BV1 4 1 7 ') 18 for i in range(6): 19 r[s[i]]=table[x//58**i%58] 20 return ''.join(r) 21 22print(dec('BV17x411w7KC')) # 170001 23print(dec('BV1Q541167Qg')) # 455017605 24print(dec('BV1mK4y1C7Bz')) # 882584971 25print(enc(170001)) # BV17x411w7KC 26print(enc(455017605)) # BV1Q541167Qg 27print(enc(882584971)) # BV1mK4y1C7Bz
js版的需要做一些修改, 主要是使用bigint做计算, 因为其中涉及的数值计算太大了, 普通的会溢出
1const table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF' 2 3const tr = table.split('').reduce( 4 (pre, v, i) => { 5 pre[table[i]] = BigInt(i) 6 return pre 7 }, [] 8) 9 10let s = [11, 10, 3, 8, 4, 6].map(i => BigInt(i)) 11let xor = BigInt(177451812); 12let add = BigInt(8728348608) 13const NUM_58 = BigInt(58) 14 15function dec(x) { 16 let r = BigInt(0); 17 for (let i = 0; i < 6; i++) { 18 r += tr[x[s[i]]] * NUM_58 ** BigInt(i); 19 } 20 let res = (r - add) ^ xor 21 return res.toString(); 22} 23 24 25function enc(x) { 26 x = BigInt(x) 27 x = (x ^ xor) + add 28 let r = 'BV1 4 1 7 '.split('') 29 for (let i = 0; i < 6; i++) { 30 r[s[i]] = table [x / NUM_58 ** BigInt(i) % NUM_58] 31 } 32 return r.join('') 33} 34 35 36console.log(dec('BV17x411w7KC')) // 170001 37console.log(dec('BV1Q541167Qg')) // 455017605 38console.log(dec('BV1mK4y1C7Bz')) // 882584971 39console.log(enc(170001)) // BV17x411w7KC 40console.log(enc(455017605)) // BV1Q541167Qg 41console.log(enc(882584971)) // BV1mK4y1C7Bz 42console.log(enc(498566183)) // BV1AK411W7wq 43console.log(dec('BV1Ft4y197pr')) // 626046351