pub fn readpassphrase<'a>(
prompt: &CStr,
buf: &'a mut [u8],
flags: Flags,
) -> Result<&'a str, Error>Expand description
Reads a passphrase using readpassphrase(3).
This function returns a &str backed by buf, representing a password of up to
buf.len() - 1 bytes. Any additional characters and the terminating newline are discarded.
§Errors
Returns Err if readpassphrase(3) itself failed or if the entered password is not UTF-8.
The former will be represented by Error::Io and the latter by Error::Utf8.
§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/inplace.rs (line 9)
6fn main() {
7 let mut buf = Zeroizing::new(vec![0u8; PASSWORD_LEN]);
8 let password = Zeroizing::new(
9 readpassphrase(c"Password: ", &mut buf, RpFlags::empty())
10 .expect("failed reading passphrase")
11 .to_string(),
12 );
13 for _ in 0..5 {
14 let confirm = readpassphrase(c"Confirmation: ", &mut buf, RpFlags::REQUIRE_TTY)
15 .expect("failed reading confirmation");
16 if *password == confirm {
17 eprintln!("Passwords match.");
18 return;
19 }
20 eprintln!("Passwords don’t match.");
21 }
22 eprintln!("Too many attempts.");
23 exit(1);
24}More examples
examples/owned.rs (line 7)
4fn main() -> Result<(), Error> {
5 let mut buf = Zeroizing::new(Some(vec![0u8; PASSWORD_LEN]));
6 let pass = Zeroizing::new(
7 readpassphrase(c"Password: ", buf.as_deref_mut().unwrap(), Flags::ECHO_ON)?.to_string(),
8 );
9 let mut buf = buf.take();
10 loop {
11 buf = Some(
12 match readpassphrase_into(c"Confirmation: ", buf.take().unwrap(), Flags::REQUIRE_TTY) {
13 Ok(mut s) if *pass == s => {
14 s.zeroize();
15 break;
16 }
17 Ok(s) => s.into_bytes(),
18 Err(e) => match e.error() {
19 Error::Io(_) => return Err(e.into()),
20 Error::Utf8(_) => {
21 eprintln!("decode error: {e}");
22 e.into_bytes()
23 }
24 },
25 },
26 );
27 }
28 Ok(())
29}