S
S
Sergey Fedotov2016-06-27 12:01:18
OpenSSL
Sergey Fedotov, 2016-06-27 12:01:18

PHP: How to hide private key file from web server (openssl_pkcs7_sign)?

I'm trying to implement interaction with the ESIA. Everything seems to be working fine, but it's annoying that the interaction takes place with the private key file available to the web server.
There is a suspicion that OpenSSL has its own private key store, especially since it can use hardware keys for encryption where the private key is not programmatically available at all.
Is it possible to hide the private key from the web server?
For example, the implementation of the function for signing PKCS7:

private function signPKCS7($message) {
      $this->checkFilesExists();
      $certContent = file_get_contents($this->certPath);
      $keyContent = file_get_contents($this->privateKeyPath);
      $cert = openssl_x509_read($certContent);
      if ($cert === false) {
          throw new Exception('Ошибка чтения сертификата '.$this->certPath);
      }
      #$this->writeLog('Cert: ' . print_r($cert, true));
      $privateKey = openssl_pkey_get_private($keyContent, $this->privateKeyPassword);
      if ($privateKey === false) {
          throw new Exception('Ошибка чтения приватного ключа '.$this->privateKeyPath);
      }
      $messageFile=TMP_PATH.DIRECTORY_SEPARATOR.uniqid();
      $signFile=TMP_PATH.DIRECTORY_SEPARATOR.uniqid();
      try {
        file_put_contents($messageFile, $message);
        $signResult = openssl_pkcs7_sign(
            $messageFile,
            $signFile,
            $cert,
            $privateKey,
            []
        );
        if (!$signResult) {
          throw new SignFailException('SSH error: ' . openssl_error_string());
        }
        $signed = file_get_contents($signFile);
        $signed = explode("\n\n", $signed);
        $sign = str_replace("\n", "", $this->urlSafe($signed[3]));
      } finally {
        unlink($signFile);
        unlink($messageFile);        
      }
      return $sign;
    }

$this->certPath - path to the certificate
$this->privateKeyPath - path to the private key (you have to give the full path to the file) $
this->privateKeyPassword - private key password
with a key.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question