Rust program to generate a random password using a given set of characters


Generate a random password using a given set of characters

Rust Programming Language


Generate a random password using a given set of characters


Problem


In this program, we will generate a random password using a given set of characters and print generated password.

Add random external library to your project

Create your project using the below command.
$cargo new random --bin{codeBox}

Goto the project folder cd random and edit Cargo.toml file.
$random>nano Cargo.toml{codeBox}

Then add dependency in Cargo.toml file
[dependencies]
rand = "0.5.5"{codeBox}

After that, build your project using the below command
$random>cargo build{codeBox}

Then execute your project after modification in the src/main.rs source file.
$random>cargo run{codeBox}


Input


// Rust program to generate a random password 
// using given set of characters.
fn main() {
    use rand::Rng;
    const CHAR_SET: &[u8] = b"abcdefghijklmnopqrstuvwxyz\
        ABCDEFGHIJKLMNOPQRSTUVWXYZ\
        0123456789(~!@#$%^&*)";
    
    const PWD_LEN: usize = 10;
    let mut rnd = rand::thread_rng();

    let password: String = (0..PWD_LEN)
        .map(|_| {
            let idx = rnd.gen_range(0,CHAR_SET.len());
            CHAR_SET[idx] as char
        })
        .collect();

    println!("Generated password: {:?}", password);
}{codeBox}


Output


$random> cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/random`

Generated password: "MNe2&TMjlf"{codeBox}


Explanation


In the above program, we imported the "rand" library to our project for generating random numbers. We imported the "rand" library using the below line:

use rand::Rng;{codeBox}

In the main() function, we generated a random password using a given set of characters with the help of "rand" library functions and printed the result.

Post a Comment