CT-Codecs
A Rust implementation of constant-time Base64 and Hexadecimal codecs, originally from libsodium and libhydrogen.
Features
- Constant-time implementation: Suitable for cryptographic applications where timing attacks are a concern
- Strict validation: Base64 strings are not malleable, providing security for cryptographic applications
- Multiple variants: Supports standard Base64, URL-safe Base64, both with and without padding
- Character filtering: Supports ignoring specific characters during decoding (useful for whitespace/newlines)
- Zero dependencies: No external crates required
no_stdcompatible: Works in environments without the standard library- Memory safety: No unsafe code (
#![forbid(unsafe_code)])
Installation
Add this to your Cargo.toml:
[]
= "1.1.3"
Usage Examples
Base64 Encoding/Decoding
use ;
// Standard Base64 with padding
let data = b"Hello, world!";
let encoded = encode_to_string?;
assert_eq!;
// Decoding
let decoded = decode_to_vec?;
assert_eq!;
// Ignoring specific characters (like whitespace)
let encoded_with_whitespace = "SGVsbG8s IHdvcmxk IQ==";
let decoded = decode_to_vec?;
assert_eq!;
URL-safe Base64 Encoding/Decoding
use ;
// URL-safe Base64 with padding
let data = b"Hello, world!";
let encoded = encode_to_string?;
assert_eq!;
// URL-safe Base64 without padding
let encoded_no_padding = encode_to_string?;
assert_eq!;
// Decoding
let decoded = decode_to_vec?;
assert_eq!;
Hexadecimal Encoding/Decoding
use ;
let data = b"Hello, world!";
let encoded = encode_to_string?;
assert_eq!;
let decoded = decode_to_vec?;
assert_eq!;
Working in no_std Environments
use ;
// Preallocated buffers for no_std environments
let data = b"Hello, world!";
let mut encoded_buf = ; // Buffer must be large enough
let encoded = encode?;
let mut decoded_buf = ; // Buffer must be large enough
let decoded = decode?;
assert_eq!;
Error Handling
The library uses a simple error type with two variants:
Error::Overflow: The provided output buffer would be too smallError::InvalidInput: The input isn't valid for the given encoding
Security Considerations
All operations are implemented to run in constant time relative to the input length, which helps prevent timing side-channel attacks. This makes the library suitable for handling sensitive cryptographic material.
License
This project is licensed under the MIT License - see the LICENSE file for details.