Create a simple program to generate password with python 2 and wxPython

A few years ago I have developed a simple program which will help me to generate password as well as keeps those password for later use which I would like to share with you all today!

Although this program is for windows user but if you are using linux and os-x you can copy the source code below this article and then compile this program in your own operating system. If you have decided to compile the program and run it under your operating system then you will need to install both python 2 and wxPython in your computer. Otherwise if your computer’s operating system is windows then just go ahead and download the .exe file for either the 32 or 64 bit windows os.

If you are windows os user then…

Go ahead and download the .exe file for either the 32 bit or 64 bit windows os through this link. Next click on the .exe file to install the program on your pc. Once the application has been installed on your laptop or pc you need to open it up then we can start to see what we can do with this software.

safty pass
saftypass

Lets create your first password by clicking on the first icon from the left to open up the password generator.

create password!
create password!

Enter how many characters you need for that new password, the user name of your website and the domain name of your website accordingly then press the Generate Password button to create the new password, next click the Close button to close the form.

The second icon will open up the container which shows you all the domain name you have entered, click on one of them to show the password for that website.

select any domain name then press ok

After you have pressed the Ok button you will see the user name and the password of that website within the input form.

username and password
username and password

If you want to keep a copy of those passwords you have generated then it is simple and easy, just click on the third icon from the left and select a directory in your laptop or pc to keep the text file of those passwords.

The fourth icon from the left will help you to look for the password you have created, all you have to do is to enter the domain name of your website under the text input form then press that button to look for it’s password.

domain name user name and password
domain name user name and password

If you want to open up your password pickle file which is inside the SFT folder with the filename of password.pickle then press the fifth button from the left. The SFT folder is the one appears on your computer hard drive once you have installed the program.

It is always better to create another pickle file just to avoid losing it so click on the sixth button from the left to create another copy of the password.pickle file. You can open up that pickle file anytime with the fifth button from the left.

If you want to delete the password then just go ahead and click on the seventh button from the left and select any domain name which you wish to delete from the password database.

select the domain name to delete
select the domain name to delete

Click on the last icon will bring you to the tutorial page of this software which is here!

I have used this program to generate lots of passwords and it is still the only program which I use up till today to create all the passwords for my websites.

If your os is linux and os-x…

Here is the source code file for the entire program, you can copy, modify and then turn the program into an application for your linux or the os-x operating system. If you use windows and decided to DIY then you can copy the source code to any IDE but make sure you have wxPython and python 2 installed in your pc or laptop.

import wx
import webbrowser
import string
import pickle
from random import choice
import os

