#๐Ÿ”’ Is there a more elegant way to do this?

47 messages ยท Page 1 of 1 (latest)

tropic badger
#

I tried to do an assignment of making a strong password validator using regex. But I feel like I'm not doing it right. Could anyone just have a look at it and give me pointers?

https://paste.pythondiscord.com/3QOA

muted salmonBOT
#

@tropic badger

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

tropic badger
#

I was suggested to use dictionaries but I don't understand how to use them here even though I learned about it.

latent carbon
#

Your current implementation is fine, idk how you would use dictionary in this, but maybe a list or tuple would work (or even a set)? For storing a sequence of regex patterns and looping over them while applying, instead of creating a new variable for every pattern

#

And your this chain of conditional statements-

if mat0 != None:
    if mat1 != None:
        if mat2 != None:
            if mat3 != None:
                print(f'{passwd} is a valid password')
            else:
                print("invalid Password")
        else:
            print("invalid Password")
    else:
        print("invalid Password")
else:

    print("invalid password")

Can be written as-

if mat0 is None or mat1 is None or mat2 is None or mat3 is None:
    print("Invalid password")

else:
    print(f'{passwd} is a valid password')
tropic badger
tropic badger
#

Wait let me check

latent carbon
tropic badger
#

Oh my bad.. thanks!

#

Should I have made some kind of exception handling or... packaged it into a function?

#

Or is this fine for an assignment?

latent carbon
tropic badger
#

uhh.. I don't know.. I am back trying to learn programming after like 2 months and I'm just nervous about if I'm doing it right ๐Ÿ˜…

latent carbon
#

Lol its fine

#

Other than the conditional statements, its good

tropic badger
#

Ok ok. Thanks!

latent carbon
# tropic badger Ok ok. Thanks!

If you want to make it slightly better, you can use the all function to do so-

if all((mat0, mat1, mat2, mat3)):
    print(f'{passwd} is a valid password')

else:
    print("Invalid password")
#

The function takes in an iterable and checks if every element is truthy, if it is then it returns true

#

truthy elements are those which are non-zero, non-empty data, not False nor None

nova oak
#

i generaly use try/catch for stuff that is "secure"

vast plover
#

hmm perhaps "better" would be expandable, or even submitting the match types.

def validate_password(passwd, matches):
    psw_valid = [k for k, v in matches.items() if v is None]

    if psw_valid:
        print(f"Invalid password {missing=}")
    else:
        print(f"{passwd} is a valid password")
nova oak
#
def validate_password(password: str):
    # NEGATIVE / INVERSE CHECKING
    if len(password) < 12:
        raise ValueError("Password too short (must be โ‰ฅ 12 characters)")
    if password.islower() or password.isupper():
        raise ValueError("Password must contain both upper and lower case characters")
    if password.isalnum():
        raise ValueError("Password must include at least one symbol")
    if " " in password:
        raise ValueError("Password must not contain spaces")```

using negative/inverse pattern matching
#

when checking for passwords/security events you should check for what the condition isnot, not for what it is (generaly)

#

then you use a block like this for the actual input ```python
def hash_password(password: str) -> str:
return hashlib.sha256(password.encode()).hexdigest()

password = input("Enter password: ")

try:
validate_password(password)
except Exception as e:
print(f"Password rejected: {e}")
else:
hashed = hash_password(password)
print(f"Password accepted. Hash: {hashed}")```

#

so you run the password input against the validation funtion that does negative matching

latent carbon
#

I usually try to follow the principle of "Ask for permission instead of forgiveness", meaning trying to ask for permission via if statements and giving them priority whenever, over asking for forgiveness via exception handling

nova oak
#

yeah never do that with passwords

#

explict deny/negative pattern matching is the accepted standard for secure software engineering

#

postive matching allows for unintended matching and bypass of security

latent carbon
#

you can still get explicit positive/negative pattern matching with if statements too

#

its just a design choice

#

but whatever suits you

nova oak
#

not really, CIS, MS SDL, NIST all enforce negative matching with defult deny

#

its not so much a "whatever suits you" case, its a case where there are accepted design preincpiles from the security side of our profession

latent carbon
#

I see

potent trench
tropic badger
#

What?

#

This is supposed to be an assignment

#

But thanks for the suggestion

potent trench
#

Oh I see

#

You're right you said assignment

#

My bad

muted salmonBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.