thotp 0.1.11

An RFC based implementation of TOTPs and HOTPs
Documentation
//! A simple module containing 2 functions to encode and decode the secrets generated by this crate's
//! `generate_secret` function to and from the given encoding available in the
//! [data_encoding](https://docs.rs/data-encoding/latest/data_encoding/index.html) crate.
//!
//!
//! ## Example
//! ```
//! use thotp::encoding::{encode, decode};
//! use thotp::generate_secret;
//!
//! let buffer = generate_secret(160);
//!
//! let encoded = encode(&buffer, data_encoding::BASE32);
//!
//! let decoded: [u8; 160] =
//!   decode(&encoded, data_encoding::BASE32)
//!   .unwrap()
//!   .try_into()
//!   .unwrap();
//!
//! assert_eq!(buffer, decoded)
//! ```

use super::ThotpError;
pub use data_encoding;
use data_encoding::Encoding;

/// Encodes the provided buffer to the encoding of choice. Useful for encoding secret
/// buffers generated by this crate's `generate_secret` function.
pub fn encode(buffer: &[u8], encoding: Encoding) -> String {
    encoding.encode(buffer)
}

/// Decodes the provided string from the encoding of choice. Useful for decoding
/// encoded secrets generated with this crate's `generate_secret` and `encode` functions.
pub fn decode(key: &str, encoding: Encoding) -> Result<Vec<u8>, ThotpError> {
    let decoded = encoding.decode(key.as_bytes())?;
    Ok(decoded)
}

#[cfg(test)]
mod tests {
    use super::super::{generate_secret, ThotpError};
    use super::{decode, encode};

    #[test]
    fn encode_decode() -> Result<(), ThotpError> {
        let buffer = generate_secret(160);
        let encoded = encode(&buffer, data_encoding::BASE32);
        let decoded: [u8; 160] = decode(&encoded, data_encoding::BASE32)?.try_into().unwrap();
        assert_eq!(buffer, decoded);
        Ok(())
    }
}