How to Extract Chrome Cookies in Python

Learn how to extract Google Chrome browser saved cookies and decrypt them on your Windows machine in Python.
  · 5 min read · Updated jul 2023 · Ethical Hacking · Digital Forensics

Juggling between coding languages? Let our Code Converter help. Your one-stop solution for language conversion. Start now!

As you may already know, the Chrome browser saves a lot of browsing data locally in your machine. Undoubtedly, the most dangerous is being able to extract passwords and decrypt passwords from Chrome. Also, one of the interesting stored data is cookies. However, most of the cookie values are encrypted.

In this tutorial, you will learn how to extract Chrome cookies and decrypt them as well, on your Windows machine with Python.

Related: How to Extract Chrome Passwords in Python.

To get started, let's install the required libraries:

$ pip3 install pycryptodome pypiwin32

Open up a new Python file and import the necessary modules:

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

Below are two handy functions that will help us later for extracting cookies (brought from chrome password extractor tutorial):

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:
            return datetime(1601, 1, 1) + timedelta(microseconds=chromedate)
        except Exception as e:
            print(f"Error: {e}, chromedate: {chromedate}")
            return chromedate
        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 =
        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:
    return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]

Related: Build 35+ Ethical Hacking Scripts & Tools with Python Book

get_chrome_datetime() function converts the datetimes of chrome format into a Python datetime format.

get_encryption_key() extracts and decodes the AES key that was used to encrypt the cookies, which is stored in "%USERPROFILE%\AppData\Local\Google\Chrome\User Data\Local State" file in JSON format.

def decrypt_data(data, key):
        # get the initialization vector
        iv = data[3:15]
        data = data[15:]
        # generate cipher
        cipher =, AES.MODE_GCM, iv)
        # decrypt password
        return cipher.decrypt(data)[:-16].decode()
            return str(win32crypt.CryptUnprotectData(data, None, None, None, 0)[1])
            # not supported
            return ""

The above function accepts the data and the AES key as parameters and uses the key to decrypt the data to return it.

Now that we have everything we need, let's dive into the main function:

def main():
    # local sqlite Chrome cookie database path
    db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                            "Google", "Chrome", "User Data", "Default", "Network", "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)

The file that contains the cookies data is located as defined in db_path variable, we need to copy it to the current directory, as the database will be locked when the Chrome browser is currently open.

Connecting to the SQLite database:

    # connect to the database
    db = sqlite3.connect(filename)
    # ignore decoding errors
    db.text_factory = lambda b: b.decode(errors="ignore")
    cursor = db.cursor()
    # get the cookies from `cookies` table
    SELECT host_key, name, value, creation_utc, last_access_utc, expires_utc, encrypted_value 
    FROM cookies""")
    # you can also search by domain, e.g
    # cursor.execute("""
    # SELECT host_key, name, value, creation_utc, last_access_utc, expires_utc, encrypted_value
    # FROM cookies
    # WHERE host_key like ''""")

After we connect to the database, we ignore decoding errors in case there are any, we then query the cookies table with cursor.execute() function to get all cookies stored in this file. You can also filter cookies by a domain name as shown in the commented code.

Now let's get the AES key and iterate over the rows of cookies table and decrypt all encrypted data:

    # 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)
            # already decrypted
            decrypted_value = value
        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
        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
    # close connection

Get: Build 35+ Ethical Hacking Scripts & Tools with Python Book

We use our previously defined decrypt_data() function to decrypt encrypted_value column, we print the results and set the value column to the decrypted data. We also make the cookie persistent by setting is_persistent to 1 and also is_secure to 0 to indicate that it is not encrypted anymore.

Finally, let's call the main function:

if __name__ == "__main__":

Once you execute the script, it'll print all the cookies stored in your Chrome browser including the encrypted ones, here is a sample of the results:

        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


Awesome, now you know how to extract your Chrome cookies and use them in Python.

To protect ourselves from this, we can simply clear all cookies in the Chrome browser or use the DELETE command in SQL in the original Cookies file to delete cookies.

Another alternative solution is to use Incognito mode. In that case, the Chrome browser does not save browsing history, cookies, site data, or any user information.

Also, you can also extract and decrypt Chrome passwords using the same way, and this tutorial shows how.

A worth note, though: if you want to use your cookies in Python directly without extracting them as we did here, there is a cool library that helps you do that.

You can get the complete code here.

Finally, in our Ethical Hacking with Python Ebook, we build 35+ hacking tools and scripts from scratch using Python! Check it out here if you're interested.

Disclaimer: Please run this Python script on your machine or a machine you have permission to access. Otherwise, we do not take any responsibility for any misuse.

Learn also: How to Encrypt and Decrypt Files in Python

Happy coding ♥

Take the stress out of learning Python. Meet our Python Code Assistant – your new coding buddy. Give it a whirl!

View Full Code Explain My Code
Sharing is caring!

Read Also

Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!