Reputation: 60
Im searching for a fast and pythonic way to generate new (forgotten) user passwords with high entropy. To achieve this i use a list with 64 chars which in this code will only be named "chars = []"
The problem is that sometimes chars are more than once (sometimes even triple) in a password. As far as i found out i can remove repeating items from a list with "set". But how can i append new items with this code that dont repeat again? Maybe this could be done all at once when generating it?
I need to say that im quite new to programming. Maybe my code is bad but i was reading much about random and urandom and i am sure i want to use os.urandom. Any suggestions, snippets and hints to make the code better would be very much appreciated.
chars = []
z = map(ord, os.urandom(12))
passw = []
for i in z:
y = int(i) % 64 # modulo each item from urandom to map it to the list
passw.append(chars[y])
print ''.join(passw)
Thank you for taking your time!
Upvotes: 0
Views: 195
Reputation:
Remove each char from the list of available chars after taking it.
import random
import string
def mkpwd(l=12):
# Start with all available characters.
chars = [c for c in string.ascii_letters + string.digits]
# Make sure we don't take more characters than are available.
l = min(l, len(chars))
# Collect the picked characters.
cs = []
for _ in range(l):
# Take a random character from the current list of characters.
i = random.randint(0, len(chars) - 1)
c = chars[i]
cs.append(c)
# Remove the taken character from the list.
# This ensures that every character is only taken once.
del chars[i]
return("".join(cs))
print(mkpwd())
print(mkpwd(24))
print(mkpwd(62))
print(mkpwd(1024))
Output (example):
0GEmMWXYbqeQ
eL83iPTMNatK54Efr2ZhdqWn
fIBj2DTw6P1grGJKZONdv9U8CaWet7l4n5QiFczRhqmxSALHMY0Vskp3oEXbuy
v6Fpt3yrMcGwENTjXODk5W2bZYeL8AqHQ0lJ9oadfIsg7mhBzU14RVnKiuxSPC
Upvotes: 2
Reputation: 4250
Loop while you reach the desired length
passw = ''
while len(passw) <= 12:
char = chars[ord(os.urandom(1)) % 64]
if char not in passw:
passw += char
Upvotes: 2