Home >Backend Development >C++ >How Can I Securely Obtain Password Input in C Without Echoing to the Console?

How Can I Securely Obtain Password Input in C Without Echoing to the Console?

DDD
DDDOriginal
2024-12-20 05:59:12618browse

How Can I Securely Obtain Password Input in C   Without Echoing to the Console?

Secure Password Input in C

To protect user privacy, it's often desirable to prevent passwords entered via standard input from being echoed to the console. Here's how to disable echo using a system-agnostic approach:

Overview

This issue can be addressed on both Windows and UNIX-like operating systems. The solution involves modifying the standard input settings to disable echo.

Windows

For Windows systems, use the Win32 API:

#include <windows.h>

void SetStdinEcho(bool enable = true)
{
    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);
}

UNIX-like Systems

For UNIX-like systems, use the termios library:

#include <termios.h>
#include <unistd.h>

void SetStdinEcho(bool enable = true)
{
    struct termios tty;
    tcgetattr(STDIN_FILENO, &tty);
    if (!enable)
        tty.c_lflag &= ~ECHO;
    else
        tty.c_lflag |= ECHO;

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

Usage

To suppress echoing while retrieving the password:

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

Example

#include <iostream>
#include <string>

int main()
{
    SetStdinEcho(false);

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

    SetStdinEcho(true);

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

    return 0;
}

The above is the detailed content of How Can I Securely Obtain Password Input in C 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