Skip to main content

Crate base64_ng

Crate base64_ng 

Source
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 Alphabet from a 64-byte string literal.
secret_array_frame
Constructs a stack-backed secret frame while enforcing its capacity limit.

Structs§

BackendHealthSnapshot
Atomic snapshot of one backend’s health latch.
BackendInitializationReport
Summary returned by explicit startup backend initialization.
Base64
A codec value parameterized by one complete sealed specification.
Base64String
An owned ordinary Base64 string validated by one exact codec policy.
Bcrypt
The bcrypt Base64 alphabet.
BodyCodec
One Base64 codec paired with an encoded-body line layout.
BodyWrap
Immutable, always-progressing Base64 body wrapping policy.
BufferLengthError
Error returned when a visible prefix exceeds its backing array.
CodecBuilder
Fallible no-allocation builder for an advanced ordinary runtime codec.
CodecSettings
One complete, immutable ordinary codec policy.
Crypt
The Unix crypt(3) Base64 alphabet.
DecodedArray
Ordinary bounded decoded bytes.
DecodedBuffer
Stack-backed decoded Base64 output.
DecoderState
Heapless strict Base64 decoder state.
EncodedArray
Ordinary bounded bytes intended to contain encoded text.
EncodedBuffer
Stack-backed encoded Base64 output.
EncodedChunk
One synthesized Base64 output chunk.
EncodedChunks
Iterator over synthesized Base64 output chunks for one borrowed input.
EncodedDisplay
Lazy allocation-free encoded display for one borrowed input.
EncoderState
Heapless ordinary Base64 encoder state.
Engine
A zero-sized Base64 engine parameterized by alphabet and padding policy.
ExposedDecodedArray
Owned stack array extracted from DecodedBuffer.
ExposedEncodedArray
Owned stack array extracted from EncodedBuffer.
ExposedSecretString
Owned secret UTF-8 text extracted from SecretBuffer.
ExposedSecretVec
Owned secret bytes extracted from SecretBuffer.
LineWrap
Base64 line wrapping policy.
OutputFull
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.
RuntimeSpec
A complete owned runtime specification.
SecretBuffer
Owned sensitive bytes with redacted formatting and drop-time cleanup.
Standard
The RFC 4648 standard Base64 alphabet.
StaticBackendToken
Non-forgeable, thread-bound proof that a static SIMD backend passed its KAT.
Step
One non-failing transform result.
StrictStandardPadded
A sealed strict RFC 4648 built-in specification.
StrictStandardUnpadded
A sealed strict RFC 4648 built-in specification.
StrictUrlSafePadded
A sealed strict RFC 4648 built-in specification.
StrictUrlSafeUnpadded
A sealed strict RFC 4648 built-in specification.
UrlSafe
The RFC 4648 URL-safe Base64 alphabet.
ValidatedAlphabet
An owned, immutable, validated 64-byte Base64 alphabet.

Enums§

AlphabetError
Alphabet validation error.
AssuranceClass
Reporting category for an operation’s assurance boundary.
Atomicity
Destination mutation contract used by API and corpus metadata.
BackendClass
Reporting category for the selected ordinary backend.
BackendFault
Internal backend integrity failure, separate from attacker input errors.
BackendHealthState
Runtime state of an ordinary accelerated backend.
BodyLineEnding
Line ending inserted between encoded body lines.
BodyWrapError
Failure constructing a line-wrapping policy.
CodecBuilderError
A policy combination that cannot form a self-consistent codec.
ConstTransformError
Error returned by an exact const transform.
CountedWriteError
Failure from exact-progress counted-sink encoding.
DecodeError
Decoding error.
DecodeErrorKind
Redacted decoding error class.
DecodePadding
Which padding forms ordinary decoding accepts.
EncodeError
Encoding error.
EncodePadding
Whether ordinary encoding emits canonical = padding.
Failure
Absorbing transform failure.
FormatWriteError
Error from allocation-free formatter encoding.
InPlaceError
Error returned by a finite-buffer in-place operation.
InputError
Detailed ordinary malformed-input diagnostic.
InputErrorKind
Redacted malformed-input classification.
LineEnding
Line ending used by wrapped Base64 output.
OneShotError
Error returned by a canonical ordinary one-shot operation.
OperationError
Error returned by a lifecycle operation.
ProtocolScope
Reporting scope for core and companion protocol behavior.
Status
Non-failing state reached after one transform call.
TerminalError
Illegal call against a successfully completed state.
TrailingBits
Whether ordinary decoding enforces zero unused trailing bits.
ValidatedAlphabetError
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 BinHex 4.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.
PBKDF2_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.
CountedSink
A sink whose successful writes report their exact accepted prefix.

Functions§

checked_encoded_len
Returns the encoded length, or None if it would overflow usize.
checked_wrapped_encoded_len
Returns the encoded length after line wrapping, or None on 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 input as strict standard padded Base64.
encode_infallible
Encodes input as 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.