secret/
secret.rs

1use totp_rs::{Algorithm, Secret, TOTP};
2
3#[cfg(feature = "otpauth")]
4fn main() {
5    // create TOTP from base32 secret
6    let secret_b32 = Secret::Encoded(String::from("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG"));
7    let totp_b32 = TOTP::new(
8        Algorithm::SHA1,
9        6,
10        1,
11        30,
12        secret_b32.to_bytes().unwrap(),
13        Some("issuer".to_string()),
14        "user-account".to_string(),
15    )
16    .unwrap();
17
18    println!(
19        "base32 {} ; raw {}",
20        secret_b32,
21        secret_b32.to_raw().unwrap()
22    );
23    println!(
24        "code from base32:\t{}",
25        totp_b32.generate_current().unwrap()
26    );
27
28    // create TOTP from raw binary value
29    let secret = [
30        0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2d, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2d, 0x73, 0x65,
31        0x63, 0x72, 0x65, 0x74, 0x2d, 0x31, 0x32, 0x33,
32    ];
33    let secret_raw = Secret::Raw(secret.to_vec());
34    let totp_raw = TOTP::new(
35        Algorithm::SHA1,
36        6,
37        1,
38        30,
39        secret_raw.to_bytes().unwrap(),
40        Some("issuer".to_string()),
41        "user-account".to_string(),
42    )
43    .unwrap();
44
45    println!("raw {} ; base32 {}", secret_raw, secret_raw.to_encoded());
46    println!(
47        "code from raw secret:\t{}",
48        totp_raw.generate_current().unwrap()
49    );
50}
51
52#[cfg(not(feature = "otpauth"))]
53fn main() {
54    // create TOTP from base32 secret
55    let secret_b32 = Secret::Encoded(String::from("OBWGC2LOFVZXI4TJNZTS243FMNZGK5BNGEZDG"));
56    let totp_b32 = TOTP::new(Algorithm::SHA1, 6, 1, 30, secret_b32.to_bytes().unwrap()).unwrap();
57
58    println!(
59        "base32 {} ; raw {}",
60        secret_b32,
61        secret_b32.to_raw().unwrap()
62    );
63    println!(
64        "code from base32:\t{}",
65        totp_b32.generate_current().unwrap()
66    );
67
68    // create TOTP from raw binary value
69    let secret = [
70        0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2d, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x2d, 0x73, 0x65,
71        0x63, 0x72, 0x65, 0x74, 0x2d, 0x31, 0x32, 0x33,
72    ];
73    let secret_raw = Secret::Raw(secret.to_vec());
74    let totp_raw = TOTP::new(Algorithm::SHA1, 6, 1, 30, secret_raw.to_bytes().unwrap()).unwrap();
75
76    println!("raw {} ; base32 {}", secret_raw, secret_raw.to_encoded());
77    println!(
78        "code from raw secret:\t{}",
79        totp_raw.generate_current().unwrap()
80    );
81}