C++ 密碼強度檢查程式
給定一個包含密碼字元的字串輸入,任務是檢查密碼的強度。
密碼強度是指判斷密碼是否容易被猜測或破解。強度應從弱、中等和強三個級別區分。為了檢查強度,我們必須檢查以下幾點:
- 密碼必須至少 8 個字元長。
- 必須包含 1 個小寫字母。
- 必須包含 1 個大寫字母
- 必須包含一個數字
- 必須包含一個特殊字元,例如:!@#$%^&*()><,.+=-
例如,密碼“tutorialspoint”很容易被猜測,因此我們可以說給定的密碼是“弱”的,因為它只包含小寫字元,而密碼“Tutorialspoint@863!”是強的,因為它同時包含大小寫字母、數字和特殊字元,並且長度超過 8 個字元,因此滿足了使密碼更強大的所有條件。
如果某個密碼滿足了強密碼特徵的一半以上,那麼我們將該密碼視為中等強度。例如,密碼“tutorialspoint12”將被視為中等強度,因為它包含小寫字母、數字,並且長度大於 8 個字元。
示例
Input: tutoriAlspOint!@12 Output: Strength of password:-Strong Explanation: Password has 1 lowercase, 1 uppercase, 1 special character, more than 8 characters long and a digit, hence the password is strong. Input: tutorialspoint Output: Strength of password:-Weak
**我們將使用的方法來解決給定的問題**:
- 獲取密碼的字串輸入。
- 檢查密碼是否滿足所有影響密碼強度的因素。
- 根據這些因素列印密碼的強度。
演算法
Start Step 1 ⇒ In function void printStrongNess(string& input) Declare and initialize n = input.length() Declare bool hasLower = false, hasUpper = false Declare bool hasDigit = false, specialChar = false Declare string normalChars = "abcdefghijklmnopqrstu" "vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 " Loop For i = 0 and i < n and i++ If (islower(input[i])) Set hasLower = true If (isupper(input[i])) Set hasUpper = true If (isdigit(input[i])) Set hasDigit = true Set size_t special = input.find_first_not_of(normalChars) If (special != string::npos) Set specialChar = true End Loop Print "Strength of password:-" If (hasLower && hasUpper && hasDigit && specialChar && (n >= 8)) Print "Strong" else if ((hasLower || hasUpper) && specialChar && (n >= 6)) Print "Moderate" else print "Weak" Step 2 ⇒ In function int main() Declare and initialize input = "tutorialspoint!@12" printStrongNess(input) Stop
示例
#include <iostream>
using namespace std;
void printStrongNess(string& input) {
int n = input.length();
// Checking lower alphabet in string
bool hasLower = false, hasUpper = false;
bool hasDigit = false, specialChar = false;
string normalChars = "abcdefghijklmnopqrstu" "vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ";
for (int i = 0; i < n; i++) {
if (islower(input[i]))
hasLower = true;
if (isupper(input[i]))
hasUpper = true;
if (isdigit(input[i]))
hasDigit = true;
size_t special = input.find_first_not_of(normalChars);
if (special != string::npos)
specialChar = true;
}
// Strength of password
cout << "Strength of password:-";
if (hasLower && hasUpper && hasDigit &&
specialChar && (n >= 8))
cout << "Strong" << endl;
else if ((hasLower || hasUpper) &&
specialChar && (n >= 6))
cout << "Moderate" << endl;
else
cout << "Weak" << endl;
}
int main() {
string input = "tutorialspoint!@12";
printStrongNess(input);
return 0;
}輸出
Strength of password:-Moderate
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP