phpseclib: asn1parse Interpretation Guide

 

asn1parse Interpretation Guide

Let's say you're trying to decode this:

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCunhp5XEEptnE/+jhfdTF1ryjr 
756tUJs26RTKgVa/6isdO+SzTdHRvsOqle8Ze58Y9Qj8goVGkcsxrSHr+nEWcN6O 
oQK+e1Inux5PDwVOE9kiWbjDN4hs41+d6ZgdN6l8h4bhPeAVgQoS2F4a2TKMyLY5 
dyzwj7RK98mLwbfaNwIDAQAB

Here's the ASN.1 decoding you'll get back:

    0:d=0  hl=3 l= 159 cons: SEQUENCE 
    3:d=1  hl=2 l=  13 cons:  SEQUENCE 
    5:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption 
   16:d=2  hl=2 l=   0 prim:   NULL 
   18:d=1  hl=3 l= 141 prim:  BIT STRING

Great. So you have an RSA public key. But what is contained within BIT STRING?

To figure that out let's first explain the format of the output.

Consider this line:

   18:d=1  hl=3 l= 141 prim:  BIT STRING

18 is the offset from the beginning, d=1 is the depth and hl=3 is the header length.

Here's how you can isolate the BIT STRING:

<?php 
$data = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCunhp5XEEptnE/+jhfdTF1ryjr 
756tUJs26RTKgVa/6isdO+SzTdHRvsOqle8Ze58Y9Qj8goVGkcsxrSHr+nEWcN6O 
oQK+e1Inux5PDwVOE9kiWbjDN4hs41+d6ZgdN6l8h4bhPeAVgQoS2F4a2TKMyLY5 
dyzwj7RK98mLwbfaNwIDAQAB'; 
$data = preg_replace('#\s#', '', $data); 
$data = base64_decode($data); 
$data = substr($data, 18+3+1, 141); 
$data = base64_encode($data); 
echo $data;

That'll get you this:

    0:d=0  hl=3 l= 137 cons: SEQUENCE 
    3:d=1  hl=3 l= 129 prim:  INTEGER           :AE9E1A795C4129B6713FFA385F753175AF28EBEF9EAD509B36E914CA8156BFEA2B1D3BE4B34DD1D1BEC3AA95EF197B9F18F508FC82854691CB31AD21EBFA711670DE8EA102BE7B5227BB1E4F0F054E13D92259B8C337886CE35F9DE9981D37A97C8786E13DE015810A12D85E1AD9328CC8B639772CF08FB44AF7C98BC1B7DA37
  135:d=1  hl=2 l=   3 prim:  INTEGER           :010001

ie. you have to go one (1) past the offset from the beginning (18) and the headerlength (3).