Octet string что это
Перейти к содержимому

Octet string что это

  • автор:

ASN.1 простыми словами (часть 3, заключительная)

Продолжаю публикацию своей статьи «ASN.1 простыми словами». Предыдущие части статьи, размещённые на Хабре, можно найти здесь: ASN.1 простыми словами (кодирование типа REAL) и ASN.1 простыми словами (часть 2).

Глава 7. Кодирование последовательностей бит (битовых строк)

В разряд типов, кодирующих битовые строки, я отношу два типа — BIT STRING и OCTET STRING.

Тип BIT STRING предназначен для хранения последовательностей наименьших блоков информации — битов. Фактически никакого кодирования не происходит — в блок значения для закодированного значения помещается блок кодируемого значения. За одним только исключением — в первом октете закодированного значения хранится число не используемых бит. Значения количества не используемых бит может изменяться от 0 до 7. Не используемые биты располагаются в битовой строке крайними справа. То есть если закодирована последовательность бит 0000 1111 = 0F, и число не используемых бит равно 4, то тогда при декодировании эту битовую строку следует трактовать как 0000.

При кодировании типа BIT STRING может быть использован как примитивный метод кодирования, так и конструктивный. Конструктивный метод кодирования битовых строк позволяет просто логически разбить одну битовую строку на множество более мелких. При декодировании такой битовой строки, закодированной конструктивным методом, значения из всех вложенных битовых строк объединяются в одну большую битовую строку. В случае использования конструктивного метода задания битовых строк в блоке значения должны быть закодированы только битовые строки, причём у всех битовых подстрок, кроме последней, октет со значением не используемых бит должен быть равен нулю.

Приведем пример конструктивного кодирования битовых строк. Допустим начальная битовая строка содержит значения 0B 0B 0F, причем количество не используемых бит равно 4. Теперь разобьем эту строку на 3 вложенных битовых подстроки и получим следующую последовательность октетов, кодирующую начальную битовую строку в конструктивной форме:

23 0C
03 02 00 0B
03 02 00 0B
03 02 04 0F

Здесь в первых двух октетах приведены идентификационный октет для конструктивной формы кодирования битовой строки и общая длина значения конструктивной формы (12). Далее задано кодирование битовой строки со значением 0B (количество не используемых бит равно нулю!). Потом еще раз закодирована битовая строка со значением 0B (опять обязательно количество не используемых бит должно быть равно нулю). Последней закодирована битовая строка 0F, у которой задано количество не используемых бит равное 4. Таким образом, соединяя последовательно закодированные битовые подстроки, получим изначально закодированную битовую строку 01 01 0 (4 последних бита не используется, а следовательно F = 1111 отсекается от окончательного значения).

Тип OCTET STRING предназначен для хранения простых последовательностей байт (октетов). То есть в этот тип можно закодировать всё что угодно! То есть в этом типе можно кодировать даже содержимое файлов операционной системы. Одно «но» в случае использования «не явного задания длины» (см. главу про основы кодирования в ASN.1) для типа OCTET STRING следует самостоятельно отслеживать появление в кодируемом потоке появления двух нулевых октетов подряд (00 00) и создавать дополнительные вложенные подстроки, разделяющие нулевые октеты во входном потоке октетов.

Глава 8. Кодирование префиксных типов

Зачастую необходимо различать закодированные в одном элементы одного и того же типа, следующие один за другим (например при кодировании типа SET, где порядок вложенных элементов может быть произвольным). Для этого применяют дополнительное кодирование элементов в блоках с новыми, специфичными тэгами. Например типа REAL имеет класс тэга UNIVERSAL (002) и номер тэга 9. Для того чтобы логически отличить два подряд идущих значения REAL применяют дополнительное, «обёрточное» кодирование значения. Для этого используют классы тэгов кроме класса UNIVERSAL (002). То есть вводят новый тип, со своим отличительным номером тэга и классом тэга, отличным от UNIVERSAL (002), а в качестве значения для этого нового типа кодируется весь стандартный блок закодированного типа REAL (новый тип «инкапсулирует» всё закодированное значение другого типа, вместе с блоками идентификационного октета и блоками длины).

Например «обернем» так закодированное значение для типа REAL для значения 0.15625 (кодированное в двоичной форме, основание равно 2, см. главу про кодирование REAL). Полностью это значение кодируется пятью октетами 09 03 80 FB 05. Для внешней «обертки» используем класс тэга PRIVATE (112) и номер тэга выберем равный 2. Так как в качестве значения для внутреннего блока будет использоваться не примитивный тип, а закодированное стандартное значение для типа REAL, то внешняя «обертка» будет иметь конструктивную форму кодирования. Следовательно полностью тип REAL вместе с «оберткой» будет кодироваться с помощью октетов E2 05 09 03 80 FB 05.

В случае, когда между получателем закодированной информации и отправителем существует заранее согласованная и известная схема ASN.1 сообщений, то при использовании «оберточного кодирования» можно не указывать значение информационного октета для внутреннего, «обёрнутого», значения. В этом случае в качестве значения для «обёртки» будет уже использоваться примитивный тип и закодированное значение можно записать как C2 03 80 FB 05 (здесь C2 — указание на применение класса тэга PRIVATE + применение примитивной формы кодирования + номер тэга равен 2; 03 — длина блока значения; оставшиеся октеты — блок значения, непосредственно взятый из блока значения для стандартного кодирования типа REAL). Таким образом можно сказать, что использование заранее согласованных схем ASN.1 позволяет кодировать в выбранных местах общего ASN.1 сообщения выбранные типы с помощью выбранных значений как классов тэгов, так и номеров классов тэгов (полная свобода действий!).

