Python and SQLite: Building password Databases

Python and SQLite: Building password Databases

Sometimes when creating a new media account, thinking of a password every single time could be exhausting. Not to mention the security risk involved with using similar passwords throughout your media accounts. In other situations, you might be asked to think of a “strong password”.

If you've considered using python and sqlite to generate and store passwords, you're in luck.

If not, consider it!

Here, you’ll learn how to:

• Use the time module in python to know how long your program took to run.

• Connect and close connections to the SQLite database.

• Set up random string characters for different password combinations.

• Work with databases.

WHY PYTHON

Python is a simple programming language and pretty easy to learn. It has a simple syntax and works easily on windows and mac terminals. This makes it possible to run codes from the comfort of a command line rather than opening an editor every single time.

WHY SQLITE3

SQLite is basically a relational database management system which is not client-based. In other words, it us used “on disk” and not cloud based, for desktop applications and can be accessed directly from your hard drive/solid state drive without internet connectivity. For this tutorial, we’ll be using SQLite3

If you don’t already have python 3 and SQLite3 installed, simply install python3 from the official python website and watch how to get SQLite up and running for your project here.

PS: You’d need DB browser SQLite to view your passwords in the database when this project is completed. Download BD Browser SQLite here

Wire framing the idea

Ideally, the project consists of three aspects

• Importing the python modules needed(such as strings, time, sqlite3)

• Questions that’ll set a stage towards password generation(for example: how many characters should the password be)

• Connections to the SQLite database to save the generated password.

Importing necessary modules

Import time module: Serves as a medium towards timing the whole interpretation process

Import os : Needed in other to call some operating system(windows) functions Import sqlite3: imports the SQLite module. Necessary to store our passwords

Import string: From this module, we would draw out string characters, letters and numbers for various combinations of our passwords

Import random: Imports the random module which makes it easier to select random string characters from a given set.

