百度百科的 ASN.1 http://baike.baidu.com/view/26378.htm
怎么解析,這里有微軟的解析方法
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字節填充個數) 填充個數字節 數據