В заключение скажу несколько слов о нотации, которой обозначаются «префиксные типы». Рассмотрим несколько примеров:

Type1 ::= [0] BOOLEAN

Здесь описывается Type1, который имеет класс тэга «Context-specific» (10)2, номер тэга равный 0 и конструктивную форму кодирования. В блоке значения для Type1 передается полностью кодированное значение стандартного типа BOOLEAN.

Type2 ::= [PRIVATE 2] IMPLICIT BOOLEAN

Здесь описывается тип Type2, который имеет класс тэга «Private» (11)2, номер тэга равный 2 и примитивную форму кодирования. То есть в блоке значения для Type2 передается только соответствующий блок значения из стандартно закодированного типа BOOLEAN (идентификационный блок и блок длины теперь берутся из Type2).

То есть по умолчанию в ASN.1 в качестве класса тэга применяется «Context-specific» (10)2, а также применяется конструктивная форма кодирования. То есть первый пример может быть записан в эквивалентном виде (хотя такая запись и не может непосредственно присутствовать в файле, описывающем типы ASN.1):

Type1 ::= [CONTEXT 0] EXPLICIT BOOLEAN

Кстати формально полный эквивалент стандартному типу, например BOOLEAN, может быть записан как:

BOOLEAN_Eq ::= [UNIVERSAL 1] IMPLICIT BOOLEAN

  1. Блок значения для нового типа всегда берётся из блока значения кодируемого типа;
  2. Использование конструктивного или примитивного кодирования зависит от кодируемого типа — тип кодирования нового типа эквивалентен типу кодирования, применяемому в кодируемом типе;

ConstType ::= [0] REAL
PrimType ::= [PRIVATE 2] IMPLICIT ConstType

В заключение скажу, что для типа CHOICE по правилам кодирования ASN.1 должна всегда применятся нотация EXPLICIT (конструктивное кодирование).

Глава 9. Кодирование типа SEQUENCE

Тип SEQUENCE служит для логической группировки (объединения) закодированных значений для различных типов. Фактически само название SEQUENCE (в переводе «последовательность») указывает на область применения этого типа. Порядок следования типов в последовательности заранее определен и не может быть изменен.
Кодирование для этого типа является «конструктивным», то есть в блоке с закодированным значением содержаться дополнительные подблоки, кодирующие отдельные значения. За более подробным описанием отсылаю читателя к главе 1 этой статьи с более подробным описанием.

Пример кодирования типа SEQUENCE. Предположим, что в последовательности должны быть закодированы два числа: одно целое (INTEGER), равное -128, и одно число с плавающей точкой (REAL) равное 0.15625 (представленное в разложении по основанию 2). Из соответствующих предыдущих глав можно узнать, что целое число кодируется как последовательность октетов (02 01 80), а число с плавающей запятой кодируется как последовательность октетов (09 03 80 FB 05). Тогда тип SEQUENCE, содержащий эти два закодированных числа будет кодироваться в виде:

30 08 02 01 80 09 03 80 FB 05

Здесь первый октет является идентификационным октетом и информирует о том, что закодировано значение типа SEQUENCE и что используется конструктивный метод кодирования. Второй октет хранит количество октетов, в которых закодировано значение типа SEQUENCE. Следующие три октета представляют закодированное значение целого числа (-128), а последние 5 октетов — значение закодированного числа с плавающей точкой (0.15625).

Глава 10. Кодирование типа SET

Кодирование типа SET фактически полностью соответствует кодированию для типа SEQUENCE за тем исключением, что порядок следования типов, закодированных с помощью SET, может изменяться. То есть если для примера взять числа из главы про тип SEQUENCE, то фактически мы получаем два возможных (абсолютно равноценных) варианта кодирования их для типа SET:

Вариант 1: 31 08 02 01 80 09 03 80 FB 05
Вариант 2: 30 08 09 03 80 FB 05 02 01 80

Второй вариант просто помещает закодированное целое число после закодированного числа с плавающей точкой.

В типе SET также могут быть закодированы два (и более) значений, имеющих одинаковые типы. При декодировании их значения различаются с помощью применения «префиксных типов». О них уже было рассказано в главе 8.

Глава 11. Кодирование типа BOOLEAN

Тип BOOLEAN может кодировать только два значение — или TRUE (истина), или FALSE (ложь). В случае если кодируется значение FALSE, то в блоке значения должен быть только один октет равный 00. В случае если кодируется значение TRUE то в блоке значения должен быть только один октет, значение которого отлично от нуля. То есть следующие два варианта кодирования TRUE для типа BOOLEAN эквивалентны:

Вариант 1: 01 01 01
Вариант 2: 01 01 FF

Глава 12. Кодирование типа NULL

Значение типа NULL всегда постоянно и всегда кодируется всего двумя октетами 05 00, где первый октет является информационным октетом, а второй октет — октет длины, который всегда кодирует нулевую длину.

3 Getting Started

The following example demonstrates the basic functionality used to run the Erlang ASN.1 compiler.

Create a file named People.asn containing the following:

This file must be compiled before it can be used. The ASN.1 compiler checks that the syntax is correct and that the text represents proper ASN.1 code before generating an abstract syntax tree. The code-generator then uses the abstract syntax tree to generate code.

