密码安全性检测软件(cpp)

· · 算法·理论

本蒟蒻写的第一个长代码,勿喷
(本人6年级)
确实是我自己写的,只是请AI重构了
(AI重构确实清爽)

  • 检测大小写、数字、符号
  • 检测重复字符、字母连续、键盘连续
  • 检测常见弱密码、年份、生日格式、疑似名字拼音
  • 输出扣分原因和安全等级

等等,可以吱一声或者点个赞再拿吗
谢谢惹~

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <thread>
#include <chrono>

#ifdef _WIN32
#include <conio.h>
#else
#include <termios.h>
#include <unistd.h>
#endif

using namespace std;

// ==================== 全局常量模块 ====================

const string KEYBOARD_ROWS[3] = {
    "qwertyuiop",
    "asdfghjkl",
    "zxcvbnm"
};

const int BASE_SCORE = 100;

// ==================== 工具函数模块 ====================

bool isDigitChar(char ch) {
    return ch >= '0' && ch <= '9';
}

bool isLowerChar(char ch) {
    return ch >= 'a' && ch <= 'z';
}

bool isUpperChar(char ch) {
    return ch >= 'A' && ch <= 'Z';
}

bool isLetterChar(char ch) {
    return isLowerChar(ch) || isUpperChar(ch);
}

bool isVowel(char ch) {
    if (isUpperChar(ch)) {
        ch = ch - 'A' + 'a';
    }
    return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

string toLowerStr(string s) {
    for (int i = 0; i < (int)s.size(); i++) {
        if (isUpperChar(s[i])) {
            s[i] = s[i] - 'A' + 'a';
        }
    }
    return s;
}

string getOnlyNumbers(string s) {
    string result = "";

    for (int i = 0; i < (int)s.size(); i++) {
        if (isDigitChar(s[i])) {
            result += s[i];
        }
    }

    return result;
}

int strToInt(string s) {
    int result = 0;

    for (int i = 0; i < (int)s.size(); i++) {
        if (!isDigitChar(s[i])) {
            return -1;
        }
        result = result * 10 + (s[i] - '0');
    }

    return result;
}

// ==================== 输入模块 ====================

string inputPasswordVisible() {
    string password;
    cout << "请输入你的密码:";
    getline(cin, password);
    return password;
}

string inputPasswordHidden() {
    string password = "";

#ifdef _WIN32
    char ch;

    while (true) {
        ch = _getch();

        if (ch == 13) { // 回车
            cout << endl;
            break;
        } else if (ch == 8) { // 退格
            if (!password.empty()) {
                password.erase(password.size() - 1, 1);
                cout << "\b \b";
            }
        } else {
            password += ch;
            cout << '*';
        }
    }
#else
    termios oldt, newt;
    tcgetattr(STDIN_FILENO, &oldt);

    newt = oldt;
    newt.c_lflag &= ~(ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    char ch;

    while (cin.get(ch)) {
        if (ch == '\n') {
            cout << endl;
            break;
        } else if (ch == 127 || ch == 8) {
            if (!password.empty()) {
                password.erase(password.size() - 1, 1);
                cout << "\b \b";
            }
        } else {
            password += ch;
            cout << '*';
        }
    }

    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
#endif

    return password;
}

string inputPassword() {
    char choice;

    cout << "是否显示密码?" << endl;
    cout << "y:显示" << endl;
    cout << "n:隐藏" << endl;
    cout << "请输入选择:";

    cin >> choice;
    cin.ignore(10000, '\n');

    if (choice == 'n' || choice == 'N') {
        cout << "请输入你的密码:";
        return inputPasswordHidden();
    }

    return inputPasswordVisible();
}

// ==================== 字符统计模块 ====================

struct CharCount {
    int lower;
    int upper;
    int digit;
    int symbol;
};

CharCount countChars(string password) {
    CharCount cnt;
    cnt.lower = 0;
    cnt.upper = 0;
    cnt.digit = 0;
    cnt.symbol = 0;

    for (int i = 0; i < (int)password.size(); i++) {
        if (isLowerChar(password[i])) {
            cnt.lower++;
        } else if (isUpperChar(password[i])) {
            cnt.upper++;
        } else if (isDigitChar(password[i])) {
            cnt.digit++;
        } else {
            cnt.symbol++;
        }
    }

    return cnt;
}

int countDifferentChars(string password) {
    if (password.empty()) {
        return 0;
    }

    sort(password.begin(), password.end());

    int different = 1;
    for (int i = 1; i < (int)password.size(); i++) {
        if (password[i] != password[i - 1]) {
            different++;
        }
    }

    return different;
}

// ==================== 键盘位置模块 ====================

void getKeyboardPosition(char ch, int &row, int &col) {
    if (isUpperChar(ch)) {
        ch = ch - 'A' + 'a';
    }

    row = -1;
    col = -1;

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < (int)KEYBOARD_ROWS[i].size(); j++) {
            if (KEYBOARD_ROWS[i][j] == ch) {
                row = i;
                col = j;
                return;
            }
        }
    }
}

