js中pbkdf2_hmac加密python翻译

java中的pbkdf2_hmac加密和解码代码片段,使用python翻译

import hashlib
import base64
import hmac
import binascii
import json
import re
from Crypto.Cipher import AES
from binascii import a2b_hex
# url加密代码
"""
 f = o.default.HmacSHA1(o.default.enc.Utf8.parse(f), "D23ABC@#56"),
 f = o.default.enc.Base64.stringify(f).toString(),
 之后进行md5编码
"""

def hash_hmac(txt, key='D23ABC@#56', sha1=hashlib.sha1):
    hmac_code = hmac.new(key.encode(), txt.encode(), sha1).digest()
    md5 = hashlib.md5()
    md5.update(base64.b64encode(hmac_code))
    return md5.hexdigest()


# api接口返回数据js加密代码

"""
a = o.default.PBKDF2(f, "secret", {
                    keySize: 8,  # 输出64位
                    iterations: 1e3,
                    hasher: o.default.algo.SHA256
                }).toString()
u = o.default.PBKDF2(h, "secret", {
                    keySize: 4, # 输出32位
                    iterations: 1e3,
                    hasher: o.default.algo.SHA256
                }).toString();
o.default.AES.encrypt(o.default.enc.Utf8.parse(l), o.default.enc.Hex.parse(a), {
                    iv: o.default.enc.Hex.parse(u)
                }).toString()
"""
#翻译代码
def decrypt(text):
    n = hashlib.pbkdf2_hmac(hash_name='sha256',
                            password=b'D23ABC@#56',
                            salt=b'secret',
                            iterations=1000)
    key = binascii.hexlify(n)
    h = hashlib.pbkdf2_hmac(hash_name='sha256',
                            password=b'apidata/api/gk/score/special',
                            salt=b'secret',
                            iterations=1000)
    iv = binascii.hexlify(h)[:32]
    mode = AES.MODE_CBC
    cryptos = AES.new(a2b_hex(key), mode, a2b_hex(iv))
    plain_text = cryptos.decrypt(a2b_hex(text))
    return json.loads(re.findall('(\{.*\})', bytes.decode(plain_text))[0])

你可能感兴趣的:(爬虫,加密解密)