Skip to content

CEncoder

Jay edited this page Oct 3, 2026 · 2 revisions

CEncoder

#include <certpp/asn1/encoder.hpp> --- certpp::asn1

Represents an ASN.1 encoder. This provides static methods for encoding ASN.1 data using definite-length form.

Methods

static size_t encodedValueSize(const CTag& tag, SReadOnlyByteSpan content)

Computes the total number of octets required to encode a tag-length-value with the given tag and content.

  • tag --- The tag of the value to encode.
  • content --- The content octets of the value to encode.

Returns: The number of octets the encoded value will occupy, or 0 if the tag is invalid.

static bool writeEncodedValue( TSpan<uint8_t> destination, EEncodingRule ruleSet, const CTag& tag, SReadOnlyByteSpan content, size_t& bytesWritten )

Writes an ASN.1 tag-length-value into the destination span, using definite-length form.

  • destination --- The destination span to write the encoded value into.
  • ruleSet --- The ASN.1 encoding rule set to use.
  • tag --- The tag of the value to encode.
  • content --- The content octets of the value to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if the value was successfully encoded; otherwise, false.

static inline bool readNextElement( TReadOnlySpan<uint8_t>& cursor, EEncodingRule ruleSet, CTag& outTag, TReadOnlySpan<uint8_t>& outArea )

Reads the next encoded ASN.1 value from a SEQUENCE/SET's content, advancing the cursor past it. Thin re-export of CDecoder::readNextElement() so a caller building up a SEQUENCE/SET OF from freshly-encoded children doesn't need to also name CDecoder.

  • cursor --- The remaining content to read from; advanced past the value read on success.
  • ruleSet --- The ASN.1 encoding rule set to use.
  • outTag --- The output tag of the encoded value.
  • outArea --- The output span containing the encoded value's content.

Returns: True if a value was successfully read; false on a parse error or if cursor was empty.

static bool encodeBoolean(TSpan<uint8_t> destination, bool value, size_t& bytesWritten)

Encodes a BOOLEAN's content octets. Always writes the canonical 1-octet form (0x00 / 0xFF), which is valid under all three rule sets.

  • destination --- The destination span to write into.
  • value --- The value to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if value was successfully encoded; otherwise, false.

static bool encodeInteger(TSpan<uint8_t> destination, int64_t value, size_t& bytesWritten)

Encodes an INTEGER's content octets: a minimal-length two's-complement big-endian integer.

  • destination --- The destination span to write into.
  • value --- The value to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if value was successfully encoded; otherwise, false.

static bool encodeEnumerated(TSpan<uint8_t> destination, uint32_t value, size_t& bytesWritten)

Encodes an ENUMERATED's content octets (encoded identically to INTEGER).

  • destination --- The destination span to write into.
  • value --- The value to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if value was successfully encoded; otherwise, false.

static bool encodeNull(TSpan<uint8_t> destination, size_t& bytesWritten)

Encodes a NULL's content octets (always empty).

  • destination --- The destination span to write into.
  • bytesWritten --- The number of bytes written to the destination span (always 0).

Returns: Always true.

static bool encodeOctetString(TSpan<uint8_t> destination, SReadOnlyByteSpan value, size_t& bytesWritten)

Encodes an OCTET STRING's content octets (a direct copy of value).

  • destination --- The destination span to write into.
  • value --- The octets to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if destination had enough room; otherwise, false.

static inline bool encodeOctetString(TSpan<uint8_t> destination, const COctet& value, size_t& bytesWritten)

Encodes an OCTET STRING's content octets from an owning COctet. Thin wrapper over the SReadOnlyByteSpan overload via COctet::toSpan().

  • destination --- The destination span to write into.
  • value --- The octets to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if destination had enough room; otherwise, false.

static bool encodeBitString( TSpan<uint8_t> destination, SReadOnlyByteSpan bits, uint8_t unusedBits, size_t& bytesWritten )

Encodes a BIT STRING's content octets.

  • destination --- The destination span to write into.
  • bits --- The packed bit data octets.
  • unusedBits --- The number of unused (padding) bits in the last octet of bits (0-7); the corresponding low bits of destination's last written octet are forced to zero.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if the arguments were valid and destination had enough room; otherwise, false.

static inline bool encodeBitString( TSpan<uint8_t> destination, const COctet& bits, uint8_t unusedBits, size_t& bytesWritten )

Encodes a BIT STRING's content octets from an owning COctet's packed bit data. Thin wrapper over the SReadOnlyByteSpan overload via COctet::toSpan().

  • destination --- The destination span to write into.
  • bits --- The packed bit data octets.
  • unusedBits --- The number of unused (padding) bits in the last octet of bits (0-7); the corresponding low bits of destination's last written octet are forced to zero.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if the arguments were valid and destination had enough room; otherwise, false.

