title: How do I validate the signature of a pdf document with PHP?
body: <p><strong>Background</strong></p>
  
  <p>We allow users to upload a pdf file in our backend system (Laravel/php) containing information about their salary which they download from a website from the dutch goverment agency (UWV Verzekeringsbericht). This document has a digital signature.</p>
  
  <p><strong>Goal</strong></p>
  
  <p>We want to validate and verify this signature, so we know that the user did not change anything from this file and that the file is correct. Kind of how you can validate the certificate in adobe acrobat reader.</p>
  
  <p><strong>Question</strong></p>
  
  <p>I've been trying to accomplish this for the last few hours but because of my limited knowledge/experience I can't seem to get this to work. Any information and/or additional info/tutorials on how to accomplish this would be really appreciated. I'm willing to read about the basics of this but I don't really know where to start.</p>
  
  <p><strong>Code</strong></p>
  
  <p>Oh boy be ready to have a massive brainfart looking at my code. This is the result of not really knowing how things work and searching on stack overflow for solutions and trying them out.</p>
  
  <pre><code>  public function first_attempt(): void
  {
      $path = app_path('/Verzekeringsbericht.pdf');
  
      $content = file_get_contents($path);
  
      $regexp = '#ByteRange\s*\[(\d+) (\d+) (\d+)#'; // subexpressions are used to extract b and c
  
      $result = [];
      preg_match_all($regexp, $content, $result);
  
      // $result[2][0] and $result[3][0] are b and c
      if (isset($result[2]) &amp;&amp; isset($result[3]) &amp;&amp; isset($result[2][0]) &amp;&amp; isset($result[3][0])) {
          $start = $result[2][0];
          $end = $result[3][0];
          if ($stream = fopen($path, 'rb')) {
              $signature = stream_get_contents($stream, $end - $start - 2, $start + 1); // because we need to exclude &lt; and &gt; from start and end
  
              fclose($stream);
          }
  
          file_put_contents('signature.pkcs7', hex2bin($signature));
  
          shell_exec('openssl pkcs7 -in signature.pkcs7 -inform DER -print_certs &gt; cert.pem');
      }
  }
  
  public function second_attempt(): void
      {
          $path = 'file://' . app_path('/qveucag4.pem');
          $authorKey = openssl_pkey_get_public($path);
      }
  
  public function third_attempt(): void
  {
      $pemPath = app_path('/qveucag4.pem');
      $fileCertPath = app_path('/cert.pem');
  
      shell_exec("openssl verify -verbose -CAfile $pemPath $fileCertPath");
  }
  </code></pre>