Expand description
base64-ng is a no_std-first Base64 encoder and decoder.
The core API provides strict RFC 4648 behavior, caller-owned output
buffers, and an audited scalar fallback. The 2.0 line admits selected
SIMD encode and strict decode acceleration for standard-family alphabets.
Any accelerated backend must match the scalar module byte-for-byte and pass
the documented admission evidence before dispatch can select it.
STANDARD and URL_SAFE require canonical padding; the explicitly
named STANDARD_NO_PAD and URL_SAFE_NO_PAD engines reject padding.
Strict decode rejects whitespace, mixed alphabets, malformed input, and
non-canonical unused trailing bits. Legacy whitespace and wrapped line
handling remain separately named opt-in policies.
§2.0 API
The 2.0 surface is available through Base64 and the four
explicitly named STRICT_* presets. Its one-shot slice methods validate
and size completely before writing, so every returned error leaves the
destination unchanged. The retained 1.x API remains available as the
compatibility surface documented in the migration guide. Exact const
transforms and bounded ordinary storage are available through the same
validated codec values. The optional secrets capability publishes
separate redacted storage and bounded constant-time-oriented codecs under
base64_ng::secret.
Finite-buffer in-place transforms use explicit input lengths, while secret
in-place decode requires byte-disjoint private staging.
Allocation-free display, exact counted sinks, rollback-capable append, and
synthesized encoded chunk iteration share the same validated codec values.
Exact WHATWG decoding is separately named web::FORGIVING. Expert
padding-indifferent and noncanonical-bit policies live under compat
and never become strict or secret defaults. Accurately scoped body and
alphabet presets include MIME_BODY_STRICT, PEM_BODY_LF,
BCRYPT_ALPHABET_NO_PAD, and PBKDF2_ALPHABET_NO_PAD. The sole generic
legacy transport-whitespace policy is legacy::ASCII_WHITESPACE.
§Examples
Encode and decode with caller-owned buffers:
use base64_ng::{STANDARD, checked_encoded_len};
let input = b"hello";
const ENCODED_CAPACITY: usize = match checked_encoded_len(5, true) {
Some(len) => len,
None => panic!("encoded length overflow"),
};
let mut encoded = [0u8; ENCODED_CAPACITY];
let encoded_len = STANDARD.encode_slice(input, &mut encoded).unwrap();
assert_eq!(&encoded[..encoded_len], b"aGVsbG8=");
let mut decoded = [0u8; 5];
let decoded_len = STANDARD.decode_slice(&encoded, &mut decoded).unwrap();
assert_eq!(&decoded[..decoded_len], input);Use the URL-safe no-padding engine:
use base64_ng::URL_SAFE_NO_PAD;
let mut encoded = [0u8; 3];
let encoded_len = URL_SAFE_NO_PAD.encode_slice(b"\xfb\xff", &mut encoded).unwrap();
assert_eq!(&encoded[..encoded_len], b"-_8");§Sensitive Decode Policy
The default engines such as STANDARD and URL_SAFE_NO_PAD are strict
scalar encoders/decoders with localized diagnostics. They are not
constant-time token validators or key-material decoders: strict decode and
validation may branch or return early based on malformed input, and strict
DecodeError values can include input-derived bytes and indexes. Do not
log strict decode errors verbatim for secret-bearing input; log
DecodeError::kind instead. Use ct::STANDARD,
crate::ct::URL_SAFE_NO_PAD, or Engine::ct_decoder for secret-bearing
payloads where decode timing posture matters more than exact error indexes.
Recommended heap-owning pattern for secret-bearing standard Base64:
use base64_ng::ct;
let expected = b"session-key";
let decoded = ct::STANDARD.decode_secret(b"c2Vzc2lvbi1rZXk=").unwrap();
assert!(decoded.constant_time_eq_public_len(expected));For shared-memory, enclave-adjacent, HSM-style, or multi-principal
deployments where even transient writes into caller-owned output are
unacceptable, use ct::CtEngine::decode_slice_staged_clear_tail with a
private staging buffer.
CT behavior is best-effort and build-profile specific. Link-Time
Optimization can change generated code shape across crate boundaries, so
high-assurance deployments must rerun the dudect and generated-assembly
evidence scripts for their exact compiler, target, feature set, and release
profile before treating CT decode as acceptable.
§Zeroization Caveat
Cleanup APIs and redacted buffers use dependency-free best-effort wiping:
byte-wise volatile zero writes followed by an architecture-gated inline
assembly barrier plus a hardware store-ordering fence where stable Rust
supports it, and a compiler fence on all targets. This resists common
compiler dead-store elimination and orders the issued zero stores on native
supported architectures, but it is not a formal zeroization guarantee and
cannot clear historical copies, registers, cache lines, write buffers, swap,
hibernation images, core dumps, cold-boot remanence, or OS-level memory
snapshots.
High-assurance applications should apply their own approved zeroization
policy to caller-owned buffers at the protocol boundary. Ordinary
public-data codecs do not require a wipe-policy opt-in. When the secrets
capability is enabled, architectures without a native wipe barrier fail
closed unless allow-compiler-fence-only-wipe is enabled after platform
review. On wasm32, secret cleanup is compiler-fence-only and cannot
constrain downstream runtime JITs, so secrets builds require the explicit
allow-wasm32-best-effort-wipe acceptance feature.
Modules§
- assurance
- Runtime assurance tokens and allocation-specific protected ownership.
- compat
- Explicit expert compatibility configurations.
- ct
- Constant-time-oriented scalar decoding APIs.
- legacy
- Explicit legacy ASCII-whitespace compatibility decoding.
- prelude
- Focused imports for ordinary 2.0 Base64 operations.
- runtime
- Runtime backend reporting for security-sensitive deployments.
- secret
- Redacted secret storage and explicit exposure.
- stream
- Streaming Base64 wrappers for
std::io. - web
- Exact WHATWG forgiving Base64 decoding for ordinary web-compatible input.
Macros§
- define_
alphabet - Defines a custom
Alphabetfrom a 64-byte string literal. - secret_
array_ frame - Constructs a stack-backed secret frame while enforcing its capacity limit.
Structs§
- Backend
Health Snapshot - Atomic snapshot of one backend’s health latch.
- Backend
Initialization Report - Summary returned by explicit startup backend initialization.
- Base64
- A codec value parameterized by one complete sealed specification.
- Base64
String - An owned ordinary Base64 string validated by one exact codec policy.
- Bcrypt
- The bcrypt Base64 alphabet.
- Body
Codec - One Base64 codec paired with an encoded-body line layout.
- Body
Wrap - Immutable, always-progressing Base64 body wrapping policy.
- Buffer
Length Error - Error returned when a visible prefix exceeds its backing array.
- Codec
Builder - Fallible no-allocation builder for an advanced ordinary runtime codec.
- Codec
Settings - One complete, immutable ordinary codec policy.
- Crypt
- The Unix
crypt(3)Base64 alphabet. - Decoded
Array - Ordinary bounded decoded bytes.
- Decoded
Buffer - Stack-backed decoded Base64 output.
- Decoder
State - Heapless strict Base64 decoder state.
- Encoded
Array - Ordinary bounded bytes intended to contain encoded text.
- Encoded
Buffer - Stack-backed encoded Base64 output.
- Encoded
Chunk - One synthesized Base64 output chunk.
- Encoded
Chunks - Iterator over synthesized Base64 output chunks for one borrowed input.
- Encoded
Display - Lazy allocation-free encoded display for one borrowed input.
- Encoder
State - Heapless ordinary Base64 encoder state.
- Engine
- A zero-sized Base64 engine parameterized by alphabet and padding policy.
- Exposed
Decoded Array - Owned stack array extracted from
DecodedBuffer. - Exposed
Encoded Array - Owned stack array extracted from
EncodedBuffer. - Exposed
Secret String - Owned secret UTF-8 text extracted from
SecretBuffer. - Exposed
Secret Vec - Owned secret bytes extracted from
SecretBuffer. - Line
Wrap - Base64 line wrapping policy.
- Output
Full - Retry information when the current destination cannot make progress.
- Profile
- A named Base64 profile with an engine and optional strict line wrapping.
- Progress
- Exact progress committed by one transform call.
- Runtime
Spec - A complete owned runtime specification.
- Secret
Buffer - Owned sensitive bytes with redacted formatting and drop-time cleanup.
- Standard
- The RFC 4648 standard Base64 alphabet.
- Static
Backend Token - Non-forgeable, thread-bound proof that a static SIMD backend passed its KAT.
- Step
- One non-failing transform result.
- Strict
Standard Padded - A sealed strict RFC 4648 built-in specification.
- Strict
Standard Unpadded - A sealed strict RFC 4648 built-in specification.
- Strict
UrlSafe Padded - A sealed strict RFC 4648 built-in specification.
- Strict
UrlSafe Unpadded - A sealed strict RFC 4648 built-in specification.
- UrlSafe
- The RFC 4648 URL-safe Base64 alphabet.
- Validated
Alphabet - An owned, immutable, validated 64-byte Base64 alphabet.
Enums§
- Alphabet
Error - Alphabet validation error.
- Assurance
Class - Reporting category for an operation’s assurance boundary.
- Atomicity
- Destination mutation contract used by API and corpus metadata.
- Backend
Class - Reporting category for the selected ordinary backend.
- Backend
Fault - Internal backend integrity failure, separate from attacker input errors.
- Backend
Health State - Runtime state of an ordinary accelerated backend.
- Body
Line Ending - Line ending inserted between encoded body lines.
- Body
Wrap Error - Failure constructing a line-wrapping policy.
- Codec
Builder Error - A policy combination that cannot form a self-consistent codec.
- Const
Transform Error - Error returned by an exact const transform.
- Counted
Write Error - Failure from exact-progress counted-sink encoding.
- Decode
Error - Decoding error.
- Decode
Error Kind - Redacted decoding error class.
- Decode
Padding - Which padding forms ordinary decoding accepts.
- Encode
Error - Encoding error.
- Encode
Padding - Whether ordinary encoding emits canonical
=padding. - Failure
- Absorbing transform failure.
- Format
Write Error - Error from allocation-free formatter encoding.
- InPlace
Error - Error returned by a finite-buffer in-place operation.
- Input
Error - Detailed ordinary malformed-input diagnostic.
- Input
Error Kind - Redacted malformed-input classification.
- Line
Ending - Line ending used by wrapped Base64 output.
- OneShot
Error - Error returned by a canonical ordinary one-shot operation.
- Operation
Error - Error returned by a lifecycle operation.
- Protocol
Scope - Reporting scope for core and companion protocol behavior.
- Status
- Non-failing state reached after one transform call.
- Terminal
Error - Illegal call against a successfully completed state.
- Trailing
Bits - Whether ordinary decoding enforces zero unused trailing bits.
- Validated
Alphabet Error - Failure returned while constructing a
ValidatedAlphabet.
Constants§
- BCRYPT
- bcrypt-style no-padding Base64 profile.
- BCRYPT_
ALPHABET_ NO_ PAD - Standard bit grouping with the bcrypt alphabet and no padding.
- BCRYPT_
NO_ PAD - bcrypt-style Base64 engine without padding.
- BINHEX_
ALPHABET - The 64-character
BinHex4.0 alphabet. - CRYPT
- Unix
crypt(3)-style no-padding Base64 profile. - CRYPT_
ALPHABET_ NO_ PAD - Standard bit grouping with the
crypt(3)alphabet and no padding. - CRYPT_
NO_ PAD - Unix
crypt(3)-style Base64 engine without padding. - IMAP_
MUTF7_ ALPHABET_ NO_ PAD - Standard bit grouping with the IMAP modified-UTF-7 alphabet and no padding.
- MIME
- MIME Base64 profile: standard alphabet, padding, 76-column CRLF wrapping.
- MIME_
BODY_ STRICT - Strict Standard Base64 with MIME’s 76-column CRLF body layout.
- PBKD
F2_ ALPHABET_ NO_ PAD - Standard bit grouping with the PBKDF2-adapted alphabet and no padding.
- PEM
- PEM Base64 profile: standard alphabet, padding, 64-column LF wrapping.
- PEM_
BODY_ CRLF - Strict Standard Base64 with a 64-column CRLF PEM body layout.
- PEM_
BODY_ LF - Strict Standard Base64 with a 64-column LF PEM body layout.
- PEM_
CRLF - PEM Base64 profile with CRLF line endings.
- STANDARD
- Standard Base64 engine with padding.
- STANDARD_
NO_ PAD - Standard Base64 engine without padding.
- STRICT_
STANDARD_ PADDED - Strict RFC 4648 Standard Base64 with canonical padding.
- STRICT_
STANDARD_ UNPADDED - Strict RFC 4648 Standard Base64 without padding.
- STRICT_
URL_ SAFE_ PADDED - Strict RFC 4648 URL-safe Base64 with canonical padding.
- STRICT_
URL_ SAFE_ UNPADDED - Strict RFC 4648 URL-safe Base64 without padding.
- URL_
SAFE - URL-safe Base64 engine with padding.
- URL_
SAFE_ NO_ PAD - URL-safe Base64 engine without padding.
Traits§
- Alphabet
- A Base64 alphabet.
- Codec
- The single sealed consumer boundary for a complete codec specification.
- Counted
Sink - A sink whose successful writes report their exact accepted prefix.
Functions§
- checked_
encoded_ len - Returns the encoded length, or
Noneif it would overflowusize. - checked_
wrapped_ encoded_ len - Returns the encoded length after line wrapping, or
Noneon overflow or invalid line wrapping. - clear_
bytes - Clears caller-owned bytes with this crate’s best-effort cleanup primitive.
- constant_
time_ eq - Compares two byte slices with a public length-mismatch branch.
- constant_
time_ eq_ fixed_ width - Compares two fixed-width byte arrays without a length-mismatch branch.
- decode
- Decodes strict standard padded Base64 into an owned byte vector.
- decode_
alphabet_ byte - Decodes one byte by scanning a caller-provided alphabet table.
- decoded_
capacity - Returns the maximum decoded length for an encoded input length.
- decoded_
len - Returns the exact decoded length implied by input length and padding.
- encode
- Encodes
inputas strict standard padded Base64. - encode_
infallible - Encodes
inputas strict standard padded Base64. - encoded_
len - Returns the encoded length for an input length and padding policy.
- initialize_
backends - Runs KAT initialization for every accelerated backend available now.
- secure_
wipe - Best-effort dependency-free wipe for caller-owned byte slices.
- validate_
alphabet - Validates a 64-byte Base64 alphabet table.
- wrapped_
encoded_ len - Returns the encoded length after applying a line wrapping policy.