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
Release: 2024-12-20 05:59:12
Original
621 people have browsed it

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);
}
Copy after login

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);
}
Copy after login

Usage

To suppress echoing while retrieving the password:

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

Example

#include <iostream>
#include <string>

int main()
{
    SetStdinEcho(false);

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

    SetStdinEcho(true);

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

    return 0;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template