static bool encodeNamedBitList( TSpan<uint8_t> destination, SReadOnlyByteSpan bits, uint32_t bitCount, size_t& bytesWritten )

Encodes a BIT STRING used as a NamedBitList (e.g. X.509's KeyUsage), trimming trailing 0 bits per X.690 11.2.2 (an all-zero bit set encodes as the empty BIT STRING).

  • destination --- The destination span to write into.
  • bits --- The packed named bits, MSB-first (bit 0 is the MSB of bits[0]); must cover at least bitCount bits.
  • bitCount --- The number of named bit positions in bits.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if destination had enough room for the trimmed encoding; otherwise, false.

static size_t encodedOidSize(TReadOnlySpan<uint32_t> arcs)

Computes the number of content octets required to encode an OBJECT IDENTIFIER's arcs.

  • arcs --- The arc values (at least 2; arcs[0] must be 0-2, and if arcs[0] < 2, arcs[1] must be < 40).

Returns: The number of octets required, or 0 if arcs is not a valid arc sequence.

static bool encodeOid(TSpan<uint8_t> destination, TReadOnlySpan<uint32_t> arcs, size_t& bytesWritten)

Encodes an OBJECT IDENTIFIER's content octets from its arc values.

  • destination --- The destination span to write into.
  • arcs --- The arc values (see encodedOidSize() for the constraints on arcs[0]/arcs[1]).
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if arcs was valid and destination had enough room; otherwise, false.

template<typename TChar> static size_t encodedOidStringSize(const TString<TChar>& text)

Computes the number of content octets required to encode a dotted-decimal OID string via encodeOidString(). @tparam TChar The source TString's character type (char or wchar_t).

  • text --- The dotted-decimal OID text to measure (e.g. "1.2.840.113549.1.1.1").

Returns: The number of octets required, or 0 if text is not a well-formed dotted-decimal OID (see parseOidArcs()) or doesn't form a valid arc sequence (see encodedOidSize()).

template<typename TChar> static bool encodeOidString(TSpan<uint8_t> destination, const TString<TChar>& text, size_t& bytesWritten)

Encodes an OBJECT IDENTIFIER's content octets from its dotted-decimal text form (e.g. "1.2.840.113549.1.1.1"), the inverse of CDecoder::decodeOidString(). Parses text via parseOidArcs(), then encodes the resulting arc values exactly like encodeOid(). @tparam TChar The source TString's character type (char or wchar_t).

  • destination --- The destination span to write into.
  • text --- The dotted-decimal OID text to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if text was a well-formed dotted-decimal OID forming a valid arc sequence and destination had enough room; otherwise, false.

static bool encodeText( TSpan<uint8_t> destination, EUniversalTags kind, SReadOnlyByteSpan text, size_t& bytesWritten )

Encodes/validates a character string type's content octets.

  • destination --- The destination span to write into.
  • kind --- The universal string tag (see CDecoder::decodeText() for which kinds get their character set validated).
  • text --- The text to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if text is valid for kind's character set and destination had enough room; otherwise, false.

template<typename TChar> static size_t encodedStringSize(const TString<TChar>& text)

Computes the number of UTF-8 content octets required to encode text via encodeString(). TChar=wchar_t measures genuine UTF-8, locale-independent; TChar=char goes through TUtf8Encoding, which treats char as native-locale text -- see encodeString()'s doc comment for the same locale caveat. @tparam TChar The source TString's character type (char or wchar_t).

  • text --- The text to measure.

Returns: The number of content octets required, or 0 if text is empty or not encodable (e.g. text contains a wide character not representable in the current locale, for TChar=char).

template<typename TChar> static bool encodeString( TSpan<uint8_t> destination, EUniversalTags kind, const TString<TChar>& text, size_t& bytesWritten )

Encodes a TString directly into a character string type's content octets, the inverse of CDecoder::decodeString(). Transcodes text to UTF-8 via TUtf8Encoding, then validates the result via CDecoder::decodeText() against kind's character set -- so encoding a TString whose content doesn't fit kind (e.g. non-ASCII text as IA5String) fails rather than silently writing invalid content.

TChar=wchar_t encodes genuine UTF-8 regardless of the process locale. TChar=char instead goes through TUtf8Encoding, which treats char as native-locale text (not raw UTF-8) -- so non-ASCII text only produces valid UTF-8 content under a UTF-8-compatible locale; under "C", only ASCII text encodes successfully. @tparam TChar The source TString's character type (char or wchar_t).

  • destination --- The destination span to write into.
  • kind --- The universal string tag; see CDecoder::decodeText() for which kinds get validated.
  • text --- The text to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if text was successfully transcoded to UTF-8, the result is valid for kind's character set, and destination had enough room; otherwise, false.

static bool encodeUtcTime(TSpan<uint8_t> destination, const SDateTime& time, size_t& bytesWritten)

Encodes a UTCTime's content octets (the DER-canonical "YYMMDDHHMMSSZ" form; always 13 octets).

  • destination --- The destination span to write into.
  • time --- The time to encode; time.isUtc must be true and time.year must be in [1950, 2049].
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if time was encodable and destination had enough room; otherwise, false.

static size_t encodedGeneralizedTimeSize(const SDateTime& time)

Computes the number of content octets required to encode a GeneralizedTime.

  • time --- The time to measure.

Returns: The number of octets required, or 0 if time is not encodable (time.isUtc must be true).

static bool encodeGeneralizedTime(TSpan<uint8_t> destination, const SDateTime& time, size_t& bytesWritten)

Encodes a GeneralizedTime's content octets (the "YYYYMMDDHHMMSS[.fff]Z" form; a trailing ".fff" fractional-seconds part is included only when time.millisecond != 0, with trailing zero digits trimmed per DER).

  • destination --- The destination span to write into.
  • time --- The time to encode; time.isUtc must be true.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if time was encodable and destination had enough room; otherwise, false.

static bool writeSequenceOf( TSpan<uint8_t> destination, TReadOnlySpan<SReadOnlyByteSpan> children, size_t& bytesWritten )

Builds a SEQUENCE/SEQUENCE OF's content octets by concatenating already-encoded child tag-length-values, in the order given.

  • destination --- The destination span to write into.
  • children --- The already-encoded children, in encoding order.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if destination had enough room for all children; otherwise, false.

static bool writeSetOf( TSpan<uint8_t> destination, TSpan<SReadOnlyByteSpan> children, size_t& bytesWritten )

Builds a SET OF's content octets from already-encoded child tag-length-values. Reorders children in place into ascending order by encoded octets (X.690 11.6), the canonical order CER/DER require and that remains valid under BER, before concatenating them.

  • destination --- The destination span to write into.
  • children --- The already-encoded children; reordered by this call.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if destination had enough room for all children; otherwise, false.

static size_t encodedDistinguishedNameSize(const CDistinguishedName& value)

Computes the number of content octets required to encode a CDistinguishedName via encodeDistinguishedName(), i.e. the size of the resulting SEQUENCE's content (the RDNSequence content, not including the outer SEQUENCE tag-length).

  • value --- The distinguished name to measure.

Returns: The number of octets required; 0 both for an empty (no-component) value and for one that can't be encoded (see encodeDistinguishedName()) -- as with encodedStringSize(), callers that need to tell the two apart should call encodeDistinguishedName() directly and check its return value.

static bool encodeDistinguishedName( TSpan<uint8_t> destination, const CDistinguishedName& value, size_t& bytesWritten )

Encodes a CDistinguishedName (X.501 Name/RDNSequence) into a SEQUENCE's content octets, the inverse of CDecoder::decodeDistinguishedName(). One RelativeDistinguishedName (SET) is written per component, in the CDistinguishedName's ascending ENameType order, each containing exactly one AttributeTypeAndValue (SEQUENCE {}): type is the component's X.520 attribute OID (CName::attributeOid()), and value is the component's unescaped text (CName::toString<wchar_t>()) encoded as a PrintableString where possible, falling back to a UTF8String otherwise.

Always applies DER's encoding rules; see CDecoder::decodeDistinguishedName() for why.

  • destination --- The destination span to write into.
  • value --- The distinguished name to encode.
  • bytesWritten --- The number of bytes written to the destination span.

Returns: True if every component has a recognized X.520 OID and encodable text, and destination had enough room; otherwise, false. Vacuously true (bytesWritten = 0) for an empty (no-component) value.

Example

Encodes an INTEGER in two steps, because that is how the class is split: encodeInteger() writes only the content octets, and writeEncodedValue() wraps content in its tag and length. Each reports its own bytesWritten, and that -- not the buffer's sizeof -- is the encoded length.

// given: int64_t serial
uint8_t content[8];
size_t contentLength = 0;

if (!CEncoder::encodeInteger(TSpan<uint8_t>(content, sizeof(content)), serial, contentLength)) {
    return;
}

const CTag tag(EAUTAG_INTEGER, false);
SReadOnlyByteSpan body(content, contentLength);

uint8_t element[16];
size_t elementLength = 0;

if (CEncoder::encodedValueSize(tag, body) > sizeof(element)) {
    return;
}

if (!CEncoder::writeEncodedValue(TSpan<uint8_t>(element, sizeof(element)), EAENC_DER, tag, body, elementLength)) {
    return;
}

// element[0 .. elementLength) is the complete DER tag-length-value

Reference generated from certpp/asn1/encoder.hpp at commit 0834b29 (v1.0.1). The header is authoritative --- if this page disagrees with it, the header is right and this page needs regenerating.

Clone this wiki locally