Open In App

How to Extract Chrome Passwords in Python?

Last Updated : 21 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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
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
Driving Headless Chrome with Python
In this article, we are going to see how to drive headless chrome with Python. Headless Chrome is just a regular Chrome but without User Interface(UI). We need Chrome to be headless because UI entails CPU and RAM overheads. For this, we will use ChromeDriver, Which is a web server that provides us with a way to interact with Headless Chrome. And Se
3 min read
Automate Chrome Dino Game using Python
For this article, we will be building a Python bot that can play the "Chrome Dino Offline Game". Chrome dino is a dinosaur game that launches itself on your web browser when there is no internet connection. For the introduction of the game, the dinosaur has to jump to avoid the approaching cactus or duck to avoid the bird. The first fundamental ste
7 min read
How to make HTML files open in Chrome using Python?
Prerequisites: Webbrowser HTML files contain Hypertext Markup Language (HTML), which is used to design and format the structure of a webpage. It is stored in a text format and contains tags that define the layout and content of the webpage. HTML files are widely used online and displayed in web browsers. To preview HTML files, we make the use of br
2 min read
How To Automate Google Chrome Using Foxtrot and Python
In this article, we are going to see how to automate google chrome using Foxtrot &amp; Python. What is Foxtrot RPA?Robotic process automation (RPA) cuts down employees’ workloads by automating repetitive, high-volume steps in processes. Software robots, such as Foxtrot RPA emulate the actions of human workers to execute tasks within applications vi
4 min read
How to Play the Dinosaur Game Hidden Inside your Google Chrome?
Every Google Chrome user is known for the famous game "The Chrome Dino Game" or the official "No Internet Game". Whenever the internet goes out the Dino Game opens up and keeps you engaged until the internet is restored. It is a fun, interactive and engaging game developed by Google using JavaScript. The T-Rex Dinosaur is displayed whenever the com
3 min read
Python Regex to extract maximum numeric value from a string
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. Examples: Input : 100klh564abc365bgOutput : 564Maximum numeric value among 100, 564 and 365 is 564.Input : abchsd0sdhsOutput : 0Python Regex to extract maximum numeric value from a stringThis problem has existing solution please refer
2 min read
Python Slicing | Extract ‘k’ bits from a given position
How to extract ‘k’ bits from a given position ‘p’ in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get o
4 min read
How to extract image information from YouTube Playlist using Python?
Prerequisite: YouTube API Google provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video, et
2 min read
Python program to extract Email-id from URL text file
Prerequisite : Pattern Matching with Python Regex Given the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work. Example : Input : Hello This is Geeksforgeeks [email protected] [email protected] GfG is a portal for gee
1 min read
Extract CSS tag from a given HTML using Python
Prerequisite: Implementing Web Scraping in Python with BeautifulSoup In this article, we are going to see how to extract CSS from an HTML document or URL using python. Module Needed: bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below
2 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Extract images from video in Python
OpenCV comes with many powerful video editing functions. In current scenario, techniques such as image scanning, face recognition can be accomplished using OpenCV. Image Analysis is a very common field in the area of Computer Vision. It is the extraction of meaningful information from videos or images. OpenCv library can be used to perform multiple
2 min read
Python | Extract URL from HTML using lxml
Link extraction is a very common task when dealing with the HTML parsing. For every general web crawler that's the most important function to perform. Out of all the Python libraries present out there, lxml is one of the best to work with. As explained in this article, lxml provides a number of helper function in order to extract the links. lxml in
4 min read
How to Extract Wikipedia Data in Python?
In this article we will learn how to extract Wikipedia Data Using Python, Here we use two methods for extracting Data. Method 1: Using Wikipedia module In this method, we will use the Wikipedia Module for Extracting Data. Wikipedia is a multilingual online encyclopedia created and maintained as an open collaboration project by a community of volunt
5 min read
Python | Extract Combination Mapping in two lists
Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let's discuss certain way in which this problem can be solved. Method : Using zip() + product() With these functions thi
2 min read
Extract numbers from a text file and add them using Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program
4 min read
Python program to extract a single value from JSON response
We will discuss how Python can be used to extract a value from a JSON response using API and JSON files. Extract value from the JSON response using the API Initially, use the API Key variable to declare the base URL. Where the first currency needs to be converted with the second, ask the user to enter a currency name and save it in a variable. The
3 min read
How to extract Audio Wave from a mixture of Signal using Scipy - Python?
Prerequisites: Scipy Spectral Analysis refers to analyzing of the frequency spectrum/response of the waves. This article as the title suggests deals with extracting audio wave from a mixture of signals and what exactly goes into the process can be explained as: Consider we have 3 mixed Audio Signals having frequency of 50Hz,1023Hz &amp; 1735Hz resp
7 min read
Extract week number from date in Pandas-Python
Many times, when working with some data containing dates we may need to extract the week number from a particular date. In Python, it can be easily done with the help of pandas. Example 1: C/C++ Code # importing pandas as pd import pandas as pd # creating a dictionary containing a date dict = {'Date':[&amp;quot;2015-06-17&amp;quot;]} # converting t
2 min read
Extract IP address from file using Python
Let us see how to extract IP addresses from a file using Python. Algorithm : Import the re module for regular expression.Open the file using the open() function.Read all the lines in the file and store them in a list.Declare the pattern for IP addresses. The regex pattern is : r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'For every element of the list sea
2 min read
Build an Application to extract URL and Metadata from a PDF using Python
The PDF (Portable Document Format) is the most common use platform-independent file format developed by Adobe to present documents. There are lots of PDF-related packages for Python, one of them is the pdfx module. The pdfx module is used to extract URL, MetaData, and Plain text from a given PDF or PDF URL. Features: Extract references and metadata
3 min read
Python - Extract String elements from Mixed Matrix
Given a Matrix, Extract all the elements that are of string data type. Input : test_list = [[5, 6, 3], ["Gfg", 3], [9, "best", 4]] Output : ['Gfg', 'best'] Explanation : All strings are extracted.Input : test_list = [["Gfg", 3], [9, "best", 4]] Output : ['Gfg', 'best'] Explanation : All strings are extracted. Method #1 : Using list comprehension +
6 min read
Create a GUI to Extract information from VIN number Using Python
Prerequisite: Python GUI – tkinter In this article, we are going to look at how can we use Python to extract vehicle information from its VIN number (Vehicle Identification Number). A VIN consists of 17 characters (digits and capital letters) that act as a unique identifier for the vehicle. It is a unique code that is assigned to every motor vehicl
3 min read
Article Tags :
Practice Tags :