Open In App

How to Extract Chrome Passwords in Python?

Last Updated : 21 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to extract all passwords stored in the Chrome browser. 

Note: This article is for users who use Chrome on Windows. If you are a Mac or Linux user, you may need to make some changes to the given path, while the rest of the Python program will remain the same.

Installation:

Now, Let’s install some important libraries which we need to write a python program through which we can extract Chrome Passwords.

pip install pycryptodome
pip install pypiwin32

Before we extract the password directly from Chrome, we need to define some useful functions that will help our main functions. 

  • First Function
def chrome_date_and_time(chrome_data):

    # Chrome_data format is 
    # year-month-date hr:mins:seconds.milliseconds
    # This will return datetime.datetime Object
    return datetime(1601, 1, 1) + timedelta(microseconds=chrome_data)

The chrome_date_and_time() function is responsible for converting Chrome’s date format into a human-readable date and time format. 

Chrome Date and time format look like this:

'year-month-date hr:mins:seconds.milliseconds'

Example:

2020-06-01 10:49:01.824691
  • Second Function
def fetching_encryption_key():
    
    # Local_computer_directory_path will
    # look like this below
    # C: => Users => <Your_Name> => AppData => 
    # Local => Google => Chrome => User Data => 
    # Local State
    
    local_computer_directory_path = os.path.join(
    os.environ["USERPROFILE"], "AppData", "Local", "Google",
    "Chrome", "User Data", "Local State")
                                                 
    with open(local_computer_directory_path, "r", encoding="utf-8") as f:
        local_state_data = f.read()
        local_state_data = json.loads(local_state_data)

    # decoding the encryption key using base64
    encryption_key = base64.b64decode(
    local_state_data["os_crypt"]["encrypted_key"])
    
    # remove Windows Data Protection API (DPAPI) str
    encryption_key = encryption_key[5:]
    
    # return decrypted key
    return win32crypt.CryptUnprotectData(
    encryption_key, None, None, None, 0)[1]

The fetching_encryption_key() function obtains and decodes the AES key used to encrypt the password. It is saved as a JSON file in “C:\Users\<Your_PC_Name>\AppData\Local\Google\Chrome\User Data\Local State”. This function will be useful for the encrypted key.

  • Third Function
def password_decryption(password, encryption_key):

    try:
        iv = password[3:15]
        password = password[15:]
        
        # generate cipher
        cipher = AES.new(encryption_key, AES.MODE_GCM, iv)
        
        # decrypt password
        return cipher.decrypt(password)[:-16].decode()
    except:
        try:
            return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
        except:
            return "No Passwords"

password_decryption() takes the encrypted password and AES key as parameters and returns the decrypted version or Human Readable format of the password.

Below is the implementation.

Python3




import os
import json
import base64
import sqlite3
import win32crypt
from Cryptodome.Cipher import AES
import shutil
from datetime import timezone, datetime, timedelta
  
  
def chrome_date_and_time(chrome_data):
    # Chrome_data format is 'year-month-date 
    # hr:mins:seconds.milliseconds
    # This will return datetime.datetime Object
    return datetime(1601, 1, 1) + timedelta(microseconds=chrome_data)
  
  
def fetching_encryption_key():
    # Local_computer_directory_path will look 
    # like this below
    # C: => Users => <Your_Name> => AppData =>
    # Local => Google => Chrome => User Data =>
    # Local State
    local_computer_directory_path = os.path.join(
      os.environ["USERPROFILE"], "AppData", "Local", "Google", "Chrome"
      "User Data", "Local State")
      
    with open(local_computer_directory_path, "r", encoding="utf-8") as f:
        local_state_data = f.read()
        local_state_data = json.loads(local_state_data)
  
    # decoding the encryption key using base64
    encryption_key = base64.b64decode(
      local_state_data["os_crypt"]["encrypted_key"])
      
    # remove Windows Data Protection API (DPAPI) str
    encryption_key = encryption_key[5:]
      
    # return decrypted key
    return win32crypt.CryptUnprotectData(encryption_key, None, None, None, 0)[1]
  
  
def password_decryption(password, encryption_key):
    try:
        iv = password[3:15]
        password = password[15:]
          
        # generate cipher
        cipher = AES.new(encryption_key, AES.MODE_GCM, iv)
          
        # decrypt password
        return cipher.decrypt(password)[:-16].decode()
    except:
          
        try:
            return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
        except:
            return "No Passwords"
  
  
