Python如何提取Chrome Cookie?本文带你了解如何在你的 Windows 机器上使用 Python 提取 Google Chrome 浏览器保存的 cookie 并解密它们。
你可能已经知道,Chrome 浏览器会在你的机器本地保存大量浏览数据。毫无疑问,最危险的是能够从 Chrome 中提取密码和解密密码。此外,有趣的存储数据之一是 cookie。但是,大多数 cookie 值都是加密的。
如何在Python中提取Chrome Cookie?在本教程中,你将学习如何在 Windows 机器上使用 Python 提取 Chrome cookie 并对其进行解密。
相关:如何在 Python 中提取 Chrome 密码。
Python如何提取Cookie?首先,让我们安装所需的库:
$ pip3 install pycryptodome pypiwin32
打开一个新的 Python 文件并导入必要的模块:
import os
import json
import base64
import sqlite3
import shutil
from datetime import datetime, timedelta
import win32crypt # pip install pypiwin32
from Crypto.Cipher import AES # pip install pycryptodome
下面是两个方便的函数,可以帮助我们以后提取 cookie(来自chrome 密码提取器教程):
def get_chrome_datetime(chromedate):
    """Return a `datetime.datetime` object from a chrome format datetime
    Since `chromedate` is formatted as the number of microseconds since January, 1601"""
    if chromedate != 86400000000 and chromedate:
        try:
            return datetime(1601, 1, 1) + timedelta(microseconds=chromedate)
        except Exception as e:
            print(f"Error: {e}, chromedate: {chromedate}")
            return chromedate
    else:
        return ""
def get_encryption_key():
    local_state_path = os.path.join(os.environ["USERPROFILE"],
                                    "AppData", "Local", "Google", "Chrome",
                                    "User Data", "Local State")
    with open(local_state_path, "r", encoding="utf-8") as f:
        local_state = f.read()
        local_state = json.loads(local_state)
    # decode the encryption key from Base64
    key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
    # remove 'DPAPI' str
    key = key[5:]
    # return decrypted key that was originally encrypted
    # using a session key derived from current user's logon credentials
    # doc: http://timgolden.me.uk/pywin32-docs/win32crypt.html
    return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]
Python如何提取Chrome Cookie?get_chrome_datetime() 函数将 chrome 格式的日期时间转换为 Python 日期时间格式。
get_encryption_key()提取和解码用于加密 cookie 的 AES 密钥,这"%USERPROFILE%\AppData\Local\Google\Chrome\User Data\Local State"以 JSON 格式存储在文件中。
def decrypt_data(data, key):
    try:
        # get the initialization vector
        iv = data[3:15]
        data = data[15:]
        # generate cipher
        cipher = AES.new(key, AES.MODE_GCM, iv)
        # decrypt password
        return cipher.decrypt(data)[:-16].decode()
    except:
        try:
            return str(win32crypt.CryptUnprotectData(data, None, None, None, 0)[1])
        except:
            # not supported
            return ""
上述函数接受数据和AES密钥作为参数,并使用密钥解密数据返回。
现在我们拥有了我们需要的一切,让我们深入研究 main 函数:
def main():
    # local sqlite Chrome cookie database path
    db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                            "Google", "Chrome", "User Data", "default", "Cookies")
    # copy the file to current directory
    # as the database will be locked if chrome is currently open
    filename = "Cookies.db"
    if not os.path.isfile(filename):
        # copy file when does not exist in the current directory
        shutil.copyfile(db_path, filename)
包含 cookie 数据的文件位于db_path变量中定义的位置,我们需要将其复制到当前目录,因为当前打开 Chrome 浏览器时数据库将被锁定。
连接到SQLite数据库:
    # connect to the database
    db = sqlite3.connect(filename)
    cursor = db.cursor()
    # get the cookies from `cookies` table
    cursor.execute("""
    SELECT host_key, name, value, creation_utc, last_access_utc, expires_utc, encrypted_value 
    FROM cookies""")
    # you can also search by domain, e.g thepythoncode.com
    # cursor.execute("""
    # SELECT host_key, name, value, creation_utc, last_access_utc, expires_utc, encrypted_value
    # FROM cookies
    # WHERE host_key like '%thepythoncode.com%'""")
如何在Python中提取Chrome Cookie?连接到数据库后,我们只需使用cursor.execute()函数查询cookies表即可获取存储在此文件中的所有cookie。你还可以按注释代码中所示的域名过滤 cookie。
现在让我们获取 AES 密钥并遍历 cookie 表的行并解密所有加密数据:
    # get the AES key
    key = get_encryption_key()
    for host_key, name, value, creation_utc, last_access_utc, expires_utc, encrypted_value in cursor.fetchall():
        if not value:
            decrypted_value = decrypt_data(encrypted_value, key)
        else:
            # already decrypted
            decrypted_value = value
        print(f"""
        Host: {host_key}
        Cookie name: {name}
        Cookie value (decrypted): {decrypted_value}
        Creation datetime (UTC): {get_chrome_datetime(creation_utc)}
        Last access datetime (UTC): {get_chrome_datetime(last_access_utc)}
        Expires datetime (UTC): {get_chrome_datetime(expires_utc)}
        ===============================================================
        """)
        # update the cookies table with the decrypted value
        # and make session cookie persistent
        cursor.execute("""
        UPDATE cookies SET value = ?, has_expires = 1, expires_utc = 99999999999999999, is_persistent = 1, is_secure = 0
        WHERE host_key = ?
        AND name = ?""", (decrypted_value, host_key, name))
    # commit changes
    db.commit()
    # close connection
    db.close()
Python如何提取Chrome Cookie?我们使用我们之前定义的decrypt_data()函数来解密encrypted_value列,我们打印结果并将value列设置为解密的数据。我们也保证Cookie持续通过设置is_persistent来1也is_secure来0,以表明它不再被加密。
最后,让我们调用 main 函数:
if __name__ == "__main__":
    main()
执行脚本后,它将打印存储在 Chrome 浏览器中的所有 cookie,包括加密的 cookie,以下是结果示例:
        ===============================================================
        Host: www.example.com
        Cookie name: _fakecookiename
        Cookie value (decrypted): jLzIxkuEGJbygTHWAsNQRXUaieDFplZP
        Creation datetime (UTC): 2021-01-16 04:52:35.794367
        Last access datetime (UTC): 2021-03-21 10:05:41.312598
        Expires datetime (UTC): 2022-03-21 09:55:48.758558
        ===============================================================
...
Python如何提取Cookie?总结
太棒了,现在你知道如何提取 Chrome cookie 并在 Python 中使用它们了。
如何在Python中提取Chrome Cookie?为了避免这种情况,我们可以简单地清除 Chrome 浏览器中的所有 cookie,或者使用DELETE原始 Cookies 文件中的 SQL 中的命令来删除 cookie。
另一种替代解决方案是使用隐身模式。在这种情况下,Chrome 浏览器不会保存浏览历史记录、cookie、站点数据或用户输入的任何信息。
此外,你还可以使用相同的方式提取和解密 Chrome 密码,本教程将展示如何操作。
不过值得注意的是,如果你想直接在 Python 中使用你的 cookie,而不像我们在这里所做的那样提取它们,那么有一个很酷的库可以帮助你做到这一点。

