Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Console private input (passwords)



  • Hi everyone,

    I'm creating a console app that will input private information like user passwords. The problem is, the console itself seems to handle its own history and echo and overall seems detached from the core application so i don't know how to go about controlling this behavior so user passwords would show up in history up/down arrows and echo the password in plain text to the screen.

    what exactly is happening when we use:

    CONFIG += console
    

    I'm assuming it calls the platform specific terminal emulator, question is how do i go about controlling it? what is the best approach to handling private input in QT console?


  • Lifetime Qt Champion

    Hi,

    See the getpass method from the GNU libc manual.



  • This post is deleted!


  • @SGaist said in Console private input (passwords):

    Hi,

    See the getpass method from the GNU libc manual.

    Thanks for the the reply but that seems to only be available in Linux. even the alternative code in that same page requires termios.h which is also only available in Linux. Sorry i forgot mention that i'm targeting both windows and Linux so a cross platform solution is desired.



  • I'll give this code a shot: https://stackoverflow.com/questions/1413445/reading-a-password-from-stdcin

    I'll post again if this works out.



  • yup works like a charm, didn't really make any huge changes different from the code posted in that stack overflow Q/A but here's how i have it currently and it works perfectly:

    void enableEcho(bool enable)
    {
    #ifdef Q_OS_WIN32
    
        HANDLE stdinHandle = GetStdHandle(STD_INPUT_HANDLE);
        DWORD  mode;
    
        GetConsoleMode(stdinHandle, &mode);
    
        if (!enable)
        {
            mode &= ~ENABLE_ECHO_INPUT;
        }
        else
        {
            mode |= ENABLE_ECHO_INPUT;
        }
    
        SetConsoleMode(stdinHandle, 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
    }
    
    

Log in to reply