网易云音乐api加密算法

2017-12-06  本文已影响0人  羽煊

在用爬虫爬网易云音乐的时候用到了api的加密算法,有牛人提供了该算法,这里记录下。

import json
import base64
import requests
from Crypto.Cipher import AES


def _aesEncrypt(self,text,secKey):
    pad = 16 - len(text) % 16
    text = text + pad * chr(pad)
    encryptor = AES.new(secKey,2,'0102030405060708')
    ciphertext = encryptor.encrypt(text)
    ciphertext = base64.b64encode(ciphertext)
    return ciphertext

def _rsaEncrypt(self,text,pubKey,modulus):
    text = text[::-1]
    rs = int(text.encode('hex'),16) ** int(pubKey,16) % int(modulus,16)
    return format(rs,'x').zfill(256)

def _createSecretKey(self,size):
    return (''.join(map(lambda xx: (hex(ord(xx))[2:]), os.urandom(size))))[0:16]

def _getUrl(self,id):
    url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='
    text = {"ids": [id],"br":"128000",'csrf_token': 'xxxxxxxxx'}
    headers = {'Cookie': 'appver=1.5.2;', 'Referer': 'http://music.163.com/'}
    modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7' 
    nonce = '0CoJUm6Qyw8W8jud'  
    pubKey = '010001'  
    text = json.dumps(text)
    secKey = self._createSecretKey(16)
    encText = self._aesEncrypt(self._aesEncrypt(text, nonce), secKey)
    encSecKey = self._rsaEncrypt(secKey, pubKey, modulus)
    data = {'params': encText, 'encSecKey': encSecKey}
    req = requests.post(url,headers=headers, data=data)
    url = json.loads(req.text)['data'][0]['url']
    return url

其中modulus,nonce,pubKey 是固定字符串
csrf_token可以在浏览器中访问“http://music.163.com/”,按F12 -> network,找到url?csrf_token,后面的字符串就是。
ids是歌名对应的id

上一篇 下一篇

猜你喜欢

热点阅读