Home >Backend Development >C++ >How Can I Securely Read Passwords Using std::cin Without Echoing to the Console?

How Can I Securely Read Passwords Using std::cin Without Echoing to the Console?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 22:34:10914browse

How Can I Securely Read Passwords Using std::cin Without Echoing to the Console?

Secure Password Input with std::cin

When acquiring sensitive user information, such as passwords, it's crucial to prevent the characters typed from being echoed on the screen for privacy concerns. To accomplish this with std::cin, platform-specific mechanisms are employed.

Windows Solution:

Windows utilizes the SetConsoleMode function to toggle echo behavior. The code snippet below sets the echo disabled by clearing the ENABLE_ECHO_INPUT flag:

#ifdef WIN32
#include <windows.h>

...

HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hStdin, &mode);
mode &= ~ENABLE_ECHO_INPUT;
SetConsoleMode(hStdin, mode);
#endif

Unix (Linux/macOS) Solution:

Unix-based systems rely on the termios library and its tcsetattr function. Here's the code to turn off echo:

#else
#include <termios.h>

...

struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
tty.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
#endif

Sample Usage:

With the echo-disabling function in place, here's how to use std::cin to securely read a password:

#include <iostream>
#include <string>

...

SetStdinEcho(false);
std::string password;
std::cin >> password;
SetStdinEcho(true);

By employing these platform-specific methods, you can ensure that user passwords are not echoed on the screen, maintaining both privacy and security in your application.

The above is the detailed content of How Can I Securely Read Passwords Using std::cin Without Echoing to the Console?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn