How to get rid of a character from a password

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fuugie
    New Member
    • Sep 2010
    • 32

    How to get rid of a character from a password

    I made a random password generator for a project and it works fine, but when it generates passwords, it always adds " { " to a password or two. Why does it add this and how do I fix it?

    Code:
    import os
    import random
    from Tkinter import *
    from tkMessageBox import *
    
    class Application(Frame):
        def __init__(self, master=None):
            Frame.__init__(self, master)
            self.grid()
            self._passwordLength = StringVar()
            self._passwordLength.set("")
            self._passwordAmount = StringVar()   # create a String control variable
            self._passwordAmount.set("")
            self._fileName = StringVar()
            self._fileName.set("")
            top = self.winfo_toplevel()  # find top-level window
            top.title("Random Password Generator")
            self._createWidgets()
    
        def _createWidgets(self):
            siteLabel = Label(self, text="Password Lengths Wanted:", anchor = E, width = 20)
            siteLabel.grid(row = 0, column = 0)
            siteLabel = Label(self, text="Password Amount Wanted:", anchor = E, width = 20)
            siteLabel.grid(row = 1, column = 0)
            siteLabel = Label(self, text="File Name:", anchor = E, width = 20)
            siteLabel.grid(row = 2, column = 0)
            lengthEntry = Entry(self, takefocus = 1,
                              textvariable = self._passwordLength)
            lengthEntry.grid(row = 0, column = 1, sticky=E+W)
            amountEntry = Entry(self, takefocus = 1,
                              textvariable = self._passwordAmount)
            amountEntry.grid(row = 1, column = 1, sticky=E+W)
            fileEntry = Entry(self, takefocus = 1,
                              textvariable = self._fileName)
            fileEntry.grid(row = 2, column = 1, sticky=E+W)
            self._button = Button(self, text = "Generate", command = self._getData, width = 20)
            self._button.grid(row = 3, column = 0)
            self._button = Button(self, text = "Quit", command = self._quitProgram, width = 20)
            self._button.grid(row = 3, column = 1)
    
        def _getData(self):
            try:
                passwordLength = int(self._passwordLength.get())
                passwordAmount = int(self._passwordAmount.get())
            except:
                showwarning("Error","Please check you input.")
            self._generatePasswords(passwordLength, passwordAmount)
    
        def _generatePasswords(self, passwordLength, passwordAmount):
            fileName = str(self._fileName.get())
            if ".txt" not in fileName:
                fileName += ".txt"
            if os.path.isfile(fileName):
                if askyesno("Verify", "This file already exists, would you like to overwrite it?"):
                    fileToWrite = open(fileName, "w")
            else:
                fileToWrite = open(fileName, "w")
            try:
                randomize(passwordLength, passwordAmount, fileToWrite)
                if True:
                    showwarning("Random Password Generator", "Passwords Created! Check your folder!")
            except:
                showwarning("Error"," Please check your input.")
                
        def _quitProgram(self):
            if askyesno('Verify', 'Are you sure you would like to quit the program?'):
                root.destroy()
    
    # end class Application
    
    def main():
        Application().mainloop()
    
    def randomize(length, amount, fileToWrite):
        for num in xrange(amount):
            newPassword = ""
            for count in xrange(length):
                randomInt = random.randint(0,26)
                newPassword += chr(randomInt+97)
                count += 1
            fileToWrite.write(newPassword+"\n")
        fileToWrite.close()
    
    root = Tk()
    main()
  • gershwyn
    New Member
    • Feb 2010
    • 122

    #2
    In ASCII, the { character follows immediately after lowercase z. When you're generating a random number, you're asking for a value between 0 and 26 inclusive, which gives you 27 possibilities total.

    Try changing line 78 to
    Code:
    randomInt = random.randint(0, 25)
    and see where that gets you.

    Comment

    • Fuugie
      New Member
      • Sep 2010
      • 32

      #3
      Worked like a charm. Thank you! :]

      Also, if it isn't too much to ask. How would I format this:
      Code:
      try:
                  randomize(passwordLength, passwordAmount, fileToWrite)
                  if True:
                      showwarning("Random Password Generator", "Passwords Created! Check your folder!")
      So it would say "Passwords Created! Check your folder for (file name)!"

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Code:
        showwarning("Random Password Generator", "Passwords Created! Check your folder for %s!" % fileToWrite)
        Randomly generated passwords are often made from a combination of digits, upper case letters and lower case letters.
        Code:
        >>> import string
        >>> import random
        >>> passwordLen = 8
        >>> seq = string.digits+string.ascii_letters
        >>> "".join([random.choice(seq) for i in range(passwordLen)])
        'v5JuKQoT'
        >>>

        Comment

        • dwblas
          Recognized Expert Contributor
          • May 2008
          • 626

          #5
          You can use a loop to create the 3 labels if you want.
          Code:
                  for ctr, lit in enumerate(["Password Lengths Wanted:", "Password Amount Wanted:", "File Name:"]):
                      siteLabel = Label(self, text=lit, anchor = E, width = 20)
                      siteLabel.grid(row = ctr, column = 0)
          Also, you have 2 separate varaibles named "count". The second one does nothing here and can be deleted.
          Code:
          def randomize(length, amount, fileToWrite):
              for num in xrange(amount):
                  newPassword = ""
                  for count in xrange(length):
                      randomInt = random.randint(0,26)
                      newPassword += chr(randomInt+97)
                      ## this does nothing so it can be deleted            
                      count += 1

          Comment

          • Fuugie
            New Member
            • Sep 2010
            • 32

            #6
            Thanks bvdet! Your answers are always short, sweet and get right to the point!
            How would I implement your code to making the password more random?

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              Sorry it took so long to respond.

              I would rewite function randomize as follows:
              Code:
              import string, random
              
              def randomize(length, amount, fileToWrite):
                  seq = string.digits+string.ascii_letters
                  fileToWrite.write("\n".join(["".join([random.choice(seq) \
                                                        for i in range(length)]) \
                                                            for i in xrange(amount)]))
                  fileToWrite.close()
              Note that writing to the file once is much faster than writing to the file for each password. The same thing holds true for print.

              Comment

              • Fuugie
                New Member
                • Sep 2010
                • 32

                #8
                Thanks again for the help bvdet! It worked out great!

                Comment

                Working...