create a password with uppercase, lowercase letters and numbers in rust

To create a password with uppercase letters, lowercase letters, and numbers, you can use Rust's built-in random number generator combined with ASCII character ranges. Here's an example function that generates a random password with 10 characters, including at least one uppercase letter, one lowercase letter, and one number:

main.rs
use rand::Rng;

fn generate_password() -> String {
    let mut rng = rand::thread_rng();
    let mut password = String::new();

    // add at least one uppercase letter
    let upper: u8 = rng.gen_range(b'A', b'Z');
    password.push(char::from(upper));

    // add at least one lowercase letter
    let lower: u8 = rng.gen_range(b'a', b'z');
    password.push(char::from(lower));

    // add at least one number
    let num: u8 = rng.gen_range(b'0', b'9');
    password.push(char::from(num));

    // add the remaining characters
    for _ in 0..7 {
        let c: u8 = rng.gen_range(b'!', b'~'); // generate printable ASCII characters
        password.push(char::from(c));
    }

    // shuffle the characters in the password
    let mut chars: Vec<char> = password.chars().collect();
    rng.shuffle(&mut chars);
    password = chars.into_iter().collect();

    password
}
876 chars
32 lines

This function first adds one random uppercase letter, one random lowercase letter, and one random number to the password. Then it generates seven more random characters from the range of printable ASCII characters (! through ~), and adds those to the password as well. Finally, it shuffles the characters in the password to randomize their order.

Note that for security purposes, you may want to make the password longer and/or more complex by adding additional character ranges (such as symbols). Also, make sure to store and validate user passwords securely in your application.

gistlibby LogSnag