webrtc_ice/rand/
mod.rs

1#[cfg(test)]
2mod rand_test;
3
4use rand::{thread_rng, Rng};
5
6const RUNES_ALPHA: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
7const RUNES_CANDIDATE_ID_FOUNDATION: &[u8] =
8    b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/+";
9
10const LEN_UFRAG: usize = 16;
11const LEN_PWD: usize = 32;
12
13// TODO: cryptographically strong random source
14pub fn generate_crypto_random_string(n: usize, runes: &[u8]) -> String {
15    let mut rng = thread_rng();
16
17    let rand_string: String = (0..n)
18        .map(|_| {
19            let idx = rng.gen_range(0..runes.len());
20            runes[idx] as char
21        })
22        .collect();
23
24    rand_string
25}
26
27/// <https://tools.ietf.org/html/rfc5245#section-15.1>
28/// candidate-id = "candidate" ":" foundation
29/// foundation   = 1*32ice-char
30/// ice-char     = ALPHA / DIGIT / "+" / "/"
31pub fn generate_cand_id() -> String {
32    format!(
33        "candidate:{}",
34        generate_crypto_random_string(32, RUNES_CANDIDATE_ID_FOUNDATION)
35    )
36}
37
38/// Generates ICE pwd.
39/// This internally uses `generate_crypto_random_string`.
40pub fn generate_pwd() -> String {
41    generate_crypto_random_string(LEN_PWD, RUNES_ALPHA)
42}
43
44/// ICE user fragment.
45/// This internally uses `generate_crypto_random_string`.
46pub fn generate_ufrag() -> String {
47    generate_crypto_random_string(LEN_UFRAG, RUNES_ALPHA)
48}