The generated Erlang files are placed in the current directory or in the directory specified with option .

The following shows how the compiler can be called from the Erlang shell:

Option verbose can be added to get information about the generated files:

ASN.1 module People is now accepted and the abstract syntax tree is saved in file People.asn1db . The generated Erlang code is compiled using the Erlang compiler and loaded into the Erlang runtime system. There is now an API for encode/2 and decode/2 in module People , which is called like:
‘People’:encode(<Type name>, <Value>)
or
‘People’:decode(<Type name>, <Value>)

Assume that there is a network application that receives instances of the ASN.1 defined type Person , modifies, and sends them back again:

In this example, a series of bytes is received from an external source and the bytes are then decoded into a valid Erlang term. This was achieved with the call ‘People’:decode(‘Person’,Bytes) , which returned an Erlang value of the ASN.1 type Person . Then an answer was constructed and encoded using ‘People’:encode(‘Person’,Answer) , which takes an instance of a defined ASN.1 type and transforms it to a binary according to the BER or PER encoding rules.

The encoder and decoder can also be run from the shell:

Module Dependencies

It is common that ASN.1 modules import defined types, values, and other entities from another ASN.1 module.

Earlier versions of the ASN.1 compiler required that modules that were imported from had to be compiled before the module that imported. This caused problems when ASN.1 modules had circular dependencies.

Referenced modules are now parsed when the compiler finds an entity that is imported. No code is generated for the referenced module. However, the compiled modules rely on that the referenced modules are also compiled.

3.2 ASN.1 Application User Interface

The ASN.1 application provides the following two separate user interfaces:

The module asn1ct , which provides the compile-time functions (including the compiler)

The module asn1rt_nif , which provides the runtime functions for the ASN.1 decoder for the BER back end

The reason for this division of the interfaces into compile-time and runtime is that only runtime modules ( asn1rt* ) need to be loaded in an embedded system.

Compile-Time Functions

The ASN.1 compiler can be started directly from the command line by the erlc program. This is convenient when compiling many ASN.1 files from the command line or when using Makefiles. Some examples of how the erlc command can be used to start the ASN.1 compiler:

Useful options for the ASN.1 compiler:

-b[ber | per | uper]

Choice of encoding rules. If omitted, ber is the default.

-o OutDirectory

Where to put the generated files. Default is the current directory.

-I IncludeDir

Where to search for .asn1db files and ASN.1 source specs to resolve references to other modules. This option can be repeated many times if there are several places to search in. The compiler searches the current directory first.

+der

DER encoding rule. Only when using option -ber .

+maps

Use maps instead of records to represent the SEQUENCE and SET types. No .hrl files will be generated. See the Section Map representation for SEQUENCE and SET for more information.

+asn1config

This functionality works together with option ber . It enables the specialized decodes, see Section Specialized Decode .

+undec_rest

A buffer that holds a message being decoded can also have trailing bytes. If those trailing bytes are important, they can be returned along with the decoded value by compiling the ASN.1 specification with option +undec_rest . The return value from the decoder is where Rest is a binary containing the trailing bytes.

+’Any Erlc Option’

Any option can be added to the Erlang compiler when compiling the generated Erlang files. Any option unrecognized by the ASN.1 compiler is passed to the Erlang compiler.

For a complete description of erlc , see ERTS Reference Manual.

The compiler and other compile-time functions can also be started from the Erlang shell. Here follows a brief description of the primary functions. For a complete description of each function, see module asn1ct in the ASN.1 Reference Manual .

The compiler is started by asn1ct:compile/1 with default options, or asn1ct:compile/2 if explicit options are given.

If PER encoding is wanted:

The generic encode and decode functions can be called as follows:

Runtime Functions

When an ASN.1 specification is compiled with option ber , the asn1rt_nif module and the NIF library in asn1/priv_dir are needed at runtime.

By calling function info/0 in a generated module, you get information about which compiler options were used.

Errors

Errors detected at compile-time are displayed on the screen together with line numbers indicating where in the source file the respective error was detected. If no errors are found, an Erlang ASN.1 module is created.

The runtime encoders and decoders execute within a catch and return or > where Description is an Erlang term describing the error.

Currently, Description looks like this: . Applications should not depend on the exact contents of Description as it could change in the future.

3.3 Multi-File Compilation

There are various reasons for using multi-file compilation:

  • To choose the name for the generated module, for example, because you need to compile the same specs for different encoding rules.
  • You want only one resulting module.

Specify which ASN.1 specs to compile in a module with extension .set.asn . Choose a module name and provide the names of the ASN.1 specs. For example, if you have the specs File1.asn , File2.asn , and File3.asn , your module MyModule.set.asn looks as follows:

If you compile with the following, the result is one merged module MyModule.erl with the generated code from the three ASN.1 specs:

3.4 Remark about Tags

Tags used to be important for all users of ASN.1, because it was necessary to add tags manually to certain constructs in order for the ASN.1 specification to be valid. Example of an old-style specification:

Without the tags (the numbers in square brackets) the ASN.1 compiler refused to compile the file.

In 1994 the global tagging mode AUTOMATIC TAGS was introduced. By putting AUTOMATIC TAGS in the module header, the ASN.1 compiler automatically adds tags when needed. The following is the same specification in AUTOMATIC TAGS mode:

Tags are not mentioned any more in this User’s Guide.

3.5 ASN.1 Types

This section describes the ASN.1 types including their functionality, purpose, and how values are assigned in Erlang.

