CRM 및 데이터 플랫폼이메일 마케팅 및 자동화

JavaScript 또는 jQuery와 정규 표현식을 사용하여 비밀번호 강도 확인(서버측 예제도 포함!)

저는 다음을 사용하는 암호 강도 검사기의 좋은 예를 찾기 위해 조사를하고있었습니다. 자바 스크립트정규 표현식 (정규식). 내 직장의 애플리케이션에서 비밀번호 강도를 확인하기 위해 포스트백을 수행하는데 이는 사용자에게 매우 불편합니다.

Regex 란 무엇입니까?

정규식은 검색 패턴을 정의하는 일련의 문자입니다. 일반적으로 이러한 패턴은 문자열 검색 알고리즘에서 발견 or 찾아 교체 문자열에 대한 작업 또는 입력 유효성 검사. 

이 기사는 정규 표현식을 가르치는 것이 아닙니다. 정규식을 사용하는 기능은 텍스트에서 패턴을 검색 할 때 개발을 절대적으로 단순화합니다. 또한 대부분의 개발 언어는 정규 표현식 사용을 최적화했습니다. 따라서 문자열을 단계별로 구문 분석하고 검색하는 대신 Regex는 일반적으로 서버와 클라이언트 측에서 훨씬 더 빠릅니다.

나는 내가 찾기 전에 꽤 많이 웹을 검색했습니다. 예를 들어 길이, 문자 및 기호의 조합을 찾는 몇 가지 훌륭한 정규식입니다. 그러나 코드는 내 취향에 약간 과하고 .NET에 맞게 조정되었습니다. 그래서 코드를 단순화해서 자바스크립트로 넣었습니다. 이를 통해 다시 게시하기 전에 클라이언트의 브라우저에서 실시간으로 암호 강도를 확인하고 사용자에게 암호 강도에 대한 피드백을 제공합니다.

비밀번호를 입력하세요

키보드를 누를 때마다 암호가 정규식에 대해 테스트되고 그 아래의 범위에서 사용자에게 피드백이 제공됩니다.

JavaScript 비밀번호 강도 기능

최대 XNUMXW 출력을 제공하는 정규 표현식 코드 길이를 최소화하는 환상적인 작업을 수행합니다. 이 JavaScript 기능은 비밀번호의 강도를 확인하고 비밀번호를 해독하는 것이 추측하기 쉬운지, 중간인지, 어려운지, 아니면 극도로 어려운지를 확인합니다. 사람이 입력하면 더 강해지도록 격려하는 팁이 표시됩니다. 다음을 기준으로 비밀번호의 유효성을 검사합니다.

  • 길이 – 길이가 8자 미만 또는 초과인 경우.
  • 혼합 케이스 – 비밀번호에 대문자와 소문자가 모두 있는 경우.
  • 넘버들 – 비밀번호에 숫자가 포함된 경우.
  • 특수 문자 – 비밀번호에 특수문자가 포함된 경우.

이 기능은 암호를 더욱 강화하기 위한 몇 가지 팁과 함께 난이도를 표시합니다.

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;
  }
}

팁의 색상을 업데이트하려면 다음 코드를 업데이트하면 됩니다. // Return results 줄입니다.

// 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";
  }

jQuery를 암호 강도 기능

jQuery를 사용하면 실제로 oninput 업데이트로 양식을 작성할 필요가 없습니다.

<form>
    <label for="password">Enter password:</label>
    <input type="password" id="password">
    <p id="password-strength"></p>
</form>

원하는 경우 메시지 색상을 수정할 수도 있습니다. 

$(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');
        }
    });
});

비밀번호 요청 강화

JavaScript 내에서 비밀번호 구성의 유효성을 검사하는 것만으로는 충분하지 않습니다. 이를 통해 브라우저 개발 도구를 사용하는 사람은 누구나 스크립트를 우회하고 원하는 비밀번호를 사용할 수 있습니다. 플랫폼에 암호를 저장하기 전에 항상 서버 측 검사를 활용하여 암호 강도를 검증해야 합니다.

비밀번호 강도를 위한 PHP 함수

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";
  }
}

암호 강도를 위한 Python 함수

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"

비밀번호 강도를 위한 C# 함수

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";
  }
}

암호 강도를 위한 Java 기능

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";
  }
}

훌륭한 암호 생성기를 찾고 있다면 이를 위한 멋진 작은 온라인 도구를 만들었습니다.

비밀번호 생성기

Douglas Karr

Douglas Karr 의 CMO입니다. 오픈인사이트 그리고 설립자 Martech Zone. Douglas는 수십 개의 성공적인 MarTech 스타트업을 도왔고, Martech 인수 및 투자에서 5억 달러가 넘는 실사를 도왔으며, 기업이 판매 및 마케팅 전략을 구현하고 자동화하도록 지속적으로 지원하고 있습니다. Douglas는 국제적으로 인정받는 디지털 혁신이자 MarTech 전문가이자 연설가입니다. Douglas는 Dummie's Guide와 비즈니스 리더십 서적을 집필한 작가이기도 합니다.

관련 기사

맨 위로 가기 버튼
닫기

애드블록 감지됨

Martech Zone 은(는) 광고 수익, 제휴 링크 및 후원을 통해 사이트에서 수익을 창출하기 때문에 이 콘텐츠를 무료로 제공할 수 있습니다. 사이트를 볼 때 광고 차단기를 제거해 주시면 감사하겠습니다.