def main():
    key = fetching_encryption_key()
    db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                           "Google", "Chrome", "User Data", "default", "Login Data")
    filename = "ChromePasswords.db"
    shutil.copyfile(db_path, filename)
      
    # connecting to the database
    db = sqlite3.connect(filename)
    cursor = db.cursor()
      
    # 'logins' table has the data
    cursor.execute(
        "select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins "
        "order by date_last_used")
      
    # iterate over all rows
    for row in cursor.fetchall():
        main_url = row[0]
        login_page_url = row[1]
        user_name = row[2]
        decrypted_password = password_decryption(row[3], key)
        date_of_creation = row[4]
        last_usuage = row[5]
          
        if user_name or decrypted_password:
            print(f"Main URL: {main_url}")
            print(f"Login URL: {login_page_url}")
            print(f"User name: {user_name}")
            print(f"Decrypted Password: {decrypted_password}")
          
        else:
            continue
          
        if date_of_creation != 86400000000 and date_of_creation:
            print(f"Creation date: {str(chrome_date_and_time(date_of_creation))}")
          
        if last_usuage != 86400000000 and last_usuage:
            print(f"Last Used: {str(chrome_date_and_time(last_usuage))}")
        print("=" * 100)
    cursor.close()
    db.close()
      
    try:
          
        # trying to remove the copied db file as 
        # well from local computer
        os.remove(filename)
    except:
        pass
  
  
if __name__ == "__main__":
    main()


Output:

For the above code, we followed these below steps;

  • First, we use the previously defined function fetching_encryption_key() to obtain the encryption key
  • Then copy the SQLite database in “C:\Users\<Your_PC_Name>\AppData\Local\Google\Chrome\User Data\default\Login Data” where the saved Password data is stored of the current directory and establish a connection with it. This is because the original database file locked when Chrome started. 
  • With the help of the cursor object, we will execute the SELECT SQL query from the ‘logins’ table order by date_last_used.
  • Traverse all the login rows in a more readable format to obtain the passwords for each password and format date_created and date_last_used.
  • Finally, With the help of print statements, we will print all the saved credentials which are extracted from Chrome.
  • Delete the copy of the database from the current directory.


Similar Reads

Remember and copy passwords to clipboard using Pyperclip module in Python
It is always a difficult job to remember all our passwords for different accounts. So this is a really simple Python program which uses sys module to obtain account name as argument from the command terminal and pyperclip module to paste the respective account's password to the clipboard. Pyperclip module does not come pre-installed with Python. To
2 min read
Getting Saved Wifi Passwords using Python
Usually while connecting with the wifi we have to enter some password to access the network, but we are not directly able to see the password we have entered earlier i.e password of saved network. In this article, we will see how we can get all the saved WiFi name and passwords using Python, in order to do this we will use subprocess module of pyth
3 min read
How to Brute Force ZIP File Passwords in Python?
In this article, we will see a Python program that will crack the zip file's password using the brute force method. The ZIP file format is a common archive and compression standard. It is used to compress files. Sometimes, compressed files are confidential and the owner doesn't want to give its access to every individual. Hence, the zip file is pro
3 min read
GUI to generate and store passwords in SQLite using Python
In this century there are many social media accounts, websites, or any online account that needs a secure password. Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It is hard to remember all the distinct passwords. We
8 min read
Hiding and encrypting passwords in Python?
There are various Python modules that are used to hide the user’s inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted. maskpass() maskpass() is a Pyth
6 min read
Hashing Passwords in Python with BCrypt
In this article, we will see how to hash passwords in Python with BCrypt. Storing passwords in plain text is a bad practice as it is vulnerable to various hacking attempts. That's why it is recommended to keep them in a hashed form. What is hashing? It's a process of converting one string to another using a hash function. There are various types of
4 min read
How To Hash Passwords In Python
In this article, we are going to know how to hash passwords in python. A strong password provides safety. Plain text passwords are extremely insecure, so we need to strengthen the passwords by hashing the password. Hashing passwords is a cheap and secure method that keeps the passwords safe from malicious activity. Password hashing generates a uniq
4 min read
Storing passwords with Python keyring
In this article, we will see how to store and retrieve passwords securely using Python's keyring package. What is a keyring package? keyring package is a module specifically designed to securely store and retrieve passwords. It is like the keychain of MacOS, using this module and Python code we can access the system keyring service. Only authorized
2 min read
Google Chrome Dino Bot using Image Recognition | Python
What would you see in your Chrome browser when there is no internet connection? Yes, everybody knows that dinosaur game that comes on screen. So, in this article, we are going to build a simple python bot that plays Chrome Dino Game without user interaction. Here we are not using any machine learning or artificial intelligence to counter this probl
4 min read
Send Chrome Notification Using Python
In this article, we are going to see how to send a Chrome notification from your PC to a phone or several devices in this article. We may send messages, links, and other content. For this, we'll use Python's notify2 module and its various capabilities, which will help us in delivering messages to many devices. notify2 is a Python module that is use
2 min read
Article Tags :
Practice Tags :