```import time

start = time.time()
import os
import sys

import sqlite3

import string
import random

LETTER = string.ascii_letters
NUMBER = string.digits
PUNCTUATIONS = string.punctuation

• Question stage towards password generation

For the next steps, we’ll work with using functions to create various prompted messages. Key ideas:

o A function that asks the user about the password’s length

o A function that asks the user what website he/she plans to use the password on.

o A function that selects random password characters depending on the user’s choice of combination (letters, numbers or punctuations).

Working with functions like these makes your code easier to read and helps simplify and easily call actions without rewriting the code all over again

def create_passLength():
    Hello = input("How many characters should your password be?  ") #Prompts a question
    return int(Hello)    #returns an integer value


def website():
    site = input("What website do you plan to use the password on:  ") #Prompts website question
    return site


password_length = create_passLength()
site = website()


def containment():
#shows the various combination of passwords
    print("""LETTER + NUMBER = LEMBERS \nLETTER + PUNCTUATIONS = LEPUNC \nPUNCTUATION + NUMBER = PUNCBER""")

    containment1 = input(
        "What characters should your password contain(reply with LETTERS,NUMBERS,PUNCTUATIONS,LEMBERS,LEPUNC,PUNCBER or ALL: ")

    if containment1.endswith("ETTER"):
        printable_LETTER = f'{LETTER}'
    return containment1


password_containment = containment() #gives the containment function a variable

print("Number of characters :    ", password_length), print("website:  ", site), print("containment: ", password_containment)

Next, we set up some multiple if else statements(the code is quite simple, don,t bother about the length)

These statements are to decide the action to take depending on the selected pass word combination chosen by the user

def password(password_length):
    if password_containment.endswith("ETTERS"):
        printable_LETTER = f'{LETTER}'
        random_pass_containment = "".join(random.choices(printable_LETTER, k=password_length))

        return random_pass_containment

    elif password_containment.endswith("UMBERS"):
        printable_LETTER = f'{NUMBER}'
        random_pass_containment = "".join(random.choices(printable_LETTER, k=password_length)) 

        return random_pass_containment

    elif password_containment.endswith("TUATIONS"):
        printable_LETTER = f'{PUNCTUATIONS}'
        random_pass_containment = "".join(random.choices(printable_LETTER, k=password_length))

        return random_pass_containment

    elif password_containment.endswith("EMBERS"):
        printable_LETTER = f'{LETTER}{NUMBER}'
        random_pass_containment = "".join(random.choices(printable_LETTER, k=password_length))

        return random_pass_containment

    elif password_containment.endswith("EPUNC"):
        printable_LETTER = f'{LETTER}{PUNCTUATIONS}'
        random_pass_containment = "".join(random.choices(printable_LETTER, k=password_length))

        return random_pass_containment

    elif password_containment.endswith("PUNCBER"):
        printable_LETTER = f'{PUNCTUATIONS}{NUMBER}'
        random_pass_containment = "".join(random.choices(printable_LETTER, k=password_length))

        return random_pass_containment

    elif password_containment.endswith("ALL"):

        random_pass1 = random.choices(printable_list, k=password_length)
        random_pass = "".join(random_pass1)

        return random_pass

The next step is to use all this information and print out a password. To make it a little bit interesting, the "generating password........" line was added which indicates a password processing stage of the code.

password_requested = (password(password_length)) #calls the above password function and assigns it to a variable

print("""GENERATING PASSWORD................\n""") #\n indicates new line

print("PASSWORD: ", password_requested) #prints the password

CREATING DATABASE

Our SQLite data base can be accessed by creating database manually. First:

  • Open your DB Browser for SQLite and you'll see the image below as the home screen

Screenshot (175).png

  • Select "file" from the menu and create a new database within the same directory as this python project file and give it any name of your choice. I gave it the name "TEST". A window would appear where you'd have to fill a table name(mine was PASSWORD) and some other table values as shown below.

Screenshot (176).png

-Hitting the "ok" button results in a table with no values. An example is the one shown below:

Screenshot (178).png

ACCESSING DATABASE WITH PYTHON

  • Our code involves creating a function that'll need two values: The password requested and the website it's needed for in order to save them to the database. We assigned these values to some variables earlier in our code.
  • We connect to the database with the sqlite3.connect function. Your database should have a (.db) extension when imputing it into the code, and then instantiate the database.
  • We insert the password and website into the database table with the cursor.execute function

NOTE:

TEST.db is the name of the database

PASSWORD is the name of the table within the database

  • "INSERT INTO PASSWORDS" code maps the table values with the function values. Similar to key-value pairs in python . This means that "website" in the code below is matched with "site"(a variable gotten from our code earlier which stores the name of the site into the variable). Datetime indicates the date of password generation.
  • Commit commands uploads these values into the database. The full code snippet is shown below
def sqlite_saver(password_requested, site):
    conn = sqlite3.connect("TEST.db")  
    cursor = conn.cursor()  # instantiates the created database

    #Inserting values into the table
    cursor.execute("INSERT INTO PASSWORD" \
                   "(Website, Password, date) VALUES" \
                   "(?,?, DATETIME('now'))", (site, password_requested))

    print("Command executed successfully, password stored in sqlite database!")

    conn.commit()  # commits/uploads the values
    conn.close  # closes connection


sqlite_saver(password_requested, site)

end = time.time()

print("Program took :", (end - start), "seconds to run")

Let's take a look by running the program.

Here's the code:

Screenshot (183).png

The output:

Screenshot (182).png

We would need to access our database and check if this password has been updated. For that, reload your SQLite database from DB Browser. You'd get this result:

Screenshot (185).png

And there you have it. An updated password saved to a database.

Working with database is quite fun and can give you a basic understanding of database management concepts. It's also comfortable to be able to access databases from python code as well.

That's why, I'd write an article on how to access this SQLite database for the password saved using a python program, and give future edits to this article for easier code understanding.

Subscribe and never miss such an important article update.

Cheers tech fam!✌🥂