// ==================== 日期检测模块 ====================

bool isValidDate(int year, int month, int day) {
    if (year < 1900 || year > 2099) {
        return false;
    }
    if (month < 1 || month > 12) {
        return false;
    }

    int monthDays[13] = {
        0, 31, 28, 31, 30, 31, 30,
        31, 31, 30, 31, 30, 31
    };

    bool leapYear = false;
    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
        leapYear = true;
    }

    if (leapYear) {
        monthDays[2] = 29;
    }

    return day >= 1 && day <= monthDays[month];
}

bool hasYear(string password) {
    for (int i = 0; i + 3 < (int)password.size(); i++) {
        string part = password.substr(i, 4);

        if (part[0] == '1' && part[1] == '9' &&
            isDigitChar(part[2]) && isDigitChar(part[3])) {
            return true;
        }

        if (part[0] == '2' && part[1] == '0' &&
            isDigitChar(part[2]) && isDigitChar(part[3])) {
            return true;
        }
    }

    return false;
}

bool hasBirthday(string password) {
    string nums = getOnlyNumbers(password);

    // 8 位生日:yyyymmdd,例如 20091231
    for (int i = 0; i + 7 < (int)nums.size(); i++) {
        int year = strToInt(nums.substr(i, 4));
        int month = strToInt(nums.substr(i + 4, 2));
        int day = strToInt(nums.substr(i + 6, 2));

        if (isValidDate(year, month, day)) {
            return true;
        }
    }

    // 6 位生日:yymmdd,例如 091231
    for (int i = 0; i + 5 < (int)nums.size(); i++) {
        int yy = strToInt(nums.substr(i, 2));
        int month = strToInt(nums.substr(i + 2, 2));
        int day = strToInt(nums.substr(i + 4, 2));

        int year;
        if (yy <= 26) {
            year = 2000 + yy;
        } else {
            year = 1900 + yy;
        }

        if (isValidDate(year, month, day)) {
            return true;
        }
    }

    // 4 位月日:mmdd,例如 1231、0101
    for (int i = 0; i + 3 < (int)nums.size(); i++) {
        int month = strToInt(nums.substr(i, 2));
        int day = strToInt(nums.substr(i + 2, 2));

        if (month >= 1 && month <= 12 && day >= 1 && day <= 31) {
            return true;
        }
    }

    return false;
}

// ==================== 密码弱点检测模块 ====================

bool hasRepeatedChars(string password) {
    for (int i = 0; i + 2 < (int)password.size(); i++) {
        if (password[i] == password[i + 1] && password[i + 1] == password[i + 2]) {
            return true;
        }
    }
    return false;
}

int countRepeatedGroups(string password) {
    int groups = 0;

    for (int i = 0; i + 2 < (int)password.size(); i++) {
        if (password[i] == password[i + 1] && password[i + 1] == password[i + 2]) {
            groups++;
        }
    }

    return groups;
}

bool hasAlphabetSequence(string password) {
    string lower = toLowerStr(password);

    for (int i = 0; i + 2 < (int)lower.size(); i++) {
        char a = lower[i];
        char b = lower[i + 1];
        char c = lower[i + 2];

        if (!isLowerChar(a) || !isLowerChar(b) || !isLowerChar(c)) {
            continue;
        }

        bool forward = (a + 1 == b && b + 1 == c);
        bool backward = (a - 1 == b && b - 1 == c);

        if (forward || backward) {
            return true;
        }
    }

    return false;
}

bool hasKeyboardSequence(string password) {
    for (int i = 0; i + 2 < (int)password.size(); i++) {
        int r1, c1, r2, c2, r3, c3;

        getKeyboardPosition(password[i], r1, c1);
        getKeyboardPosition(password[i + 1], r2, c2);
        getKeyboardPosition(password[i + 2], r3, c3);

        if (r1 == -1 || r2 == -1 || r3 == -1) {
            continue;
        }

        bool sameRow = (r1 == r2 && r2 == r3);
        bool forward = (c1 + 1 == c2 && c2 + 1 == c3);
        bool backward = (c1 - 1 == c2 && c2 - 1 == c3);

        if (sameRow && (forward || backward)) {
            return true;
        }
    }

    return false;
}

