TLV 格式及编码

来源:互联网 发布:大金微交易软件 编辑:程序博客网 时间:2024/04/25 12:02
 

一种可变格式,TLV的意思就是:Type类型, Lenght长度,Value值;
Type和Length的长度固定,一般那是2、4个字节;
Value的长度有Length指定;
解析方法:
      1.读取type 转换为ntohl、ntohs转换为主机字节序得到类型;指针偏移+2或4
      2.读取lenght,转换为ntohl、ntohs转换为主机字节序得到长度;指针偏移+2或4
      3.根据得到的长度读取value,指针偏移+Length;
      。。。。
      继续处理后面的tlv;

 

标签(Tag)字段是关于标签和编码格式的信息;
长度 (Length)字段定义数值的长度;
内容(Value)字段表示实际的数值。
因此,一个编码值又称TLV(Tag,Length,Value)三元组。编码可以是基本型或结构型,如果它表示一个简单类型的、完整的显式值,那么编码就是基本型 (primitive);如果它表示的值具有嵌套结构,那么编码就是结构型 (constructed)。

TLV编码就是指先对Tag编码,再对Length编码,最后对Value编码。BER编码的长度确定的编码方式就是这样的。
BER编码有两种方式:
一种是长度确定的编码方式。这由3部分组成Identifier octets、Length octets和Contents octets(可以和TLV对应)。另一种是长度不确定的编码方式。这由4部分组成Identifier octets、Length octets、Contents octets、End-of-contents octets。其中Length octets为0x80,End-of-contents octets为0x00 00。每种类型都能够编码成长度确定的编码方式,但是有的类型不能够编码成长度不确定的编码方式。DER编码只能使用长度确定的编码方式。
Identifier octets由3部分组成Class、P/C和Tag number。Identifier octets的第一个字节的高2位为Class,接下来一位为P/C,其他位表示Tag number。Class有4中类型Universal(00)、Application(01)、Context-specific(10)和Private(11)。P/C位如果为1则表示是Constructed的,为0表示是Primitive。如果0<=Tag number<=30,则整个Identifier octets只有一个字节,否则第一个字节的后5位前为1,接下来找第一个最高位为0的字节,该字节就是Identifier octets的最后一个字节。从第二个字节到最后一个字节去掉最高位的值拼起来就是Tag number的值。
长度确定的编码方式的Length octets有两种方法编码长度,一种是只用一个字节表示长度,其最高位为0,后7位表示长度值,显然这样只能表示0-127。另一种是第一个字节的最高位为1,其他位表示后面还有多少个字节属于Length octets。后面的那些字节组成的就是长度值。长度值表示的是Contents octets所占的字节数。DER要求如果长度为0-127则要使用第一种方式,如果大于127则使用后一种方式。
The tag field (T) consists of one or more consecutive bytes. It indicates a class,
a type, and a number. The tag field of the data objects
described in this specification is coded on one or two bytes.

* The length field (L) consists of one or more consecutive bytes. It indicates the
length of the following field. The length field of the data objects described in
this specification is coded on one or two bytes.

* The value field (V) indicates the value of the data object. If L = '00', the value
field is not present.

A BER-TLV data object belongs to one of the following two categories:

* A primitive data object where the value field contains a data element for
financial transaction interchange.

* A constructed data object where the value field contains one or more primitive
or constructed data objects. The value field of a constructed data object is
called a template.

原创粉丝点击