ASN.1 has both primitive and constructed types:

Primitive Types Constructed Types
BOOLEAN SEQUENCE
INTEGER SET
REAL CHOICE
NULL SET OF and SEQUENCE OF
ENUMERATED ANY
BIT STRING ANY DEFINED BY
OCTET STRING EXTERNAL
Character Strings EMBEDDED PDV
OBJECT IDENTIFIER CHARACTER STRING
Object Descriptor
TIME Types

Table 3.1: Supported ASN.1 Types

The values of each ASN.1 type have their own representation in Erlang, as described in the following sections. Users must provide these values for encoding according to the representation, as shown in the following example:

In Erlang code it can look as follows:

BOOLEAN

Booleans in ASN.1 express values that can be either TRUE or FALSE . The meanings assigned to TRUE and FALSE are outside the scope of this text.

In ASN.1 it is possible to have:

Assigning a value to type Operational in Erlang is possible by using the following Erlang code:

Thus, in Erlang the atoms true and false are used to encode a boolean value.

INTEGER

ASN.1 itself specifies indefinitely large integers. Erlang systems with version 4.3 and higher support very large integers, in practice indefinitely large integers.

The concept of subtyping can be applied to integers and to other ASN.1 types. The details of subtyping are not explained here; for more information, see X.680. Various syntaxes are allowed when defining a type as an integer:

The Erlang representation of an ASN.1 INTEGER is an integer or an atom if a Named Number List (see T6 in the previous list) is specified.

The following is an example of Erlang code that assigns values for the types in the previous list:

These Erlang variables are now bound to valid instances of ASN.1 defined types. This style of value can be passed directly to the encoder for transformation into a series of bytes.

The decoder returns an atom if the value corresponds to a symbol in the Named Number List .

The following ASN.1 type is used for real numbers:

It is assigned a value in Erlang as follows:

In the last line, notice that the tuple <256,10,-2>is the real number 2.56 in a special notation, which encodes faster than simply stating the number as «2.56» . The arity three tuple is , that is, Mantissa * Base^Exponent.

The type NULL is suitable where supply and recognition of a value is important but the actual value is not.

This type is assigned in Erlang as follows:

The actual value is the quoted atom ‘NULL’ .

ENUMERATED

The type ENUMERATED can be used when the value you want to describe can only take one of a set of predefined values. Example:

For example, to assign a weekday value in Erlang, use the same atom as in the Enumerations of the type definition:

The enumerated type is similar to an integer type, when defined with a set of predefined values. The difference is that an enumerated type can only have specified values, whereas an integer can have any value.

BIT STRING

The type BIT STRING can be used to model information that is made up of arbitrary length series of bits. It is intended to be used for selection of flags, not for binary files.

In ASN.1, BIT STRING definitions can look as follows:

The following two notations are available for representation of BIT STRING values in Erlang and as input to the encode functions:

  • A bitstring. By default, a BIT STRING with no symbolic names is decoded to an Erlang bitstring.
  • A list of atoms corresponding to atoms in the NamedBitList in the BIT STRING definition. A BIT STRING with symbolic names is always decoded to the format shown in the following example:

Bits2Val2 and Bits2Val3 denote the same value.

Bits2Val1 is assigned symbolic values. The assignment means that the bits corresponding to gnu and punk , that is, bits 2 and 14 are set to 1, and the rest are set to 0. The symbolic values are shown as a list of values. If a named value, which is not specified in the type definition, is shown, a runtime error occurs.

BIT STRING s can also be subtyped with, for example, a SIZE specification:

This means that no bit higher than 31 can be set.

Deprecated Representations for BIT STRING

In addition to the representations described earlier, the following deprecated representations are available if the specification has been compiled with option legacy_erlang_types :

  • Aa a list of binary digits (0 or 1). This format is accepted as input to the encode functions, and a BIT STRING is decoded to this format if option legacy_bit_string is given.
  • As where Unused denotes how many trailing zero-bits 0-7 that are unused in the least significant byte in Binary . This format is accepted as input to the encode functions, and a BIT STRING is decoded to this format if compact_bit_string has been given.
  • As a hexadecimal number (or an integer). Avoid this as it is easy to misinterpret a BIT STRING value in this format.
OCTET STRING

OCTET STRING is the simplest of all ASN.1 types. OCTET STRING only moves or transfers, for example, binary files or other unstructured information complying with two rules: the bytes consist of octets and encoding is not required.

It is possible to have the following ASN.1 type definitions:

With the following example assignments in Erlang:

By default, an OCTET STRING is always represented as an Erlang binary. If the specification has been compiled with option legacy_erlang_types , the encode functions accept both lists and binaries, and the decode functions decode an OCTET STRING to a list.

Character Strings

ASN.1 supports a wide variety of character sets. The main difference between an OCTET STRING and a character string is that the OCTET STRING has no imposed semantics on the bytes delivered.

However, when using, for example, IA5String (which closely resembles ASCII), byte 65 (in decimal notation) means character ‘A’.

For example, if a defined type is to be a VideotexString and an octet is received with the unsigned integer value X , the octet is to be interpreted as specified in standard ITU-T T.100, T.101.

The ASN.1 to Erlang compiler does not determine the correct interpretation of each BER string octet value with different character strings. The application is responsible for interpretation of octets. Therefore, from the BER string point of view, octets are very similar to character strings and are compiled in the same way.

