#๐ Is there a more elegant way to do this?
47 messages ยท Page 1 of 1 (latest)
@tropic badger
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.
I was suggested to use dictionaries but I don't understand how to use them here even though I learned about it.
Im not sure what you're trying to do here:
#for loop to create a dictionary of matches
for i in range(0,3):
matchlst[i] = 'mat' + {i}
but it throws an error as you cannot join string and sets
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')
I was trying to automate the matches instead of manually typing each line(it felt like I was not programming the right way)
I think this will give some error saying the object can't be None?
Wait let me check
No, I just made your chain of if statements easier to read in a single line
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?
Where will you add error handling though?
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 ๐
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
i generaly use try/catch for stuff that is "secure"
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")
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
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
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
you can still get explicit positive/negative pattern matching with if statements too
its just a design choice
but whatever suits you
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
if you want the bible https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
Website with the collection of all the cheat sheets of the project.
I see
You might like to try zxcvbn
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.