Reputation: 1165
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);
}
Upvotes: 20
Views: 11912
Reputation: 29
i'm new to rust so this actually took me a while to figure out but in the end i used TermRead to hide the password:
use termion::input::TermRead;
use std::io;
fn strip_nl(s: &mut String) -> String {
if s.ends_with('\n') {
s.pop();
if s.ends_with('\r') {
s.pop();
}
}
let out: String = s.to_string();
out
}
fn prompt() -> (String, String) {
let mut username = String::new();
let stdin = io::stdin();
let mut stdin = stdin;
let stdout = io::stdout();
let mut stdout = stdout;
println!("Enter Username:");
io::stdin().read_line(&mut username).expect("Failed to read username.");
println!("Enter Password:");
let passwd = TermRead::read_passwd(&mut stdin, &mut stdout);
let Ok(Some(mut password)) = passwd else { todo!() };
(strip_nl(&mut username), strip_nl(&mut password))
}
fn main() {
let (username, password) = prompt();
println!("");
println!("{}, {}", username, password)
}
Upvotes: 1
Reputation: 7759
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);
}
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.
Upvotes: 22