c++ - 从 std::cin 读取密码

标签 c++ stl password-protection

我需要从标准输入读取密码并且希望 std::cin 不回显用户键入的字符...

如何禁用 std::cin 的回显?

这是我目前正在使用的代码:

string passwd;
cout << "Enter the password: ";
getline( cin, passwd );

我正在寻找一种与操作系统无关的方法来执行此操作。 Here在 Windows 和 *nix 中都有办法做到这一点。

最佳答案

@wrang-wrang 的回答非常好,但没有满足我的需求,这就是我的最终代码(基于 this)的样子:

#ifdef WIN32
#include <windows.h>
#else
#include <termios.h>
#include <unistd.h>
#endif

void SetStdinEcho(bool enable = true)
{
#ifdef WIN32
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
    DWORD mode;
    GetConsoleMode(hStdin, &mode);

    if( !enable )
        mode &= ~ENABLE_ECHO_INPUT;
    else
        mode |= ENABLE_ECHO_INPUT;

    SetConsoleMode(hStdin, mode );

#else
    struct termios tty;
    tcgetattr(STDIN_FILENO, &tty);
    if( !enable )
        tty.c_lflag &= ~ECHO;
    else
        tty.c_lflag |= ECHO;

    (void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);
#endif
}

示例用法:

#include <iostream>
#include <string>

int main()
{
    SetStdinEcho(false);

    std::string password;
    std::cin >> password;

    SetStdinEcho(true);

    std::cout << password << std::endl;

    return 0;
}

关于c++ - 从 std::cin 读取密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1413445/

相关文章:

php - Yii2 用户名密码加密

php - PHP 中的 password_hash() 怎么样

security - Elasticsearch 从哪里获取 elasticsearch-keystore 密码?

c++ - 模板参数包的错误推导

c++ - 使用 std::vector.erase(begin(), end()) 或 std::vector.erase(begin(), begin()) 安全吗?

c++ - 将 vector<char> 转换为 const char* 和 string

c++ - 如果列表为空,QList::first() 会返回什么?

c++ - 重新分配 std::vector 对象时指向内部数据结构的指针的有效性

c++ - Windows Phone 8 上的模糊太慢

c++ - VC++ 以编程方式排除特定代码行