When PER is used, there is a significant difference in the encoding scheme between OCTET STRING s and other strings. The constraints specified for a type are especially important for PER, where they affect the encoding.

The corresponding Erlang assignments:

The Erlang representation for «BMPString» and «UniversalString» is either a list of ASCII values or a list of quadruples. The quadruple representation associates to the Unicode standard representation of characters. The ASCII characters are all represented by quadruples beginning with three zeros like <0,0,0,65>for character ‘A’. When decoding a value for these strings, the result is a list of quadruples, or integers when the value is an ASCII character.

The following example shows how it works. Assume the following specification is in file PrimStrings.asn1 :

Encoding and decoding some strings:

Type UTF8String is represented as a UTF-8 encoded binary in Erlang. Such binaries can be created directly using the binary syntax or by converting from a list of Unicode code points using function unicode:characters_to_binary/1 .

The following shows examples of how UTF-8 encoded binaries can be created and manipulated:

For details, see the unicode module in STDLIB.

In the following example, this ASN.1 specification is used:

Encoding and decoding a string with Unicode characters:

OBJECT IDENTIFIER

The type OBJECT IDENTIFIER is used whenever a unique identity is required. An ASN.1 module, a transfer syntax, and so on, is identified with an OBJECT IDENTIFIER . Assume the following example:

Therefore, the following example is a valid Erlang instance of type ‘Oid’:

The OBJECT IDENTIFIER value is simply a tuple with the consecutive values, which must be integers.

The first value is limited to the values 0, 1, or 2. The second value must be in the range 0..39 when the first value is 0 or 1.

The OBJECT IDENTIFIER is an important type and it is widely used within different standards to identify various objects uniquely. Dubuisson: ASN.1 — Communication Between Heterogeneous Systems includes an easy-to-understand description of the use of OBJECT IDENTIFIER .

Object Descriptor

Values of this type can be assigned a value as an ordinary string as follows:

TIME Types

Two time types are defined within ASN.1: Generalized Time and Universal Time Coordinated (UTC). Both are assigned a value as an ordinary string within double quotes, for example, «19820102070533.8».

For DER encoding, the compiler does not check the validity of the time values. The DER requirements upon those strings are regarded as a matter for the application to fulfill.

SEQUENCE

The structured types of ASN.1 are constructed from other types in a manner similar to the concepts of array and struct in C.

A SEQUENCE in ASN.1 is comparable with a struct in C and a record in Erlang. A SEQUENCE can be defined as follows:

This is a 4-component structure called Pdu . By default, a SEQUENCE is represented by a record in Erlang. It can also be represented as a map; see Map representation for SEQUENCE and SET . For each SEQUENCE and SET in an ASN.1 module an Erlang record declaration is generated. For Pdu , a record like the following is defined:

The record declarations for a module M are placed in a separate M.hrl file.

Values can be assigned in Erlang as follows:

The decode functions return a record as result when decoding a SEQUENCE or a SET .

A SEQUENCE and a SET can contain a component with a DEFAULT keyword followed by the actual value, which is the default value. The DEFAULT keyword means that the application doing the encoding can omit encoding of the value, which results in fewer bytes to send to the receiving application.

An application can use the atom asn1_DEFAULT to indicate that the encoding is to be omitted for that position in the SEQUENCE .

Depending on the encoding rules, the encoder can also compare the given value to the default value and automatically omit the encoding if the values are equal. How much effort the encoder makes to compare the values depends on the encoding rules. The DER encoding rules forbid encoding a value equal to the default value, so it has a more thorough and time-consuming comparison than the encoders for the other encoding rules.

In the following example, this ASN.1 specification is used:

Example where the BER encoder is able to omit encoding of the default values:

Example with a named BIT STRING where the BER encoder does not omit the encoding:

The DER encoder omits the encoding for the same BIT STRING :

In Erlang, the SET type is used exactly as SEQUENCE . Notice that if BER or DER encoding rules are used, decoding a SET is slower than decoding a SEQUENCE because the components must be sorted.

Extensibility for SEQUENCE and SET

When a SEQUENCE or SET contains an extension marker and extension components as the following, the type can get more components in newer versions of the ASN.1 spec:

In this case it has got a new component b . Thus, incoming messages that are decoded can have more or fever components than this one.

The component b is treated as an original component when encoding a message. In this case, as it is not an optional element, it must be encoded.

During decoding, the b field of the record gets the decoded value of the b component, if present, otherwise the value asn1_NOVALUE .

Map representation for SEQUENCE and SET

If the ASN.1 module has been compiled with option maps , the types SEQUENCE and SET are represented as maps.

In the following example, this ASN.1 specification is used:

Optional fields are to be omitted from the map if they have no value:

When decoding, optional fields will be omitted from the map:

Default values can be omitted from the map:

It is not allowed to use the atoms asn1_VALUE and asn1_DEFAULT with maps.

CHOICE

The type CHOICE is a space saver and is similar to the concept of a ‘union’ in C.

Assume the following:

It is then possible to assign values as follows:

A CHOICE value is always represented as the tuple where ChoiceAlternative is an atom denoting the selected choice alternative.

Extensible CHOICE

When a CHOICE contains an extension marker and the decoder detects an unknown alternative of the CHOICE , the value is represented as follows:

Here BytesForOpenType is a list of bytes constituting the encoding of the «unknown» CHOICE alternative.

SET OF and SEQUENCE OF

The types SET OF and SEQUENCE OF correspond to the concept of an array in several programming languages. The Erlang syntax for both types is straightforward, for example:

