def generatePassword(length=12): chars = string.ascii_letters+string.digits password = [random_.choice(chars) for x in range(length - 1)] # make sure there is at least one digit digitidx = random_.randbelow(length) password[digitidx:digitidx] = [random_.choice(string.digits)] return ''.join(password)
def encodePassword(plaintext, scheme, other=None, config=None): """Encrypt the plaintext password. """ if plaintext is None: plaintext = "" if scheme == "PBKDF2": if other: rounds, salt, raw_salt, digest = pbkdf2_unpack(other) else: raw_salt = random_.token_bytes(20) salt = h64encode(raw_salt) if config: rounds = config.PASSWORD_PBKDF2_DEFAULT_ROUNDS else: rounds = 10000 if rounds < 1000: raise PasswordValueError("invalid PBKDF2 hash (rounds too low)") raw_digest = pbkdf2(plaintext, raw_salt, rounds, 20) return "%d$%s$%s" % (rounds, salt, h64encode(raw_digest)) elif scheme == 'SSHA': if other: raw_other = b64decode(other) salt = raw_other[20:] else: # new password # variable salt length salt_len = random_.randbelow(52 - 36) + 36 salt = random_.token_bytes(salt_len) s = ssha(s2b(plaintext), salt) elif scheme == 'SHA': s = sha1(s2b(plaintext)).hexdigest() # nosec elif scheme == 'MD5': s = md5(s2b(plaintext)).hexdigest() # nosec elif scheme == 'crypt': if crypt is None: raise PasswordValueError('Unsupported encryption scheme %r' % scheme) if other is not None: salt = other else: saltchars = './0123456789' + string.ascii_letters salt = random_.choice(saltchars) + random_.choice(saltchars) s = crypt.crypt(plaintext, salt) elif scheme == 'plaintext': s = plaintext else: raise PasswordValueError('Unknown encryption scheme %r' % scheme) return s