readpassphrase

Function readpassphrase 

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

Reads a passphrase using readpassphrase(3).

This function tries to faithfully wrap readpassphrase(3) without overhead; the only additional work it does is:

  1. It converts from a Rust byte slice to a C pointer/length pair going in.
  2. It converts from a C char * to a Rust UTF-8 &str coming out.
  3. It translates errors from errno (or string conversion) into Result.

This function reads a passphrase of up to buf.len() - 1 bytes. If the entered passphrase is longer, it will be truncated.

ยงSecurity

The passed buffer might contain sensitive data even if this function returns an error (for example, if the contents are not valid UTF-8.) 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, RppFlags::default())?;
Examples found in repository?
examples/inplace.rs (lines 14-18)
12fn main() {
13    let mut buf = Zeroizing::new(vec![0u8; 256]);
14    let password = readpassphrase(
15        c"Password: ",
16        &mut buf,
17        RppFlags::FORCEUPPER | RppFlags::ECHO_ON,
18    )
19    .expect("failed reading passphrase");
20    println!("{password}");
21}
More examples
Hide additional examples
examples/owned.rs (line 15)
12fn main() -> Result<(), Error> {
13    let mut buf = vec![0u8; PASSWORD_LEN];
14    let pass =
15        Zeroizing::new(readpassphrase(c"Password: ", &mut buf, RppFlags::ECHO_ON)?.to_string());
16    let mut buf = Some(buf);
17    loop {
18        let mut res = readpassphrase_owned(
19            c"Confirmation: ",
20            buf.take().unwrap(),
21            RppFlags::REQUIRE_TTY,
22        )?;
23        if *pass == res {
24            res.zeroize();
25            break;
26        }
27        buf = Some(res.into());
28    }
29    Ok(())
30}