用户名和密码检查

时间:2017-06-27 00:45:04

标签: c++ authentication

我正在编写一个程序(主要是教育目的,但如果我喜欢它,那么我可能会在稍后的大项目中使用它)进行用户名+密码验证。到目前为止我所拥有的“有效”,意味着没有错误,但确实表现得有些奇怪。它在退出之前做了大约9次STUFF()(我没有保存确切的输出),只是意味着要做一次。

如何让它只做一次STUFF()?如何使密码输入不可见?我怎样才能一般地改善安全性/语法或缩短它?

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

}

1 个答案:

答案 0 :(得分:0)

我放弃了最后一个程序,并从头开始编写。 对于想要使用它的C ++新用户,它在GNU GPLv2下获得许可,可以在Github上的Small-Projects-Cpp中找到。只需下载&#34; Userpass.zip&#34;因为没有必要克隆整个存储库。

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

MENU()有一个开关/案例菜单,但它是无关的,所以我在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;
}