zoukankan      html  css  js  c++  java
  • cookieUtils.py

    从浏览器中读取cookie,返回字典格式cookie
    从Http 的请求头中的cookie 格式转化为字典形式

    import ast
    import sqlite3
    import re
    import urllib3
    import os
    import json
    
    import sys
    import base64
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    
    
    
    def dpapi_decrypt(encrypted):
        import ctypes
        import ctypes.wintypes
    
        class DATA_BLOB(ctypes.Structure):
            _fields_ = [('cbData', ctypes.wintypes.DWORD),
                        ('pbData', ctypes.POINTER(ctypes.c_char))]
    
        p = ctypes.create_string_buffer(encrypted, len(encrypted))
        blobin = DATA_BLOB(ctypes.sizeof(p), p)
        blobout = DATA_BLOB()
        retval = ctypes.windll.crypt32.CryptUnprotectData(
            ctypes.byref(blobin), None, None, None, None, 0, ctypes.byref(blobout))
        if not retval:
            raise ctypes.WinError()
        result = ctypes.string_at(blobout.pbData, blobout.cbData)
        ctypes.windll.kernel32.LocalFree(blobout.pbData)
        return result
    
    
    def aes_decrypt(encrypted_txt):
        with open(os.path.join(os.environ['LOCALAPPDATA'],
                               r"GoogleChromeUser DataLocal State"), encoding='utf-8', mode="r") as f:
            jsn = json.loads(str(f.readline()))
        encoded_key = jsn["os_crypt"]["encrypted_key"]
        encrypted_key = base64.b64decode(encoded_key.encode())
        encrypted_key = encrypted_key[5:]
        key = dpapi_decrypt(encrypted_key)
        nonce = encrypted_txt[3:15]
        cipher = Cipher(algorithms.AES(key), None, backend=default_backend())
        cipher.mode = modes.GCM(nonce)
        decryptor = cipher.decryptor()
        return decryptor.update(encrypted_txt[15:])
    
    
    def chrome_decrypt(encrypted_txt):
        if sys.platform == 'win32':
            try:
                if encrypted_txt[:4] == b'x01x00x00x00':
                    decrypted_txt = dpapi_decrypt(encrypted_txt)
                    return decrypted_txt.decode()
                elif encrypted_txt[:3] == b'v10':
                    decrypted_txt = aes_decrypt(encrypted_txt)
                    return decrypted_txt[:-16].decode()
            except WindowsError:
                return None
        else:
            raise WindowsError
    
    
    def get_cookies_from_chrome(domain):
        sql = f'SELECT name, encrypted_value as value FROM cookies where host_key like "%{domain}%"'
        filename = os.path.join(os.environ['USERPROFILE'], r'AppDataLocalGoogleChromeUser DatadefaultCookies')
        con = sqlite3.connect(filename)
        con.row_factory = sqlite3.Row
        cur = con.cursor()
        cur.execute(sql)
        cookies = []
        for row in cur:
            cookie = {}
            if row['value'] is not None:
                name = row['name']
                value = chrome_decrypt(row['value'])
                if value is not None:
                    cookie["domain"] = domain
                    cookie["name"] = name
                    cookie["value"] = value
                    cookie["path"] = "/"
                    cookie["expires"] = "None"
                    cookies.append(cookie)
        return cookies
    
    
    
    def tran_cookies_str_to_dict(cookie_str):
        first = re.sub("(.*?)=(.*?); ", '"\1":"\2",
    ', cookie_str)
        print("===================================")
        sec = re.sub(",
    ([^"]*?)=(.*)", ',
    "\1":"\2"', first)
        sec = "{" + sec + "}"
        return ast.literal_eval(sec)
    
    
    print(get_cookies_from_chrome("www.baidu.com"))
    
  • 相关阅读:
    Clean Docker <none>:<none>
    Conservation Vs Non-conservation Forms of conservation Equations
    What are the differences between an LES-SGS model and a RANS based turbulence model?
    How to permanently set $PATH on Linux/Unix?
    tar解压命令
    C++ (P199—P211)多态 虚函数 抽象类
    C++ (P160—)多继承 二义性 虚基类 “向上转型”
    java与c++的访问权限的问题
    由strupr,strlwr体会如果将字符常量转换为变量进行修改,体会常量的静态存储
    C++ (P103—P154)
  • 原文地址:https://www.cnblogs.com/ruhai/p/14344635.html
Copyright © 2011-2022 走看看