In Erlang the following can apply:

Notice that the definition of type SET OF implies that the order of the components is undefined, but in practice there is no difference between SET OF and SEQUENCE OF . The ASN.1 compiler for Erlang does not randomize the order of the SET OF components before encoding.

However, for a value of type SET OF , the DER encoding format requires the elements to be sent in ascending order of their encoding, which implies an expensive sorting procedure in runtime. Therefore it is recommended to use SEQUENCE OF instead of SET OF if possible.

ANY and ANY DEFINED BY

The types ANY and ANY DEFINED BY have been removed from the standard since 1994. It is recommended not to use these types any more. They can, however, exist in some old ASN.1 modules. The idea with this type was to leave a «hole» in a definition where it was possible to put unspecified data of any kind, even non-ASN.1 data.

A value of this type is encoded as an open type .

Instead of ANY and ANY DEFINED BY , it is recommended to use information object class , table constraints , and parameterization . In particular the construct TYPE-IDENTIFIER.@Type accomplish the same as the deprecated ANY .

EXTERNAL, EMBEDDED PDV, and CHARACTER STRING

The types EXTERNAL , EMBEDDED PDV , and CHARACTER STRING are used in presentation layer negotiation. They are encoded according to their associated type, see X.680.

The type EXTERNAL had a slightly different associated type before 1994. X.691 states that encoding must follow the older associated type. So, generated encode/decode functions convert values of the newer format to the older format before encoding. This implies that it is allowed to use EXTERNAL type values of either format for encoding. Decoded values are always returned in the newer format.

Embedded Named Types

The structured types previously described can have other named types as their components. The general syntax to assign a value to component C of a named ASN.1 type T in Erlang is the record syntax #’T’ <'C'=Value>. Here Value can be a value of yet another type T2 , for example:

SEQUENCE b can be encoded as follows in Erlang:

3.6 Naming of Records in .hrl Files

When the option maps is given, no .hrl files will be generated. The rest of this section describes the behavior of the compiler when maps is not used.

When an ASN.1 specification is compiled, all defined types of type SET or SEQUENCE result in a corresponding record in the generated .hrl file. This is because the values for SET and SEQUENCE are represented as records by default.

Some special cases of this functionality are presented in the next section.

Embedded Structured Types

In ASN.1 it is also possible to have components that are themselves structured types. For example, it is possible to have the following:

The following records are generated because of type Emb :

Values of type Emb can be assigned as follows:

For an embedded type of type SEQUENCE / SET in a SEQUENCE / SET , the record name is extended with an underscore and the component name. If the embedded structure is deeper with the SEQUENCE , SET , or CHOICE types in the line, each component name/alternative name is added to the record name.

This results in the following record:

If the structured type has a component with an embedded SEQUENCE OF / SET OF which embedded type in turn is a SEQUENCE / SET , it gives a record with the SEQUENCE OF / SET OF addition as in the following example:

This results in the following records:

A parameterized type is to be considered as an embedded type. Each time such a type is referenced, an instance of it is defined. Thus, in the following example a record with name ‘Seq_b’ is generated in the .hrl file and is used to hold values:

Recursive Types

Types that refer to themselves are called recursive types. Example:

This is allowed in ASN.1 and the ASN.1-to-Erlang compiler supports this recursive type. A value for this type is assigned in Erlang as follows:

3.7 ASN.1 Values

Values can be assigned to an ASN.1 type within the ASN.1 code itself, as opposed to the actions in the previous section where a value was assigned to an ASN.1 type in Erlang. The full value syntax of ASN.1 is supported and X.680 describes in detail how to assign values in ASN.1. A short example:

The value defined here can be used in several ways. It can, for example, be used as the value in some DEFAULT component:

It can also be used from inside an Erlang program. If this ASN.1 code is defined in ASN.1 module Values , the ASN.1 value tt can be reached from Erlang as a function call to ‘Values’:tt() as in the following example:

This example shows that a function is generated by the compiler that returns a valid Erlang representation of the value, although the value is of a complex type.

Furthermore, if the option maps is not used, a macro is generated for each value in the .hrl file. So, the defined value tt can also be extracted by ?tt in application code.

3.8 Macros

The type MACRO is not supported. It is no longer part of the ASN.1 standard.

3.9 ASN.1 Information Objects (X.681)

Information Object Classes, Information Objects, and Information Object Sets (in the following called classes, objects, and object sets, respectively) are defined in the standard definition X.681. Only a brief explanation is given here.

These constructs makes it possible to define open types, that is, values of that type can be of any ASN.1 type. Also, relationships can be defined between different types and values, as classes can hold types, values, objects, object sets, and other classes in their fields. A class can be defined in ASN.1 as follows:

An object is an instance of a class. An object set is a set containing objects of a specified class. A definition can look as follows:

The object object1 is an instance of the class GENERAL-PROCEDURE and has one type field and one fixed type value field. The object object2 has also an optional field ERROR , which is a type field. The field ADDRESS is a UNIQUE field. Objects in an object set must have unique values in their UNIQUE field, as in GENERAL-PROCEDURES :

You cannot encode a class, object, or object set, only refer to it when defining other ASN.1 entities. Typically you refer to a class as well as to object sets by table constraints and component relation constraints (X.682) in ASN.1 types, as in the following:

In type StartMessage , the constraint following field content tells that in a value of type StartMessage the value in field content must come from the same object that is chosen by field msgId .

