473,394 Members | 1,737 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How to get rid of a character from a password

32
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?

Expand|Select|Wrap|Line Numbers
  1. import os
  2. import random
  3. from Tkinter import *
  4. from tkMessageBox import *
  5.  
  6. class Application(Frame):
  7.     def __init__(self, master=None):
  8.         Frame.__init__(self, master)
  9.         self.grid()
  10.         self._passwordLength = StringVar()
  11.         self._passwordLength.set("")
  12.         self._passwordAmount = StringVar()   # create a String control variable
  13.         self._passwordAmount.set("")
  14.         self._fileName = StringVar()
  15.         self._fileName.set("")
  16.         top = self.winfo_toplevel()  # find top-level window
  17.         top.title("Random Password Generator")
  18.         self._createWidgets()
  19.  
  20.     def _createWidgets(self):
  21.         siteLabel = Label(self, text="Password Lengths Wanted:", anchor = E, width = 20)
  22.         siteLabel.grid(row = 0, column = 0)
  23.         siteLabel = Label(self, text="Password Amount Wanted:", anchor = E, width = 20)
  24.         siteLabel.grid(row = 1, column = 0)
  25.         siteLabel = Label(self, text="File Name:", anchor = E, width = 20)
  26.         siteLabel.grid(row = 2, column = 0)
  27.         lengthEntry = Entry(self, takefocus = 1,
  28.                           textvariable = self._passwordLength)
  29.         lengthEntry.grid(row = 0, column = 1, sticky=E+W)
  30.         amountEntry = Entry(self, takefocus = 1,
  31.                           textvariable = self._passwordAmount)
  32.         amountEntry.grid(row = 1, column = 1, sticky=E+W)
  33.         fileEntry = Entry(self, takefocus = 1,
  34.                           textvariable = self._fileName)
  35.         fileEntry.grid(row = 2, column = 1, sticky=E+W)
  36.         self._button = Button(self, text = "Generate", command = self._getData, width = 20)
  37.         self._button.grid(row = 3, column = 0)
  38.         self._button = Button(self, text = "Quit", command = self._quitProgram, width = 20)
  39.         self._button.grid(row = 3, column = 1)
  40.  
  41.     def _getData(self):
  42.         try:
  43.             passwordLength = int(self._passwordLength.get())
  44.             passwordAmount = int(self._passwordAmount.get())
  45.         except:
  46.             showwarning("Error","Please check you input.")
  47.         self._generatePasswords(passwordLength, passwordAmount)
  48.  
  49.     def _generatePasswords(self, passwordLength, passwordAmount):
  50.         fileName = str(self._fileName.get())
  51.         if ".txt" not in fileName:
  52.             fileName += ".txt"
  53.         if os.path.isfile(fileName):
  54.             if askyesno("Verify", "This file already exists, would you like to overwrite it?"):
  55.                 fileToWrite = open(fileName, "w")
  56.         else:
  57.             fileToWrite = open(fileName, "w")
  58.         try:
  59.             randomize(passwordLength, passwordAmount, fileToWrite)
  60.             if True:
  61.                 showwarning("Random Password Generator", "Passwords Created! Check your folder!")
  62.         except:
  63.             showwarning("Error"," Please check your input.")
  64.  
  65.     def _quitProgram(self):
  66.         if askyesno('Verify', 'Are you sure you would like to quit the program?'):
  67.             root.destroy()
  68.  
  69. # end class Application
  70.  
  71. def main():
  72.     Application().mainloop()
  73.  
  74. def randomize(length, amount, fileToWrite):
  75.     for num in xrange(amount):
  76.         newPassword = ""
  77.         for count in xrange(length):
  78.             randomInt = random.randint(0,26)
  79.             newPassword += chr(randomInt+97)
  80.             count += 1
  81.         fileToWrite.write(newPassword+"\n")
  82.     fileToWrite.close()
  83.  
  84. root = Tk()
  85. main()
  86.  
Dec 6 '10 #1

✓ answered by gershwyn

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
Expand|Select|Wrap|Line Numbers
  1. randomInt = random.randint(0, 25)
and see where that gets you.

7 2141
gershwyn
122 100+
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
Expand|Select|Wrap|Line Numbers
  1. randomInt = random.randint(0, 25)
and see where that gets you.
Dec 6 '10 #2
Fuugie
32
Worked like a charm. Thank you! :]

