I'm trying to generate random passwords for the Active Directory that has the following password requirements: at least 8 characters, at least one special character, at least one digit, at least one lowercase and at least one uppercase.
With the following code I'm able to generate a random password and check whether it contains a special character. New password is generated until a special character is found.
special_char = "!@%/()=?+.-"
password_string = "".join([random.choice(string.ascii_lowercase + string.ascii_digits + string.ascii_uppercase + special_char) for n in range(8)])
while any(c in password_string for c in special_char) is not True:
password_string = "".join([random.choice(string.ascii_lowercase + string.ascii_digits + string.ascii_uppercase + special_char) for n in range(8)])
The problem with the following is that it's only checking for the special character and generating a new password might get rid of the other requirements assuming they existed. How could I implement the AD password requirements efficiently? Thanks for any help.
You could generate a matching password to begin with, by first picking a special char and a digit (and one lower- and one uppercase letter in the same manner), filling up with anything, and shuffling the order in the end:
Use sets and intersection to enforce constraints...
I like Ulrich's answer better. He beat me to it.
Test for all conditions in your
while
test. It is easier to delegate testing for valid passwords to a function:You could implement the requirements one by one..
so before you do anything else create a string that consists of 1 special character randomly chosen. 1 digit character randomly chosen. 1 lowercase character randomly chosen. and 1 uppercase character randomly chosen. thats 4 characters in total, the remaining characters can be randomly chosen, length must be larger than 8.
all generated passwords will no be valid, so no need to check for that..
now you could complain that the passwords will all have the same predictable pattern: special, digit, lowercase, uppercase, randomized stuff..
so we shuffle it..