在保持getch()完整性的同时存储密码

时间:2010-12-21 06:41:16

标签: c++ windows console

一个简单的方法我可以存储用户输入的密码,同时仍然保持密码隐藏?

  char password[9];
   int i;
   printf("Enter your password: ");
   for (i=0;i<9;i++)
   {
   password[i] = getch();
   printf("*");
   }
   for (i=0;i<9;i++)
   printf("%c",password[i]);
   getch();
   }

我想存储密码,以便我可以做一个简单的if (password[i] == root_password),以便继续使用正确的密码。

3 个答案:

答案 0 :(得分:0)

您的问题似乎是您没有检查换行符'\ n'或文件结尾。

printf("Enter your password: ");
char password[9];
int i;
for (i = 0; i < sizeof password - 1; i++)
{
    int c = getch();
    if (c == '\n' || c == EOF)
        break;
    }
    password[i] = c;
    printf("*");
}
password[i] = '\0';

这样,密码最终会成为ASCIIZ字符串,适合使用putsprintf("%s", password)进行打印,或者 - 至关重要......

if (strcmp(password, root_password)) == 0)
    your_wish_is_my_command();

请注意,我们在密码中最多读取8个字符,因为我们需要为NUL终结符添加一个额外字符。如果你愿意,你可以增加它。

答案 1 :(得分:0)

您需要在Windows中使用控制台API。下面是一个禁用控制台窗口中的回显的代码段。函数SetConsoleMode()用于控制回显(以及其他内容)。我保存旧模式,以便在检索到密码后可以恢复控制台。

此外,*ConsoleMode()函数需要控制台输入缓冲区的句柄。 CreateFile()的MSDN文档中描述了如何获取这些缓冲区的句柄。

int main(int argc, char* argv[])
{
    char password[100] = { 0 };
    printf("Enter your password: ");

    HANDLE hConsole = ::CreateFile("CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

    DWORD dwOldMode;
    ::GetConsoleMode(hConsole, &dwOldMode);
    ::SetConsoleMode(hConsole, dwOldMode & ~ENABLE_ECHO_INPUT);

    bool bFinished = false;
    while(!bFinished) {
        if(!fgets(password, sizeof(password) / sizeof(password[0]) - 1, stdin)) {
            printf("\nEOF - exiting\n");
        } else
            bFinished = true;
    }

    ::SetConsoleMode(hConsole, dwOldMode | ENABLE_ECHO_INPUT);
    printf("\nPassword is: %s\n", password);

    return 0;
}

答案 2 :(得分:0)

因为我们在C ++和Windows中这样做:

#include <iostream>
#include <string>
#include <conio.h> //_getch
#include <Windows.h> //VK_RETURN = 0x0D

using namespace std;

string read_password()
{
    string pass;
    cout << "Enter your password: ";

    int character = 0;
    while(VK_RETURN != (character = _getch()) )
    {
        cout << '*';
        pass += static_cast<char>(character);
    }

    cout << std::endl;
    return pass;
}

int main ()
{
    string root_password = "anypass123";
    string pass = read_password();

    if (pass == root_password)
    {
        cout << "password accepted" << endl;
    }

    return 0;
}

编译&amp;测试