I’m a bit new to Elixir, and I’m trying to conditionally increment a value. This is used as part of determining the complexity of a given password. If a given password contains any digits, I want to increase the keyspace
by 10
. If the the given password also contains a lowercase letter, I want to increase the keyspace
by 26
.
Here is a psuedo-code version I have that is mostly Elixir syntax, but typical imperative style:
def determine_password_complexity(proposed_password) do
keyspace = 0
if Regex.match?(~r/[A-Z]/, proposed_password) do
# The password contains at least one common capital letter.
keyspace = keyspace + 26 # There are 26 common capital letters.
end
if Regex.match?(~r/[a-z]/, proposed_password) do
# The password contains at least one common lowercase letter.
keyspace = keyspace + 26 # There are 26 common lowercase letters.
end
if Regex.match?(~r/[0-9]/, proposed_password) do
# The password contains at least one digit.
keyspace = keyspace + 10 # There are 10 common digits.
end
if Regex.match?(~r/[^A-Za-z0-9]+/, proposed_password) do
# The password contains at least one special character.
keyspace = keyspace + 32 # There are 32 common special characters (inluding one whitespace character).
end
password_length = String.length(proposed_password)
:math.pow(keyspace, password_length)
end
The first error I run into informs me that keyspace
won’t leak out of the conditional, so I re-wrote it as suggested, like this:
defp determine_password_complexity(proposed_password) do
keyspace = 0
keyspace =
if Regex.match?(~r/[A-Z]/, proposed_password) do
# The password contains at least one common capital letter.
keyspace + 26 # There are 26 common capital letters.
end
keyspace =
if Regex.match?(~r/[a-z]/, proposed_password) do
# The password contains at least one common lowercase letter.
keyspace + 26 # There are 26 common lowercase letters.
end
keyspace =
if Regex.match?(~r/[0-9]/, proposed_password) do
# The password contains at least one digit.
keyspace + 10 # There are 10 common digits.
end
keyspace =
if Regex.match?(~r/[^A-Za-z0-9]+/, proposed_password) do
# The password contains at least one special character.
keyspace + 32 # There are 32 common special characters (inluding one whitespace character).
end
password_length = String.length(proposed_password)
:math.pow(keyspace, password_length)
end
When invoked, the code above produces the error bad argument in arithmetic expression
which happens on any of the lines that look like keyspace + 26
. I assume it’s because I’m trying to use the keyspace
variable out of scope? I’m a bit lost on this one…