Also, if it isn't too much to ask. How would I format this:
Expand|Select|Wrap|Line Numbers
  1. try:
  2.             randomize(passwordLength, passwordAmount, fileToWrite)
  3.             if True:
  4.                 showwarning("Random Password Generator", "Passwords Created! Check your folder!")
  5.  
So it would say "Passwords Created! Check your folder for (file name)!"
Dec 6 '10 #3
bvdet
2,851 Expert Mod 2GB
Expand|Select|Wrap|Line Numbers
  1. 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.
Expand|Select|Wrap|Line Numbers
  1. >>> import string
  2. >>> import random
  3. >>> passwordLen = 8
  4. >>> seq = string.digits+string.ascii_letters
  5. >>> "".join([random.choice(seq) for i in range(passwordLen)])
  6. 'v5JuKQoT'
  7. >>> 
Dec 6 '10 #4
dwblas
626 Expert 512MB
You can use a loop to create the 3 labels if you want.
Expand|Select|Wrap|Line Numbers
  1.         for ctr, lit in enumerate(["Password Lengths Wanted:", "Password Amount Wanted:", "File Name:"]):
  2.             siteLabel = Label(self, text=lit, anchor = E, width = 20)
  3.             siteLabel.grid(row = ctr, column = 0) 
Also, you have 2 separate varaibles named "count". The second one does nothing here and can be deleted.
Expand|Select|Wrap|Line Numbers
  1. def randomize(length, amount, fileToWrite):
  2.     for num in xrange(amount):
  3.         newPassword = ""
  4.         for count in xrange(length):
  5.             randomInt = random.randint(0,26)
  6.             newPassword += chr(randomInt+97)
  7.             ## this does nothing so it can be deleted            
  8.             count += 1 
Dec 7 '10 #5
Fuugie
32
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?
Dec 7 '10 #6
bvdet
2,851 Expert Mod 2GB
Sorry it took so long to respond.

I would rewite function randomize as follows:
Expand|Select|Wrap|Line Numbers
  1. import string, random
  2.  
  3. def randomize(length, amount, fileToWrite):
  4.     seq = string.digits+string.ascii_letters
  5.     fileToWrite.write("\n".join(["".join([random.choice(seq) \
  6.                                           for i in range(length)]) \
  7.                                               for i in xrange(amount)]))
  8.     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.
Dec 9 '10 #7
Fuugie
32
Thanks again for the help bvdet! It worked out great!
Dec 9 '10 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Lobang Trader | last post by:
Hi all, I am trying to create a username and a password class. I would like to know what are the RECOMMENDED minimum and maximum length for both fields? These fields will be something like...
1
by: Nitin | last post by:
I have created a console based application using C# which asks for the user identification to work using that system. Now, the problem is that i'm not able to hide or encrypt the password on the...
5
by: Skeleton Man | last post by:
Hi, I came across the basic algorithmfor decrypting WS_FTP Pro 6 passwords as follows, and I'm trying to reverse it to make an encryption function: function ws_dec() { var str =...
3
by: julianmoors | last post by:
Hey, Currently I'm writing a VB.NET/1.1 app and I need to mask the input for the password field. Does anyone know how to do this in VB? I've seen a C# example, but wouldn't know how to convert...
2
by: UJ | last post by:
Does anybody have lying around a Regex for a strong password (or a routine to check it). I'd like the normal First character has to be a character, total of 8 characters and has to have at least...
1
by: JIM.H. | last post by:
I have a password field in my login page (ASP.NET 1.1), how can I validate password based on at least 6 characters, one number, and one capital letter.
3
by: Gilbert | last post by:
I am trying to install DB2 connect V 8.2 on my new Windows XP PC, a Dell Optiplex GX620 with 4GB of RAM. I have installed this version of DB2 connect on other Windows XP PC's without any problem....
7
by: rajbala.3399 | last post by:
Hi , I want to download sql in my linux system........... # rpm -ivh MySQL-server-5.0.24a-0.glibc23.i386.rpm MySQL-cl ient-5.0.24a-0.glibc23.i386.rpm Preparing... ...
6
by: ssetz | last post by:
Hello, For work, I need to write a password filter. The problem is that my C+ + experience is only some practice in school, 10 years ago. I now develop in C# which is completely different to me....
7
by: Thana1995 | last post by:
Write a program that asks the user to give a two-character password(defined by constants within the program). the program should then test the validity of the password. if it is incorrect after three...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.