【问题标题】:username and password check用户名和密码检查
【发布时间】:2017-11-29 22:37:24
【问题描述】:

我正在编写一个程序(主要用于教育目的,但如果我喜欢它,我以后可能会在更大的项目中使用它)用于用户名+密码身份验证。到目前为止我所拥有的“有效”,这意味着没有错误,但它的行为确实有点奇怪。它在退出之前执行了 STUFF() 大约 9 次(我没有保存确切的输出),而它只打算执行一次。

我怎样才能让它做 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();
   };

}

【问题讨论】:

  • 无法复制:ideone.com/EPnGn4
  • 另外,您的 RETRY 代码不会像您预期的那样运行。它不会循环,所以即使你输入“Y”程序也会退出。
  • 我再次测试(重点是获取用户并通过错误重试)。选择 no exited 并选择 yes 然后让它们正确退出而不做任何事情。编辑:再次复制该结果两次,然后第一次让用户/通过正确,并打印“身份验证失败!再试一次?”正好 9 次

标签: c++ authentication


【解决方案1】:

我已经放弃了最后一个程序并从头开始编写。 对于任何想要使用它的 C++ 新手,它在 GNU GPLv2 下获得许可,可以在 Github 上的 Small-Projects-Cpp 中找到。只需下载“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;
   }

MENU() 有一个 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 2013-02-06
    • 2016-09-24
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多