class SaftyPasswordFrame(wx.Frame):

    def __init__(self, parent, title):    
        super(SaftyPasswordFrame, self).__init__(parent, title=title, size=(333, 133), style=wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.SYSTEM_MENU)
        icon_path = self.resource_path('password.png')
        icon = wx.Icon(icon_path, wx.BITMAP_TYPE_PNG)
        self.SetIcon(icon)
        self.InitUI()
        self.gatherDatas()

    def gatherDatas(self):
        help_path = self.resource_path('help.txt')
        self.data_folder_path = 'C:\\SFT'
        data_path = os.path.join(self.data_folder_path, 'data.pickle')
        try:
            with open(data_path, 'rb') as fld:
                self.data_dictionary = pickle.load(fld)
            if(self.data_dictionary['tip'] == True):
                tip = wx.CreateFileTipProvider(help_path, 0)
        	show = wx.ShowTip(None, tip, True)
        	self.data_dictionary['tip'] = show
                with open(data_path, 'wb') as fld:
                    pickle.dump(self.data_dictionary, fld)
        except IOError as ioerr:
            self.data_dictionary = {}
	    tip = wx.CreateFileTipProvider(help_path, 0)
            show = wx.ShowTip(None, tip, True)
            self.data_dictionary['tip'] = show
            self.data_dictionary['passwordpath'] = 'C:\\SFT'
            os.makedirs(self.data_folder_path)
            data_path = os.path.join(self.data_folder_path, 'data.pickle')
            with open(data_path, 'wb') as fld:
                pickle.dump(self.data_dictionary, fld)
            webbrowser.open('http://islandtropicaman.com/create-a-simple-program-to-generate-password-with-python-2-and-wxpython/')

    def InitUI(self):
      
        panel = wx.Panel(self)
        
        sizer = wx.GridBagSizer(5,5)
        self.search = False

        icon = wx.StaticBitmap(panel, bitmap=wx.ArtProvider.GetBitmap(wx.ART_FOLDER, size=(23, 23)))
        icon.Bind(wx.EVT_LEFT_DOWN, self.onCreatePasswordClick) 
        sizer.Add(icon, pos=(0, 0), flag=wx.TOP|wx.RIGHT|wx.ALIGN_LEFT, border=5)

        icon1 = wx.StaticBitmap(panel, bitmap=wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, size=(23, 23)))
        icon1.Bind(wx.EVT_LEFT_DOWN, self.onOpenPassWordClick) 
        sizer.Add(icon1, pos=(0, 1), flag=wx.TOP|wx.RIGHT|wx.ALIGN_LEFT, border=5)

        icon2 = wx.StaticBitmap(panel, bitmap=wx.ArtProvider.GetBitmap(wx.ART_PRINT, size=(23, 23)))
        icon2.Bind(wx.EVT_LEFT_DOWN, self.onOpenReportClick) 
        sizer.Add(icon2, pos=(0, 2), flag=wx.TOP|wx.RIGHT|wx.ALIGN_LEFT, border=5)

        icon3 = wx.StaticBitmap(panel, bitmap=wx.ArtProvider.GetBitmap(wx.ART_PASTE, size=(23, 23)))
        icon3.Bind(wx.EVT_LEFT_DOWN, self.onOpenSearchClick) 
        sizer.Add(icon3, pos=(0, 3), flag=wx.TOP|wx.RIGHT|wx.ALIGN_LEFT, border=5)

        icon4 = wx.StaticBitmap(panel, bitmap=wx.ArtProvider.GetBitmap(wx.ART_TIP, size=(23, 23)))
        icon4.Bind(wx.EVT_LEFT_DOWN, self.onOpenFileClick) 
        sizer.Add(icon4, pos=(0, 4), flag=wx.TOP|wx.RIGHT|wx.ALIGN_LEFT, border=5)

        icon5 = wx.StaticBitmap(panel, bitmap=wx.ArtProvider.GetBitmap(wx.ART_REDO, size=(23, 23)))
        icon5.Bind(wx.EVT_LEFT_DOWN, self.onOpenPickleClick) 
        sizer.Add(icon5, pos=(0,5), flag=wx.TOP|wx.RIGHT|wx.ALIGN_LEFT, border=5)

        icon6 = wx.StaticBitmap(panel, bitmap=wx.ArtProvider.GetBitmap(wx.ART_QUIT, size=(23, 23)))
        icon6.Bind(wx.EVT_LEFT_DOWN, self.onOpenDeleteClick) 
        sizer.Add(icon6, pos=(0,6), flag=wx.TOP|wx.RIGHT|wx.ALIGN_LEFT, border=5)

        icon7 = wx.StaticBitmap(panel, bitmap=wx.ArtProvider.GetBitmap(wx.ART_GO_HOME, size=(23, 23)))
        icon7.Bind(wx.EVT_LEFT_DOWN, self.onOpenHelpClick) 
        sizer.Add(icon7, pos=(0,7), flag=wx.TOP|wx.RIGHT|wx.ALIGN_LEFT, border=5)

        line = wx.StaticLine(panel)
        sizer.Add(line, pos=(1, 0), span=(1, 8), flag=wx.EXPAND|wx.BOTTOM, border=6)

        self.tc2 = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
        sizer.Add(self.tc2, pos=(2, 0), span=(3, 8), flag=wx.TOP|wx.EXPAND)

        sizer.AddGrowableCol(2)
        
        panel.SetSizer(sizer)

    def onOpenDeleteClick(self, event):
        self.tc2.Clear()
        websites = []
        data_path = os.path.join(self.data_folder_path, 'data.pickle')
        with open(data_path, 'rb') as fld:
            self.data_dictionary = pickle.load(fld)
        passworddirpath = self.data_dictionary['passwordpath']
        passwordpath = os.path.join(passworddirpath, 'password.pickle')
        try:
            with open(passwordpath, 'rb') as fld:
                self.password_dictionary = pickle.load(fld)
        except IOError as ioerr:
            self.password_dictionary = {}
        for the_key, the_value in self.password_dictionary.iteritems():
            websites.append(the_key)
        websites.sort()        
        dialog = wx.SingleChoiceDialog(self, "Select A Website", "Delete Password", websites, wx.CHOICEDLG_STYLE)
        if dialog.ShowModal() == wx.ID_OK:
            self.website = dialog.GetStringSelection()
            if(self.website!=''):
                del self.password_dictionary[self.website]
                with open(passwordpath, 'wb') as fld:
                    pickle.dump(self.password_dictionary, fld)
                    wx.MessageBox('Select site has been deleted', 'Success', wx.OK | wx.ICON_INFORMATION)
        dialog.Destroy()

    def onOpenSearchClick(self, event):
        if(self.search == False):
            self.tc2.Clear()
            self.search = True
            wx.MessageBox('Enter search term into below text box then click the search icon again', 'Search Password', wx.OK | wx.ICON_INFORMATION)
        elif(self.search == True):
            searchterm = str(self.tc2.GetValue())
            if(searchterm!=''):
                 self.tc2.Clear()
                 content = ''
                 data_path = os.path.join(self.data_folder_path, 'data.pickle')
                 with open(data_path, 'rb') as fld:
                     self.data_dictionary = pickle.load(fld)
                     passworddirpath = self.data_dictionary['passwordpath']
                     passwordpath = os.path.join(passworddirpath, 'password.pickle')
                 try:
                     with open(passwordpath, 'rb') as fld:
                         self.password_dictionary = pickle.load(fld)
                 except IOError as ioerr:
                     self.password_dictionary = {}
                 for the_key, the_value in self.password_dictionary.iteritems():
                     if(the_key.find(searchterm)!=-1):
                         content += the_key+' '+self.password_dictionary[the_key][0]+' '+self.password_dictionary[the_key][1]+'\n'
                 self.tc2.AppendText(content)
            self.search = False
            wx.MessageBox('Click search icon again and enter another search term', 'Search Again?', wx.OK | wx.ICON_INFORMATION)

    def onOpenPickleClick(self, event):
        wx.MessageBox('Select a directory to create password file in the pickle format', 'Select Directory', wx.OK | wx.ICON_INFORMATION)
        dialog = wx.DirDialog(self, message="Choose a directory", defaultPath="", style=wx.DD_NEW_DIR_BUTTON, pos = wx.DefaultPosition, size = wx.DefaultSize,
                                  name="sfpDirCtrl")
        if(dialog.ShowModal()==wx.ID_CANCEL):   
            wx.MessageBox('You have not select any directory to create the password file', 'Select Directory', wx.OK | wx.ICON_INFORMATION)
        else:             
            dirpath = str(dialog.GetPath())
            newpassfilepath = os.path.join(dirpath, 'PassWord.pickle')
            data_path = os.path.join(self.data_folder_path, 'data.pickle')
            with open(data_path, 'rb') as fld:
                self.data_dictionary = pickle.load(fld)
            passworddirpath = self.data_dictionary['passwordpath']
            passwordpath = os.path.join(passworddirpath, 'password.pickle')
            try:
                with open(passwordpath, 'rb') as fld:
                    self.password_dictionary = pickle.load(fld)
            except IOError as ioerr:
                self.password_dictionary = {}
            try:
                with open(newpassfilepath, 'wb') as fld:
                    pickle.dump(self.password_dictionary, fld)
                wx.MessageBox('New password file has been created', 'Success', wx.OK | wx.ICON_INFORMATION)
            except IOError as ioerr:
                wx.MessageBox('Can\'t write to file!', 'Error', wx.OK | wx.ICON_INFORMATION)
                
        dialog.Destroy()

    def onOpenReportClick(self, event):
        wx.MessageBox('Select directory to save the password in text file format', 'Select Directory', wx.OK | wx.ICON_INFORMATION)
        dialog = wx.DirDialog(self, message="Choose a directory", defaultPath="", style=wx.DD_NEW_DIR_BUTTON, pos = wx.DefaultPosition, size = wx.DefaultSize,
                                  name="sftDirCtrl")
        if(dialog.ShowModal()==wx.ID_CANCEL):   
            wx.MessageBox('You have not select any directory to create the password data file', 'Select Directory', wx.OK | wx.ICON_INFORMATION)
        else:             
            dirpath = str(dialog.GetPath())
            newpassfilepath = os.path.join(dirpath, 'PassWord.txt')
            content = ''
            data_path = os.path.join(self.data_folder_path, 'data.pickle')
            with open(data_path, 'rb') as fld:
                self.data_dictionary = pickle.load(fld)
            passworddirpath = self.data_dictionary['passwordpath']
            passwordpath = os.path.join(passworddirpath, 'password.pickle')
            try:
                with open(passwordpath, 'rb') as fld:
                    self.password_dictionary = pickle.load(fld)
            except IOError as ioerr:
                self.password_dictionary = {}
            for the_key, the_value in self.password_dictionary.iteritems():
                content += 'website : '+the_key+', username : '+self.password_dictionary[the_key][0]+', password : '+self.password_dictionary[the_key][1]+'\n'
            try:
                with open(newpassfilepath, "w") as f:
                    f.write(content)
                wx.MessageBox('Password text file has been created', 'Success', wx.OK | wx.ICON_INFORMATION)
            except IOError as ioerr:
                wx.MessageBox('Can\'t write to file!', 'Error', wx.OK | wx.ICON_INFORMATION)
                
        dialog.Destroy()

    def onOpenFileClick(self, event):
        self.tc2.Clear()
        self.search = False
        dialog = wx.FileDialog(self, message="Choose file", wildcard="password.pickle", style=wx.OPEN)  
        if dialog.ShowModal() == wx.ID_OK:
            dirpath = str(dialog.GetPath())
            websites = []
            content = ''
            try:
                with open(dirpath, 'rb') as fld:
                    self.password_dictionary = pickle.load(fld)
            except IOError as ioerr:
                self.password_dictionary = {}
            for the_key, the_value in self.password_dictionary.iteritems():
                websites.append(the_key)
            websites.sort()        
            dialog = wx.SingleChoiceDialog(self, "Select A Website", "Show Password", websites, wx.CHOICEDLG_STYLE)
            if dialog.ShowModal() == wx.ID_OK:
                self.website = dialog.GetStringSelection()
                if(self.website!=''):
                    content = 'username : ' + self.password_dictionary[self.website][0] + ', password : ' + self.password_dictionary[self.website][1]
                    self.tc2.AppendText(content)
        else:
            wx.MessageBox('You need to select a password file', 'Error', wx.OK | wx.ICON_INFORMATION)
        dialog.Destroy()

    def onOpenHelpClick(self, event):
        webbrowser.open('http://islandtropicaman.com/create-a-simple-program-to-generate-password-with-python-2-and-wxpython/')

    def onCreatePasswordClick(self, event):
        dialog = CreateNewPassWordDialog(self)
        if dialog.ShowModal() == wx.ID_OK:
            dialog.Destroy()

    def onOpenPassWordClick(self, event):
        websites = []
        self.search = False
        self.password_dictionary = ''
        self.tc2.Clear()
        data_path = os.path.join(self.data_folder_path, 'data.pickle')
        with open(data_path, 'rb') as fld:
            self.data_dictionary = pickle.load(fld)
        passworddirpath = self.data_dictionary['passwordpath']
        passwordpath = os.path.join(passworddirpath, 'password.pickle')
        try:
            with open(passwordpath, 'rb') as fld:
                self.password_dictionary = pickle.load(fld)
        except IOError as ioerr:
            self.password_dictionary = {}
        for the_key, the_value in self.password_dictionary.iteritems():
            websites.append(the_key)
        websites.sort()        
        dialog = wx.SingleChoiceDialog(self, "Select A Website", "Show Password", websites, wx.CHOICEDLG_STYLE)
        if dialog.ShowModal() == wx.ID_OK:
            self.website = dialog.GetStringSelection()
            if(self.website!=''):
                content = 'username : ' + self.password_dictionary[self.website][0] + ', password : ' + self.password_dictionary[self.website][1]
                self.tc2.AppendText(content)
        dialog.Destroy()

    def resource_path(self, relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")

        return os.path.join(base_path, relative_path)

class CreateNewPassWordDialog(wx.Dialog):
    
    def __init__(self, *args, **kw):
        super(CreateNewPassWordDialog, self).__init__(*args, **kw)           
        self.InitUI()
        self.SetSize((423, 113))
        self.SetTitle("Create Password")
         
    def InitUI(self):
        vbox = wx.BoxSizer(wx.VERTICAL)     
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        text0 = wx.StaticText(self, label="Character : ")
        self.tc5 = wx.TextCtrl(self, size=(33, -1) )
        text1 = wx.StaticText(self, label=" Username : ")
        self.tc6 = wx.TextCtrl(self, size=(100, -1) )
        text2 = wx.StaticText(self, label=" Website : ")
        self.tc8 = wx.TextCtrl(self, size=(100, -1) )
        hbox1.Add(text0)
        hbox1.Add(self.tc5)
        hbox1.Add(text1)
        hbox1.Add(self.tc6)
        hbox1.Add(text2)
        hbox1.Add(self.tc8)
        
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        button1 = wx.Button(self, label='Generate Password')
        button2 = wx.Button(self, label='Close')
        hbox3.Add(button1)
        hbox3.Add(button2, flag=wx.LEFT)
        
        vbox.Add(hbox1, flag=wx.ALL|wx.EXPAND, border=6)
        vbox.Add(hbox3, flag=wx.ALL|wx.EXPAND, border=10)

        self.SetSizer(vbox)
        
        button1.Bind(wx.EVT_BUTTON, self.OnCreatePassword)
        button2.Bind(wx.EVT_BUTTON, self.OnClose)  
        
    def OnClose(self, event):      
        self.Destroy()

    def OnCreatePassword(self, event):
        self.username = str(self.tc6.GetValue())
        self.character = self.tc5.GetValue()
        self.website = str(self.tc8.GetValue())
        if(self.character.isdigit() == False):
            wx.MessageBox('Please enter a number', 'Error', wx.OK | wx.ICON_INFORMATION)
        elif(self.username != '' and self.website != ''):        
            chars=string.letters+string.digits
            password = ''        
            for i in range(int(self.character)):
                password += ''.join(choice(chars))
            self.data_folder_path = 'C:\\SFT'
            data_path = os.path.join(self.data_folder_path, 'data.pickle')
            with open(data_path, 'rb') as fld:
                self.data_dictionary = pickle.load(fld)
            passworddirpath = self.data_dictionary['passwordpath']
            passwordpath = os.path.join(passworddirpath, 'password.pickle')
            try:
                with open(passwordpath, 'rb') as fld:
                    self.password_dictionary = pickle.load(fld)
                    self.password_dictionary[self.website] = [self.username, password]
                    with open(passwordpath, 'wb') as fld:
                        pickle.dump(self.password_dictionary, fld)
                        wx.MessageBox('New password has been created', 'Success', wx.OK | wx.ICON_INFORMATION)
            except IOError as ioerr:
                self.password_dictionary = {}
                self.password_dictionary[self.website] = [self.username, password]
                with open(passwordpath, 'wb') as fld:
                    pickle.dump(self.password_dictionary, fld)
                    wx.MessageBox('New password has been created', 'Success', wx.OK | wx.ICON_INFORMATION)

class SaftyPasswordApp(wx.App):
    def OnInit(self): 
        self.frame = SaftyPasswordFrame(None, title="Safety Password 1.0.0")
        self.SetTopWindow(self.frame)
        self.frame.Centre()
        self.frame.Show()
        return True

if __name__ == '__main__':

    app = SaftyPasswordApp()
    app.MainLoop()

Thank you for using this old program of mine which is still useful up until today, go ahead and subscribe to this blog for more free source code and other very useful information once we have one ready for you!

Like this post? Kindly share!