So, the value #’StartMessage’ is legal to encode as a StartMessage value. However, the value #’StartMessage’ is illegal as the constraint in StartMessage tells that when you have chosen a value from a specific object in object set GENERAL-PROCEDURES in field msgId , you must choose a value from that same object in the content field too. In this second case, it is to be any INTEGER value.

StartMessage can in field content be encoded with a value of any type that an object in object set GENERAL-PROCEDURES has in its NEW MESSAGE field. This field refers to a type field &Message in the class. Field msgId is always encoded as a PrintableString , as the field refers to a fixed type in the class.

In practice, object sets are usually declared to be extensible so that more objects can be added to the set later. Extensibility is indicated as follows:

When decoding a type that uses an extensible set constraint, it is always possible that the value in field UNIQUE is unknown (that is, the type has been encoded with a later version of the ASN.1 specification). The unencoded data is then returned wrapped in a tuple as follows:

Here Binary is an Erlang binary that contains the encoded data. (If option legacy_erlang_types has been given, only the binary is returned.)

3.10 Parameterization (X.683)

Parameterization, which is defined in X.683, can be used when defining types, values, value sets, classes, objects, or object sets. A part of a definition can be supplied as a parameter. For example, if a Type is used in a definition with a certain purpose, you want the type name to express the intention. This can be done with parameterization.

When many types (or another ASN.1 entity) only differ in some minor cases, but the structure of the types is similar, only one general type can be defined and the differences can be supplied through parameters.

Example of use of parameterization:

An example of a value that can be encoded as type T1 is <12,"hello">.

Notice that the compiler does not generate encode/decode functions for parameterized types, only for the instances of the parameterized types. Therefore, if a file contains the types General<> , T1 , and T2 as in the previous example, encode/decode functions are only generated for T1 and T2 .

Octet String: What is it?

I am starting to look into some network programming concepts for a project I am about to take over, and I keep running into this concept of an octet string. Can anyone out there provide some feedback into what this is, and how it relates to network programming?

9 Answers 9

Octet string = sequence of bytes.

«Octet» is standardese for «8-bit byte». It’s supposed to be a less ambiguous term compared to just «byte», because some platforms have bytes of different width (not sure if there are any are still remaining, but they used to exist).

Pavel Minaev's user avatar

Suppose a representation of binary 00000000 to 11111111 as 0x00 to 0xFF in hexadecimal. Then the octetString is simply 00 to FF.

Combining several octets to a string is then like 0x00 0x01 0x02 . or simply 000102.. as an octetstring.

Binary files can be encoded into octetstrings and sent from a webbclient to a server in the form of an ASCII-string containing the 0-F alphabet, like a8b9457fc6e3e410589f or it’s capitals. There are javascript using BASE-64 encoding used to store pictures in Strings. The larger alphabet, in this case(I think ) A-Z,a-z,0-9, the less data needs to be transferred. every octet has 256 different possible values, and are to be stored in an alphabet of 62 letters, clearly one needs to use more than one letter / octet. Possibly the theoretical number is proportional to log62(256).

The conclusion is that improved readability takes more space than it’s binary version, in the octetstream example it’s twice as long since each ascii char is eight bits and 2 chars (16 bits) represent an octet which is eight bits. Quite inefficient.

Octet string что это

В данном разделе описываются типы ASN.1,включая их функциональность,назначение и назначение значений на Erlang.

ASN.1 имеет как примитивные,так и сконструированные типы:

Primitive Types Constructed Types
BOOLEAN SEQUENCE
INTEGER SET
REAL CHOICE
NULL SET OF and SEQUENCE OF
ENUMERATED ANY
BIT STRING ANY DEFINED BY
OCTET STRING EXTERNAL
Character Strings EMBEDDED PDV
OBJECT IDENTIFIER CHARACTER STRING
Object Descriptor
TIME Types

Таблица 3.1:Поддерживаемые ASN.1 Типы

Значения каждого типа ASN.1 имеют свое собственное представление на Erlang,как это описано в следующих разделах.Пользователи должны предоставить эти значения для кодирования в соответствии с представлением,как показано в следующем примере:

В коде Эрланга это может выглядеть следующим образом:

Логические значения в ASN.1 выражают значения, которые могут быть TRUE или FALSE . Значения, присвоенные TRUE и FALSE , выходят за рамки этого текста.

В ASN.1 это возможно:

Присвоение значения типу Operational в Erlang возможно с помощью следующего кода Erlang:

Таким образом, в Erlang атомы true и false используются для кодирования логического значения.

Сам ASN.1 определяет бесконечно большие целые числа.Системы Erlang версии 4.3 и выше поддерживают очень большие целые числа,на практике бесконечно большие целые числа.

Понятие подтипирования может быть применено к целым числам и к другим типам ASN.1.Подробности подтипирования здесь не объясняются;более подробную информацию см.в X.680.Допускаются различные синтаксисы при определении типа как целого числа:

Представление в Эрланге ASN.1 INTEGER является целым числом или атомом, если указан список Named Number List (см. T6 в предыдущем списке).

Ниже приведен пример кода Erlang,который присваивает значения типам из предыдущего списка:

Эти переменные Erlang теперь привязаны к действительным экземплярам определенных типов ASN.1.Этот стиль значения может быть передан непосредственно энкодеру для преобразования в серию байт.

Декодер возвращает атом, если значение соответствует символу в Named Number List .

Для вещественных чисел используется следующий тип ASN.1:

Ему присваивается значение в Erlang следующим образом:

