PDFium Delphi Component Docs

FPdfAsn1 unit

Unit: FPdfAsn1
Encodes, navigates, decodes and validates ASN.1 Distinguished Encoding Rules data with bounded resource use

Public Types

TypeDescription
TAsnTagUniversal tag constants (BOOLEAN, INTEGER, OCTET STRING, OID, SEQUENCE, SET, time and string forms) used by identifier construction and validation
TAsnClassIdentifier class: asnClassUniversal, asnClassApplication, asnClassContextSpecific, or asnClassPrivate
TAsnIdentifierIdentifier class, constructed flag, and 64-bit tag number, including high-tag-number form
TDerTlvParsed TLV with Offset, HeaderLength, ContentOffset, ContentLength, NextOffset and Identifier without copying the source buffer
TDerWriterReusable DER output buffer and typed encoder
TDerReaderBounded reader with peek, advance, skip, expected-tag, child-window, slice and typed decode operations
TDerByteArraysDynamic array of TBytes used by ConcatMany and other multi-buffer helpers
TDerValidationErrorKindValidation error categories: dvekMalformedTlv, dvekTrailingData, depth, node and content limits (dvekDepthLimit, dvekNodeLimit, dvekContentLimit), dvekUniversalForm, per-type canonical failures (dvekBoolean, dvekInteger, dvekBitString, dvekNull, dvekOid, dvekString, dvekTime) and dvekSetOrder
TDerValidationErrorOffset- and Depth-aware error record with Kind and human-readable message text
TDerValidationErrorsDynamic array of TDerValidationError returned inside TDerValidationResult
TDerValidationOptionsLimits in MaxDepth, MaxNodes, MaxContentLength, MaxErrors, the RequireSingleRoot flag, optional ValidateSetOrder, and the Default class function
TDerValidationResultValidation status with IsValid, NodeCount, MaximumDepth, offset-aware Errors, plus ErrorCount and FirstError helpers

Writer APIs

APIDescription
Clear, IsEmpty, Count, Capacity, Bytes, FinishReset or inspect buffered data, copy a snapshot, or transfer the completed array and reset the writer
Reserve, Append, AppendMany, AppendByteGrow once and append arrays, caller-owned buffers, multiple arrays, or one byte with overflow checks
Wrap, WrapIdentifier, WrapConstructedWrap content with a raw identifier octet, any identifier class and 64-bit tag number, or a constructed identifier
ContextSpecific, ApplicationSpecific, PrivateSpecificEncode low or high tag numbers without truncating the identifier
Sequence, SequenceOf, SetOf, SetOfSortedCompose encoded values as SEQUENCE or SET containers; SetOfSorted sorts values by encoded bytes
BooleanOf, IntegerOf, UnsignedIntegerOf, IntegerBytes, EnumeratedOfEncode BOOLEAN, signed or unsigned INTEGER, validated arbitrary INTEGER content, and ENUMERATED values
OctetString, OctetStringOf, BitString, Null, OIDEncode binary, bit-string, NULL and object identifier values as standalone TLVs
PrintableString, Ia5String, Utf8StringEncode the supported ASN.1 character string forms
UTCTime, GeneralizedTime, UTCTimeOf, GeneralizedTimeOf, TimeOfEncode canonical time text or UTC TDateTime values, with TimeOf selecting the correct DER time type
AlgId, AlgIdWithParamsBuild an AlgorithmIdentifier SEQUENCE with NULL or explicit parameters

Reader APIs

APIDescription
Initialize, AtEnd, EffectiveLimit, RemainingInitialise a reader and inspect its bounded window and remaining byte count
TryReadTlvAt, PeekTlvParse low or high tag numbers and minimal definite lengths without changing Position
ReadNextTlv, SkipTlvAdvance only after a complete valid TLV is available
TryReadExpectedAdvance only when class, constructed form and tag number all match
EnterConstructedCreate a child reader window over the same source array without copying content
ContentBytes, EncodedBytesCopy a validated content or complete TLV slice when ownership is required
TryReadBoolean, TryReadUnsignedInteger, TryReadBitStringDecode canonical primitive values with range and unused-bit checks
TryReadString, TryReadTime, TryReadNullDecode validated UTF8String, PrintableString, IA5String, DER time or NULL content
ReadTlv, TryReadOID, ReadOID, TryReadInteger, ReadIntegerProvide compatibility access to raw TLV offsets plus object identifier and signed integer decoding

Validation

function ValidateDer(const Data: TBytes): TDerValidationResult; overload;
function ValidateDer(const Data: TBytes; const Options: TDerValidationOptions): TDerValidationResult; overload;

ValidateDer checks identifier and length minimality, buffer bounds, universal primitive forms, BOOLEAN, INTEGER, ENUMERATED, BIT STRING, NULL, OBJECT IDENTIFIER, supported strings and canonical time values

Default limits allow a maximum depth of 64, 100000 nodes, 64 MiB per content value, and 32 reported errors whilst requiring one root TLV

ValidateSetOrder is disabled by default because schema-free DER cannot distinguish every SET from SET OF; enable it for known SET OF containers such as CMS attribute collections

TDerValidationOptions.Default supplies the bounded defaults, whilst TDerValidationResult.ErrorCount and FirstError simplify diagnostic handling

Public helper functions

function AsnIdentifier(TagClass: TAsnClass; TagNumber: UInt64; Constructed: Boolean = False): TAsnIdentifier;
function EncodeIdentifier(const Identifier: TAsnIdentifier): TBytes;
function ConcatBytes(const A, B: TBytes): TBytes;
function Concat3(const A, B, C: TBytes): TBytes;
function Concat4(const A, B, C, D: TBytes): TBytes;
function ConcatMany(const Values: TDerByteArrays): TBytes;
function EncodeOIDContent(const Dotted: AnsiString): TBytes;
function DerValidationErrorKindName(Kind: TDerValidationErrorKind): string;

FunctionDescription
AsnIdentifierBuilds a TAsnIdentifier from class, tag number and constructed flag, used to drive TDerReader.TryReadExpected
EncodeIdentifierEncodes a TAsnIdentifier into its DER identifier bytes, including high-tag-number form
ConcatBytes, Concat3, Concat4, ConcatManyConcatenate two, three, four or a dynamic array of TBytes into one allocation; used widely by the CMS builder
EncodeOIDContentEncodes a dotted-decimal OID string into its content bytes without the tag and length, so callers can inspect or re-wrap an OID
DerValidationErrorKindNameReturns the display name of a TDerValidationErrorKind for diagnostics

Example

uses FPdfAsn1;

var
  Child: TDerReader;
  Data: TBytes;
  Reader: TDerReader;
  Tlv: TDerTlv;
  Validation: TDerValidationResult;
  Writer: TDerWriter;
begin
  Writer := TDerWriter.Create;
  try
    Data := Writer.Sequence(Writer.UnsignedIntegerOf(42));
  finally
    Writer.Free;
  end;

  Validation := ValidateDer(Data);
  if not Validation.IsValid then
    raise EConvertError.Create(Validation.Errors[0].MessageText);

  Reader.Initialize(Data);
  if Reader.TryReadExpected(AsnIdentifier(asnClassUniversal, 16, True), Tlv) then
    Reader.EnterConstructed(Tlv, Child);
end;

Remarks