Octet string 解析

百度百科的 ASN.1 http://baike.baidu.com/view/26378.htm

什么是 octet string 结构化字节

怎么解析,这里有微软的解析方法

If the byte array contains fewer than 128 bytes, the Length field of the TLV triplet requires only one byte to specify the content length. If it is more than 127 bytes, bit 7 of the Length field is set to 1 and bits 6 through 0 specify the number of additional bytes used to identify the content length. This is shown in the following example where the high order bit of the second byte on the first line is set to 1 and the byte indicates that there is a trailing Length byte. The third byte therefore specifies that the content is 0x80 bytes long.

以上就是解析,字节是代表什么意思

例如

字符串字节数小于128的时候:

04 0a                              ; OCTET_STRING (a Bytes)
|     1e 08 00 55 00 73 00 65  00 72  ;   ...U.s.e.r

解析

04 代表 OCTET_STRING 这个结构(参看基本类型汇总表)

0a 代表 字节的数量(a Bytes)

字符串字节数大于127的时候:

04 81 80                       ; OCTET_STRING (80 Bytes)

解析

04 仍然是 代表 OCTET_STRING 这个结构

81 代表 后面的计数有多少字节 0x81-0x80 = 0x01 这就代表1个字节(注意:这里的0x80不是上面字节串内的80,是字符串字节数大于127的时候,128计算出来的80)

所以后面的1个字节  80 就是字节长度了。

例如:

04 82 03 aa        ; OCTET_STRING (3aa Bytes)

04 代表 OCTET_STRING 这个结构

82 代表 后面的计数有多少字节 0x82-0x80 = 0x02 这就代表2个字节

所以后面跟着的两个字节组合 就是字符串长度 03aa 代表 938个字节

下面是解析代码: 

std::string OctetToString(const char * src_in,int size)
 {
     if(src_in[0] == 0x04)
     {
         if((int)src_in[1] <128)
         {
             return string(src_in+2,src_in[1]);
         }
         else
         {
             int count_len = (int)src_in[2]-0x80;
             int content_len = 0;            
             for(int i = 0;i<count_len;i++)
             {
                 count_len =count_len<<8+ (int)src_in[2+i];
             }

             return (content_len > size? "":string(src_in+3,content_len));
        }
     }
     return "";
 } 

基本类型汇总表

类型

UNIVERSALTag

取值

BOOLEAN

1

TRUE,FALSE

NULL

5

NULL

INTEGER

2

整数

ENUMERATED

10

类型定义中列出的成员

REAL

9

实数

BIT STRING

3

比特串

OCTET STRING

4

八位组串,字节流

OBJECTIDENTIFIER

6

 

RELATIVE-OID

13

 

解释:位串:{1,0,0,0,1,1,1,0,1,0,0,1},第一字节10001110=0x8E;第二字节:1001需填充,填充后得到10010000=0x90,因为填充了4个0,得到表示填充数的一个字节0x04

则完整编码为:0x03               03                                               04              8E   90

       BIT STRING结构  数据长度 (2字节数据+1字节填充个数)     填充个数字节           数据 

原文地址:https://www.cnblogs.com/HappyEDay/p/5504377.html