bool hasCommonPassword(string password) {
    password = toLowerStr(password);

    vector<string> badPasswords;
    badPasswords.push_back("123456");
    badPasswords.push_back("12345678");
    badPasswords.push_back("123456789");
    badPasswords.push_back("111111");
    badPasswords.push_back("000000");
    badPasswords.push_back("password");
    badPasswords.push_back("qwerty");
    badPasswords.push_back("admin");
    badPasswords.push_back("abc123");
    badPasswords.push_back("a123456");
    badPasswords.push_back("iloveyou");
    badPasswords.push_back("letmein");
    badPasswords.push_back("welcome");
    badPasswords.push_back("dragon");
    badPasswords.push_back("monkey");
    badPasswords.push_back("112233");
    badPasswords.push_back("123123");
    badPasswords.push_back("332211");
    badPasswords.push_back("114514");
    badPasswords.push_back("7891");

    for (int i = 0; i < (int)badPasswords.size(); i++) {
        if (password.find(badPasswords[i]) != string::npos) {
            return true;
        }
    }

    return false;
}

bool hasNameLikePinyin(string password) {
    string part = "";

    for (int i = 0; i <= (int)password.size(); i++) {
        if (i < (int)password.size() && isLetterChar(password[i])) {
            part += password[i];
            continue;
        }

        if ((int)part.size() >= 4) {
            bool hasVowelLetter = false;
            bool hasConsonantLetter = false;

            for (int j = 0; j < (int)part.size(); j++) {
                if (isVowel(part[j])) {
                    hasVowelLetter = true;
                } else {
                    hasConsonantLetter = true;
                }
            }

            if (hasVowelLetter && hasConsonantLetter) {
                return true;
            }
        }

        part = "";
    }

    return false;
}

// ==================== 评分结果模块 ====================

struct CheckResult {
    int score;
    vector<string> warnings;
};

void addWarning(CheckResult &result, string warning, int minusScore) {
    result.warnings.push_back(warning);
    result.score -= minusScore;
}

CheckResult checkPassword(string password) {
    CheckResult result;
    result.score = BASE_SCORE;

    CharCount cnt = countChars(password);

    // 规则 1:字符类型是否齐全
    if (cnt.lower == 0) {
        addWarning(result, "-你的密码没有小写字母", 40);
    }
    if (cnt.upper == 0) {
        addWarning(result, "-你的密码没有大写字母", 40);
    }
    if (cnt.digit == 0) {
        addWarning(result, "-你的密码没有数字", 40);
    }
    if (cnt.symbol == 0) {
        addWarning(result, "-你的密码没有符号", 40);
    }

    // 规则 2:连续重复字符
    int repeatGroups = countRepeatedGroups(password);
    if (repeatGroups == 1) {
        addWarning(result, "-你的密码有连续重复字符", 50);
    } else if (repeatGroups >= 2) {
        addWarning(result, "-你的密码有大量连续重复字符", 100);
    }

    // 规则 3:字母表连续
    if (hasAlphabetSequence(password)) {
        addWarning(result, "-你的密码有字母表中的连续字符", 40);
    }

    // 规则 4:键盘连续
    if (hasKeyboardSequence(password)) {
        addWarning(result, "-你的密码有键盘上的连续字符", 40);
    }

    // 规则 5:不同字符太少
    if ((int)password.size() >= 4 && countDifferentChars(password) <= 3) {
        addWarning(result, "-你的密码不同字符太少", 60);
    }

    // 规则 6:常见弱密码
    if (hasCommonPassword(password)) {
        addWarning(result, "-你的密码含有常见弱密码", 80);
    }

    // 规则 7:年份
    if (hasYear(password)) {
        addWarning(result, "-你的密码含有年份", 50);
    }

    // 规则 8:生日格式
    if (hasBirthday(password)) {
        addWarning(result, "-你的密码含有生日格式", 70);
    }

    // 规则 9:疑似名字拼音
    if (hasNameLikePinyin(password)) {
        addWarning(result, "-你的密码含有疑似名字拼音", 60);
    }

    // 规则 10:密码太短
    if ((int)password.size() <= 5) {
        addWarning(result, "-你的密码太短了", 50);
    }

    // 规则 11:长度加分或扣分
    result.score += ((int)password.size() - 8) * 10;

    return result;
}

// ==================== 输出模块 ====================

string getLevel(int finalScore) {
    if (finalScore < -200) {
        return "非常低";
    }
    if (finalScore < 0) {
        return "低";
    }
    if (finalScore < 200) {
        return "中";
    }
    if (finalScore < 400) {
        return "高";
    }
    return "非常高";
}

void printResult(string password, CheckResult result) {
    cout << "正在检测密码安全度..." << endl;
    this_thread::sleep_for(chrono::milliseconds(1000));

    for (int i = 0; i < (int)result.warnings.size(); i++) {
        cout << result.warnings[i] << endl;
    }

    int finalScore = result.score * 3;

    cout << endl;
    cout << "你的密码安全度:" << finalScore;
    cout << "(" << getLevel(finalScore) << ")" << endl;

    if ((int)password.size() >= 15) {
        cout << "你真的记得住你的密码吗" << endl;
    }
}

// ==================== 主程序模块 ====================

int main() {
    string password = inputPassword();

    CheckResult result = checkPassword(password);

    printResult(password, result);

    return 0;
}