Crate ct_codecs

Source
Expand description

§CT-Codecs

A Rust implementation of constant-time Base64 and Hexadecimal codecs, reimplemented from libsodium and libhydrogen.

§Features

  • Constant-time implementation for cryptographic applications where timing attacks are a concern
  • Strict validation ensuring Base64 strings are not malleable
  • Multiple variants of Base64: standard, URL-safe, with and without padding
  • Character filtering for ignoring specific characters during decoding (like whitespace)
  • Zero dependencies and no_std compatible
  • Memory safety with #![forbid(unsafe_code)]

§Usage Examples

§Base64 Encoding

use ct_codecs::{Base64, Encoder};

fn example() -> Result<(), ct_codecs::Error> {
    let data = b"Hello, world!";
    let encoded = Base64::encode_to_string(data)?;
    assert_eq!(encoded, "SGVsbG8sIHdvcmxkIQ==");
    Ok(())
}

§Base64 Decoding

use ct_codecs::{Base64, Decoder};

fn example() -> Result<(), ct_codecs::Error> {
    let encoded = "SGVsbG8sIHdvcmxkIQ==";
    let decoded = Base64::decode_to_vec(encoded, None)?;
    assert_eq!(decoded, b"Hello, world!");
    Ok(())
}

§Hexadecimal Encoding/Decoding

use ct_codecs::{Hex, Encoder, Decoder};

fn example() -> Result<(), ct_codecs::Error> {
    let data = b"Hello, world!";
    let encoded = Hex::encode_to_string(data)?;
    let decoded = Hex::decode_to_vec(&encoded, None)?;
    assert_eq!(decoded, data);
    Ok(())
}

§No-std Usage with Pre-allocated Buffers

use ct_codecs::{Base64, Encoder, Decoder};

fn example() -> Result<(), ct_codecs::Error> {
    let data = b"Hello, world!";
    let mut encoded_buf = [0u8; 20]; // Must be large enough
    let encoded = Base64::encode(&mut encoded_buf, data)?;
     
    let mut decoded_buf = [0u8; 13]; // Must be large enough
    let decoded = Base64::decode(&mut decoded_buf, encoded, None)?;
    assert_eq!(decoded, data);
    Ok(())
}

Structs§

Base64
Standard Base64 encoder and decoder with padding.
Base64NoPadding
Standard Base64 encoder and decoder without padding.
Base64UrlSafe
URL-safe Base64 encoder and decoder with padding.
Base64UrlSafeNoPadding
URL-safe Base64 encoder and decoder without padding.
Hex
Hexadecimal encoder and decoder implementation.

Enums§

Error
Error type for ct-codecs operations.

Traits§

Decoder
Trait for decoding text representations back into binary data.
Encoder
Trait for encoding binary data into text representations.

Functions§

verify
Constant-time equality check for two byte slices.