15

How can I get password input without showing user input?

fn main() {
    println!("Type Your Password");

    // I want to hide input here, and do not know how
    let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");

    println!("{}", input);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
fengsp
  • 1,035
  • 1
  • 11
  • 19
  • 3
    If the code you presented does something, don't let readers guess (or have to try out) what it does. Should this not echo the password but it does, or doesn't the code work at all? Please **edit** your question to extend it with that information. – Anthon Mar 08 '15 at 08:13
  • I think whether stdin is automatically echoed to stdout is controlled by the ECHO flag in some of the termios functions (under a POSIX system). A quick research on github showed some Rust bindings to it: https://github.com/nathan7/termios.rs. I haven't taken a deep look at this library so I can't tell how easy to use it will be, but you may find some useful information here. – Vaelden Mar 08 '15 at 13:28

1 Answers1

16

Update: you can use the rpassword crate. Quoting from the README:

Add the rpassword crate to your Cargo.toml:

[dependencies]
rpassword = "0.0.4"

Then use the read_password() function:

extern crate rpassword;
    
use rpassword::read_password;
use std::io::Write;
    
fn main() {
    print!("Type a password: ");
    std::io::stdout().flush().unwrap();
    let password = read_password().unwrap();
    println!("The password is: '{}'", password);
}


Old answer

I suspect your best bet is calling some C functions from rust: either getpass (3) or its recommended alternatives (see Getting a password in C without using getpass). The tricky thing is that it differs by platform, of course (if you get it working, it'd be handy as a crate).

Depending on your requirements, you could also try using ncurses-rs (crate "ncurses"); I haven't tested it but it looks like example 2 might demo turning off echoing input.

Parampreet Rai
  • 154
  • 1
  • 12
Caspar
  • 7,039
  • 4
  • 29
  • 41
  • This works if run in cmd but fails if run in cygwin – lucidbrot Dec 23 '19 at 09:58
  • 1
    As written, the prompt `Type a password: ` won't be shown on line-buffered stdout. You'll need to manually flush it (`std::io::stdout().flush().unwrap();`). – Poulsbo Jan 24 '20 at 18:04