How does this code extract a signature?

I need to debug an old PHP script from a developer who left the company. I understand most of the code except for the following function. My question is: what does ...

if ($ seq == 0x03 || $ seq == 0x30)

... means in the context of extracting a signature from an X.509 certificate?

public function extractSignature($certPemString) {

    $bin = $this->ConvertPemToBinary($certPemString);

    if(empty($certPemString) || empty($bin))
    {
        return false;
    }    

    $bin = substr($bin,4);

    while(strlen($bin) > 1) 
    {            
        $seq = ord($bin[0]); 
        if($seq == 0x03 || $seq == 0x30) 
        {            
            $len = ord($bin[1]);
            $bytes = 0;

            if ($len & 0x80)
            {
                $bytes = ($len & 0x0f);
                $len = 0;
                for ($i = 0; $i < $bytes; $i++)
                {
                    $len = ($len << 8) | ord($bin[$i + 2]);
                }
            }

            if($seq == 0x03)
            {
                return substr($bin,3 + $bytes, $len);
            }
            else 
            {
                $bin = substr($bin,2 + $bytes + $len);                  
            }                                                    
        }
        else 
        {                            
            return false;                
        }
    }
    return false;
}
+2
source share
5 answers

An X.509 certificate contains data from several sections (called triple Tag-Length-Value tags). Each section begins with a tag byte, which indicates the format of the section data. You can see a list of these data types here .

0x03 - BIT STRING 0x30 SEQUENCE.

, BIT STRING SEQUENCE. :

if($seq == 0x03)
{
    return substr($bin,3 + $bytes, $len);
}
else // $seq == 0x30
{
    $bin = substr($bin,2 + $bytes + $len);                  
}

, (0x30), - (0x03), .

, , 3 - 2 . , - , , . (, 13 , 2 = 16 , " " 3.)

: . 128 , ( 0). 128 , 7, 7 , ( ). . :

$len = ord($bin[1]);
$bytes = 0;

if ($len & 0x80)
{
    // length is greater than 127!
    $bytes = ($len & 0x0f);
    $len = 0;
    for ($i = 0; $i < $bytes; $i++)
    {
         $len = ($len << 8) | ord($bin[$i + 2]);
    }
}

$bytes , , $len Value ( ).

? ,

128 , 7 set, 7 , .

$bytes = ($len & 0x0f), 4 ! :

$bytes = ($len & 0x7f);

, : , 0x0f = 15 , 256 ^ 15 . , .

+5

, , , $seq 0x30 0x03.

, , , , . $seq - , , , , , , ( " , 10:45 - RFC" ).

0x30 0x03. ( , 0x), 16. , . :

0 = 0000
1 = 0001
2 = 0010
3 = 0011
...
...
E = 1110
F = 1111

, if($seq == 3 || $seq == 48), .

+2

, 3 x.509. . RFC 1422, p7. -.

+2

ord () gets the value of the ASCII character you pass. In this case, it checks if the ASCII character is either 0 or the end of the text (according to this ASCII table ).

+1
source

0x03 and 0x30 are hexadecimal values. Look at this and you will have what $ seq matches

-1
source

All Articles