Обратите внимание, что в последней строке кортеж <256,10, -2>представляет собой действительное число 2,56 в специальной записи, которая кодируется быстрее, чем просто указание числа как «2.56» . Кортеж арности три — это , то есть Мантисса * Основание ^ Экспонента.

Тип NULL подходит для случаев, когда передача и распознавание значения важны, а фактическое значение — нет.

В Erlang этот тип назначен следующим образом:

Фактическое значение — это атом ‘NULL’ в кавычках .

Тип ENUMERATED можно использовать, когда значение, которое вы хотите описать, может принимать только одно из набора предопределенных значений. Пример:

Например, чтобы присвоить значение дня недели в Erlang, используйте тот же атом, что и в Enumerations определения типа:

Перечисленный тип аналогичен целочисленному типу,если он определен с набором предопределенных значений.Разница заключается в том,что перечисляемый тип может иметь только заданные значения,в то время как целое число может иметь любое значение.

Тип BIT STRING может использоваться для моделирования информации, состоящей из серий битов произвольной длины. Он предназначен для выбора флагов, а не для двоичных файлов.

В ASN.1 определения BIT STRING могут выглядеть следующим образом:

Следующие две нотации доступны для представления значений BIT STRING в Erlang и в качестве входных данных для функций кодирования:

  1. Битва. По умолчанию BIT STRING без символических имен декодируется в битовую строку Erlang.
  2. Список атомов, соответствующих атомам в NamedBitList в определении BIT STRING . BIT STRING с символическими именами всегда декодируются в формат , показанном в следующем примере:

Bits2Val2 и Bits2Val3 обозначают одно и то же значение.

Bits2Val1 присваиваются символьные значения. Присвоение означает, что биты, соответствующие gnu и punk , то есть биты 2 и 14 установлены в 1, а остальные установлены в 0. Символьные значения показаны в виде списка значений. Если отображается именованное значение, которое не указано в определении типа, возникает ошибка времени выполнения.

BIT STRING также может иметь подтип, например, со спецификацией SIZE :

Это означает,что не может быть установлен бит выше 31.

Исключительное представительство для BIT STRING

В дополнение к представлениям, описанным ранее, следующие устаревшие представления доступны, если спецификация была скомпилирована с опцией legacy_erlang_types :

  1. Список двоичных цифр (0 или 1). Этот формат принимается в качестве входных данных для функций кодирования, и BIT STRING декодируется в этот формат, если задана опция legacy_bit_string .
  2. Как , где Unused обозначает количество завершающих нулевых битов 0-7, которые не используются в младшем значащем байте в Binary . Этот формат принимается в качестве входных данных для функций кодирования, и BIT STRING декодируется в этот формат, если compact_bit_string .
  3. В виде шестнадцатеричного числа (или целого числа). Избегайте этого, поскольку значение BIT STRING в этом формате легко неверно истолковать .

OCTET STRING — самый простой из всех типов ASN.1. OCTET STRING только перемещает или передает, например, двоичные файлы или другую неструктурированную информацию, соблюдая два правила: байты состоят из октетов и кодирование не требуется.

Возможно наличие следующих определений типа ASN.1:

С помощью следующего примера заданий на Эрланге:

По умолчанию OCTET STRING всегда представляется как двоичный файл Erlang. Если спецификация была скомпилирована с опцией legacy_erlang_types , функции кодирования принимают как списки, так и двоичные файлы, а функции декодирования декодируют OCTET STRING в список.

ASN.1 поддерживает широкий спектр наборов символов. Основное различие между OCTET STRING и символьной строкой состоит в том, что OCTET STRING не имеет навязанной семантики доставляемых байтов.

Однако при использовании, например, IA5String (который очень похож на ASCII), байт 65 (в десятичной системе счисления) означает символ «A».

Например, если определенный тип должен быть VideotexString и получен октет с целым числом без знака X , октет должен интерпретироваться, как указано в стандарте ITU-T T.100, T.101.

Компилятор ASN.1 к Erlang не определяет правильную интерпретацию каждого значения октета BER-строки с различными символьными строками.Приложение отвечает за интерпретацию октетов.Поэтому с точки зрения BER-строки октеты очень похожи на символьные строки и скомпилированы таким же образом.

Когда используется PER, существует значительная разница в схеме кодирования между OCTET STRING и другими строками. Ограничения, указанные для типа, особенно важны для PER, поскольку они влияют на кодировку.

Соответствующие задания Эрланга:

Представление Erlang для «BMPString» и «UniversalString» является либо списком ASCII-значений,либо списком четырёхкратных.Четырехкратное представление ассоциируется со стандартным представлением символов в Unicode.Все ASCII-символы представлены четырёхугольниками,начинающимися с трёх нулей типа <0,0,0,65>для символа ‘A’.При декодировании значения для этих строк в результате получается список четырёхугольников,или целых чисел,когда значение является ASCII символом.

В следующем примере показано, как это работает. Предположим, что следующая спецификация находится в файле PrimStrings.asn1 :

Кодирование и декодирование некоторых строк:

Тип UTF8String представлен в Erlang как двоичный код в кодировке UTF-8. Такие двоичные файлы могут быть созданы непосредственно с использованием двоичного синтаксиса или путем преобразования из списка кодовых точек Unicode с помощью функции unicode:characters_to_binary/1 .

Ниже приведены примеры того,как можно создавать кодированные двоичные файлы в кодировке UTF-8 и манипулировать ими:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *