Welcome, guest | Sign In | My Account | Store | Cart

Generate strong random passwords of specified length.

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import random
import string
import time

def mkpass(size=16):
    chars = []
    chars.extend([i for i in string.ascii_letters])
    chars.extend([i for i in string.digits])
    chars.extend([i for i in '\'"!@#$%&*()-_=+[{}]~^,<.>;:/?'])
    
    passwd = ''
    
    for i in range(size):
        passwd += chars[random.randint(0,  len(chars) - 1)]
        
        random.seed = int(time.time())
        random.shuffle(chars)
        
    return passwd

3 comments

Anton Kapishev 13 years, 8 months ago  # | flag

Thanks for sample. Instead

passwd += chars[random.randint(0, len(chars) - 1)]

better use

passwd += random.choice(chars)

James Mills 13 years, 8 months ago  # | flag

Hi,

This is probably a smaller and perhaps more optimal solution to the same problem:

import string import random

validCharacters = string.ascii_letters + string.digits validCharacters = validCharacters.strip("oO0") return string.join( [random.choice(validCharacters) for x in range(n)], "")

Stephen Chappell 13 years, 8 months ago  # | flag

This is a program that I use when a strong, random password is needed.

import string, random

def main():
    total = string.ascii_letters + string.punctuation + string.digits
    password = ''.join(random.sample(total, 30))
    while not approved(password):
        password = ''.join(random.sample(total, 30))
    print(password)

def approved(password):
    group = select(password[0])
    for character in password[1:]:
        trial = select(character)
        if trial is group:
            return False
        group = trial
    return True

def select(character):
    for group in (string.ascii_uppercase,
                  string.ascii_lowercase,
                  string.punctuation,
                  string.digits):
        if character in group:
            return group
    raise ValueError('Character was not found in any group!')

if __name__ == '__main__':
    main()

For better cryptographic use, random.SystemRandom() should be used.