当前位置:C++技术网 > 资讯 > Octet string 解析

Octet string 解析

更新时间:2015-06-27 17:46:12浏览次数:1+次

因为发现百度竟然查不到 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个字节

所以后面的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 "";
 } 


by 顺铭 ooklasd