Sprawdź siłę hasła za pomocą JavaScript lub jQuery i wyrażeń regularnych (również z przykładami po stronie serwera!)
Poszukiwałem dobrego przykładu sprawdzania siły hasła, który używa JAVASCRIPT i Wyrażenia regularne (wyrażenie regularne). W aplikacji w mojej pracy robimy post zwrotny w celu weryfikacji siły hasła i jest to dość uciążliwe dla naszych użytkowników.
Co to jest Regex?
Wyrażenie regularne to sekwencja znaków definiujących wzorzec wyszukiwania. Zazwyczaj takie wzorce są używane przez algorytmy wyszukiwania ciągów znaków odnaleźć or Znajdź i zamień operacje na łańcuchach lub do sprawdzania poprawności danych wejściowych.
Ten artykuł zdecydowanie nie ma na celu nauczenia Cię wyrażeń regularnych. Po prostu wiedz, że możliwość korzystania z wyrażeń regularnych absolutnie uprości programowanie podczas wyszukiwania wzorców w tekście. Należy również zauważyć, że większość języków programistycznych ma zoptymalizowane użycie wyrażeń regularnych ... więc zamiast analizować i wyszukiwać ciągi krok po kroku, Regex jest zwykle znacznie szybszy zarówno po stronie serwera, jak i klienta.
Przeszukałem internet trochę, zanim znalazłem przykład kilku świetnych wyrażeń regularnych, które szukają kombinacji długości, znaków i symboli. Jednak kod był trochę przesadzony jak na mój gust i dostosowany do platformy .NET. Uprościłem więc kod i umieściłem go w JavaScript. Dzięki temu sprawdza siłę hasła w przeglądarce klienta w czasie rzeczywistym przed wysłaniem go z powrotem… i dostarcza użytkownikowi informacji zwrotnych na temat siły hasła.
Wpisz hasło
Przy każdym naciśnięciu klawisza hasło jest sprawdzane pod kątem wyrażenia regularnego, a następnie użytkownik otrzymuje informację zwrotną w zakresie poniżej.
Funkcja siły hasła JavaScript
Połączenia Wyrażenia regularne wykonaj fantastyczną robotę, minimalizując długość kodu. Ta funkcja JavaScript sprawdza siłę hasła i to, czy jego udaremnienie jest łatwe, średnie, trudne czy niezwykle trudne do odgadnięcia. Gdy osoba pisze, wyświetla wskazówki, jak zachęcić ją do bycia silniejszą. Weryfikuje hasło na podstawie:
- Długość – Jeśli długość jest mniejsza lub większa niż 8 znaków.
- Mieszany przypadek – Jeśli hasło zawiera zarówno wielkie, jak i małe litery.
- Liczby – Jeśli hasło zawiera cyfry.
- Znaki specjalne – Jeśli hasło zawiera znaki specjalne.
Funkcja wyświetla trudność, a także wskazówki dotyczące dalszego wzmacniania hasła.
function checkPasswordStrength(password) {
// Initialize variables
var strength = 0;
var tips = "";
// Check password length
if (password.length < 8) {
tips += "Make the password longer. ";
} else {
strength += 1;
}
// Check for mixed case
if (password.match(/[a-z]/) && password.match(/[A-Z]/)) {
strength += 1;
} else {
tips += "Use both lowercase and uppercase letters. ";
}
// Check for numbers
if (password.match(/\d/)) {
strength += 1;
} else {
tips += "Include at least one number. ";
}
// Check for special characters
if (password.match(/[^a-zA-Z\d]/)) {
strength += 1;
} else {
tips += "Include at least one special character. ";
}
// Return results
if (strength < 2) {
return "Easy to guess. " + tips;
} else if (strength === 2) {
return "Medium difficulty. " + tips;
} else if (strength === 3) {
return "Difficult. " + tips;
} else {
return "Extremely difficult. " + tips;
}
}
Jeśli chcesz zaktualizować kolor końcówki, możesz to również zrobić, aktualizując kod po // Return results
Linia.
// Get the paragraph element
var strengthElement = document.getElementById("passwordStrength");
// Return results
if (strength < 2) {
strengthElement.textContent = "Easy to guess. " + tips;
strengthElement.style.color = "red";
} else if (strength === 2) {
strengthElement.textContent = "Medium difficulty. " + tips;
strengthElement.style.color = "orange";
} else if (strength === 3) {
strengthElement.textContent = "Difficult. " + tips;
strengthElement.style.color = "black";
} else {
strengthElement.textContent = "Extremely difficult. " + tips;
strengthElement.style.color = "green";
}
Funkcja siły hasła jQuery
Dzięki jQuery nie musimy właściwie pisać formularza z aktualizacją oninput:
<form>
<label for="password">Enter password:</label>
<input type="password" id="password">
<p id="password-strength"></p>
</form>
Możemy również modyfikować kolor wiadomości, jeśli chcemy.
$(document).ready(function() {
$('#password').on('input', function() {
var password = $(this).val();
var strength = 0;
var tips = "";
// Check password length
if (password.length < 8) {
tips += "Make the password longer. ";
} else {
strength += 1;
}
// Check for mixed case
if (password.match(/[a-z]/) && password.match(/[A-Z]/)) {
strength += 1;
} else {
tips += "Use both lowercase and uppercase letters. ";
}
// Check for numbers
if (password.match(/\d/)) {
strength += 1;
} else {
tips += "Include at least one number. ";
}
// Check for special characters
if (password.match(/[^a-zA-Z\d]/)) {
strength += 1;
} else {
tips += "Include at least one special character. ";
}
// Update the text and color based on the password strength
var passwordStrengthElement = $('#password-strength');
if (strength < 2) {
passwordStrengthElement.text("Easy to guess. " + tips);
passwordStrengthElement.css('color', 'red');
} else if (strength === 2) {
passwordStrengthElement.text("Medium difficulty. " + tips);
passwordStrengthElement.css('color', 'orange');
} else if (strength === 3) {
passwordStrengthElement.text("Difficult. " + tips);
passwordStrengthElement.css('color', 'black');
} else {
passwordStrengthElement.text("Extremely difficult. " + tips);
passwordStrengthElement.css('color', 'green');
}
});
});
Wzmocnienie żądania hasła
Ważne jest, aby nie tylko sprawdzać poprawność konstrukcji hasła w kodzie JavaScript. Umożliwiłoby to każdemu, kto posiada narzędzia do programowania przeglądarki, ominięcie skryptu i użycie dowolnego hasła. ZAWSZE powinieneś sprawdzić siłę hasła przed zapisaniem go na swojej platformie po stronie serwera.
Funkcja PHP dla siły hasła
function checkPasswordStrength($password) {
// Initialize variables
$strength = 0;
// Check password length
if (strlen($password) < 8) {
return "Easy to guess";
} else {
$strength += 1;
}
// Check for mixed case
if (preg_match("/[a-z]/", $password) && preg_match("/[A-Z]/", $password)) {
$strength += 1;
}
// Check for numbers
if (preg_match("/\d/", $password)) {
$strength += 1;
}
// Check for special characters
if (preg_match("/[^a-zA-Z\d]/", $password)) {
$strength += 1;
}
// Return strength level
if ($strength < 2) {
return "Easy to guess";
} else if ($strength === 2) {
return "Medium difficulty";
} else if ($strength === 3) {
return "Difficult";
} else {
return "Extremely difficult";
}
}
Funkcja Pythona dla siły hasła
def check_password_strength(password):
# Initialize variables
strength = 0
# Check password length
if len(password) < 8:
return "Easy to guess"
else:
strength += 1
# Check for mixed case
if any(char.islower() for char in password) and any(char.isupper() for char in password):
strength += 1
# Check for numbers
if any(char.isdigit() for char in password):
strength += 1
# Check for special characters
if any(not char.isalnum() for char in password):
strength += 1
# Return strength level
if strength < 2:
return "Easy to guess"
elif strength == 2:
return "Medium difficulty"
elif strength == 3:
return "Difficult"
else:
return "Extremely difficult"
Funkcja C# dla siły hasła
public string CheckPasswordStrength(string password) {
// Initialize variables
int strength = 0;
// Check password length
if (password.Length < 8) {
return "Easy to guess";
} else {
strength += 1;
}
// Check for mixed case
if (password.Any(char.IsLower) && password.Any(char.IsUpper)) {
strength += 1;
}
// Check for numbers
if (password.Any(char.IsDigit)) {
strength += 1;
}
// Check for special characters
if (password.Any(ch => !char.IsLetterOrDigit(ch))) {
strength += 1;
}
// Return strength level
if (strength < 2) {
return "Easy to guess";
} else if (strength == 2) {
return "Medium difficulty";
} else if (strength == 3) {
return "Difficult";
} else {
return "Extremely difficult";
}
}
Funkcja Java dla siły hasła
public String checkPasswordStrength(String password) {
// Initialize variables
int strength = 0;
// Check password length
if (password.length() < 8) {
return "Easy to guess";
} else {
strength += 1;
}
// Check for mixed case
if (password.matches(".*[a-z].*") && password.matches(".*[A-Z].*")) {
strength += 1;
}
// Check for numbers
if (password.matches(".*\\d.*")) {
strength += 1;
}
// Check for special characters
if (password.matches(".*[^a-zA-Z\\d].*")) {
strength += 1;
}
// Return strength level
if (strength < 2) {
return "Easy to guess";
} else if (strength == 2) {
return "Medium difficulty";
} else if (strength == 3) {
return "Difficult";
} else {
return "Extremely difficult";
}
}
A jeśli szukasz tylko świetnego generatora haseł, stworzyłem do tego ładne, małe narzędzie online.