readpassphrase

Function readpassphrase 

Source
pub fn readpassphrase<'a>(
    prompt: &CStr,
    buf: &'a mut [u8],
    flags: Flags,
) -> Result<&'a str, Error>
Expand description

Reads a passphrase using readpassphrase(3), returning a &str.

This function reads a password of up to buf.len() - 1 bytes into buf. If the entered password is longer, it is truncated to the maximum length. If readpasspharse(3) itself fails, or if the entered password is not valid UTF-8, then Error is returned.

§Security

The passed buffer might contain sensitive data, even if this function returns an error. Therefore it should be zeroed as soon as possible. This can be achieved, for example, with zeroize::Zeroizing:

use zeroize::Zeroizing;
let mut buf = Zeroizing::new(vec![0u8; PASSWORD_LEN]);
let pass = readpassphrase(c"Pass: ", &mut buf, Flags::default())?;
Examples found in repository?
examples/owned.rs (line 15)
12fn main() -> Result<(), Error> {
13    let mut buf = Zeroizing::new(Some(vec![0u8; PASSWORD_LEN]));
14    let pass = Zeroizing::new(
15        readpassphrase(c"Password: ", buf.as_deref_mut().unwrap(), Flags::ECHO_ON)?.to_string(),
16    );
17    let mut buf = buf.take();
18    loop {
19        let mut res =
20            readpassphrase_owned(c"Confirmation: ", buf.take().unwrap(), Flags::REQUIRE_TTY)?;
21        if *pass == res {
22            res.zeroize();
23            break;
24        }
25        buf = Some(res.into_bytes());
26    }
27    Ok(())
28}
More examples
Hide additional examples
examples/inplace.rs (line 17)
14fn main() {
15    let mut buf = Zeroizing::new(vec![0u8; PASSWORD_LEN]);
16    let password = Zeroizing::new(
17        readpassphrase(c"Password: ", &mut buf, RpFlags::empty())
18            .expect("failed reading passphrase")
19            .to_string(),
20    );
21    for _ in 0..5 {
22        let confirm = readpassphrase(c"Confirmation: ", &mut buf, RpFlags::REQUIRE_TTY)
23            .expect("failed reading confirmation");
24        if *password == confirm {
25            eprintln!("Passwords match.");
26            return;
27        }
28        eprintln!("Passwords don’t match.");
29    }
30    eprintln!("Too many attempts.");
31    exit(1);
32}