C++ 用户名和密码检查

C++ 用户名和密码检查,c++,authentication,C++,Authentication,我写的程序主要是为了教育目的,但如果我喜欢它,我可能会在以后的一个更大的项目中使用它进行用户名+密码身份验证。到目前为止,我所做的工作是有效的,这意味着没有错误,但它的行为确实有点怪异。它做了9次,我在退出之前没有保存确切的输出,因为它只打算做一次 我怎样才能让它只做一次?如何使密码输入不可见?我怎样才能提高安全性/语法或者缩短它 #include <iostream> using namespace std; void STUFF() { cout << "Do

我写的程序主要是为了教育目的,但如果我喜欢它,我可能会在以后的一个更大的项目中使用它进行用户名+密码身份验证。到目前为止,我所做的工作是有效的,这意味着没有错误,但它的行为确实有点怪异。它做了9次,我在退出之前没有保存确切的输出,因为它只打算做一次

我怎样才能让它只做一次?如何使密码输入不可见?我怎样才能提高安全性/语法或者缩短它

#include <iostream>
using namespace std;

void STUFF()
{
   cout << "Doing stuff..." << endl;
}

int CREDS;
void AUTH()
{
   cout << "Username: "; string USER; cin >> USER;
   cout << "Password: "; string PASS; cin >> PASS;
   if (USER == "josh" and PASS == "passwd")
   {
      CREDS = 0;
   }
   else 
   {
      CREDS = 1;
   };
}

void RETRY()
{
   cout << "Authentication failed! Try again? [Y/n]" << endl; char REPLY; cin >> REPLY;
   if (REPLY == 'Y' or REPLY == 'y')
   {
      AUTH();
   }
   else if (REPLY == 'N' or REPLY == 'n')
   {
      cout << "Exiting..." << endl;
   }
   else
   {
      RETRY();
   };
}

int main()
{
   AUTH();
   if (CREDS == 0)
   {
      STUFF();
      return 0;
   }
   else if (CREDS == 1)
   {
      RETRY();
   };

}

我放弃了最后一个程序,从头开始写了这个。 对于任何新的C++用户,都希望使用这个,它是在GNU GPLV2下授权的,可以在Github上找到。只需下载Userpass.zip,因为不需要克隆整个存储库

#include <iostream>
#include <string>
#include <unistd.h>
#include <termios.h>
getpass使密码输入显示星号。不是完全看不见,但这可能是最好的解决方案

using namespace std;
string PASSWD;
string getPASS()
{
    termios oldt;
    tcgetattr(STDIN_FILENO, &oldt);
    termios newt = oldt;
    newt.c_lflag &= ~ECHO;
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    string PASS;
    cout << "Password: "; cin >> PASS; cout << endl;
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return PASS;
   }
菜单有一个switch/case菜单,但它是不相关的,所以我在asnwer中跳过它。你可以用你想要的任何功能来代替它

int attempts = 0;
int main()
{

   while (attempts == 3)
   {
      cout << "Too many attempts have been made! Exiting..." << endl; exit(0);
   };
   string USER;
   cout << "Username: "; cin >> USER;

   if (USER == "josh") 
       {   
           if (getPASS() == "hsoj")
       {
        cout << "\nAccess granted!\n" << endl;
        MENU();
       }
           else
       {
           cout << "\nAccess denied!\n" << endl; 
        attempts = attempts + 1;
        main();
       };
   }
   else
   {
      cout << "\nAccess denied!\n" << endl; 
      attempts = attempts + 1;
      main();
   };
   return 0;
}

无法复制:此外,您的重试代码不会像您预期的那样运行。它不会循环回来,所以即使你输入Y,程序也会退出。我再次测试了它,以获得用户并通过错误的重试。选择“否”退出,选择“是”,然后让他们正确无误地退出。编辑:再次复制该结果两次,然后第一次获得用户/通行证正确,打印验证失败!再试一次?正好9次