Created
September 5, 2014 03:07
-
-
Save maliubiao/fc327ea50811cf8be347 to your computer and use it in GitHub Desktop.
random password generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import string | |
letters = string.letters | |
lowercase = string.lowercase | |
uppercase = string.uppercase | |
digits = string.digits | |
punctuation = string.punctuation | |
all_nospace = digits + letters + punctuation | |
def generate_map(collection): | |
collection = "".join(list(set(list(collection)))) | |
klen = len(collection) | |
h = 255 / klen | |
i = 0 | |
k = 0 | |
table = {} | |
while i < 256: | |
if k >= klen: | |
break | |
for j in range(h): | |
table[i+j] = collection[k] | |
i += h | |
k += 1 | |
if 255 % len(collection): | |
t = len(table) | |
for i in range(256 - t): | |
table[t+i] = collection[i] | |
return table | |
def generate(length, collection, mapcache=False): | |
if length < 1 or length > 255: | |
return None | |
result = [] | |
if mapcache: | |
table = mapcache | |
else: | |
table = generate_map(collection) | |
while len(result) != length: | |
for i in os.urandom(length): | |
result.append(table[ord(i)]) | |
return "".join(result) | |
if __name__ == "__main__": | |
print generate(16, letters+digits) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment