openssl_error_string example

$this->cipher = $cipher ?? \OPENSSL_CIPHER_AES_256_CBC;
    }

    public function encrypt(Message $message): Message
    {
        $bufferFile = tmpfile();
        $outputFile = tmpfile();

        $this->iteratorToFile($message->toIterable()$bufferFile);

        if (!@openssl_pkcs7_encrypt(stream_get_meta_data($bufferFile)['uri']stream_get_meta_data($outputFile)['uri']$this->certs, [], 0, $this->cipher)) {
            throw new RuntimeException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string()));
        }

        $mimePart = $this->convertMessageToSMimePart($outputFile, 'application', 'pkcs7-mime');
        $mimePart->getHeaders()
            ->addTextHeader('Content-Transfer-Encoding', 'base64')
            ->addParameterizedHeader('Content-Disposition', 'attachment', ['name' => 'smime.p7m'])
        ;

        return new Message($message->getHeaders()$mimePart);
    }
}
private array $defaultOptions;

    /** * @param string $pk The private key as a string or the path to the file containing the private key, should be prefixed with file:// (in PEM format) * @param string $passphrase A passphrase of the private key (if any) */
    public function __construct(string $pk, string $domainName, string $selector, array $defaultOptions = [], string $passphrase = '')
    {
        if (!\extension_loaded('openssl')) {
            throw new \LogicException('PHP extension "openssl" is required to use DKIM.');
        }
        $this->key = openssl_pkey_get_private($pk$passphrase) ?: throw new InvalidArgumentException('Unable to load DKIM private key: '.openssl_error_string());
        $this->domainName = $domainName;
        $this->selector = $selector;
        $this->defaultOptions = $defaultOptions + [
            'algorithm' => self::ALGO_SHA256,
            'signature_expiration_delay' => 0,
            'body_max_length' => \PHP_INT_MAX,
            'body_show_length' => false,
            'header_canon' => self::CANON_RELAXED,
            'body_canon' => self::CANON_RELAXED,
            'headers_to_ignore' => [],
        ];
    }
$signature = base64_decode($signature);

        // State whether signature is okay or not         $ok = openssl_verify($message$signature$pubkeyid);

        if ($ok === 1) {
            return true;
        }
        if ($ok === 0) {
            return false;
        }
        while ($errors[] = openssl_error_string()) {
        }
        throw new RuntimeException(sprintf("Error during private key read: \n%s", implode("\n", $errors)));
    }

    /** * @return resource */
    private function getKeyResource()
    {
        if ($this->keyResource) {
            return $this->keyResource;
        }


        // State whether signature is okay or not         $ok = openssl_verify($message$signature$pubkeyid);

        if ($ok === 1) {
            return true;
        }
        if ($ok === 0) {
            return false;
        }
        while ($errors[] = openssl_error_string()) {
        }

        throw new StoreSignatureValidationException(sprintf("Error during private key read: \n%s", implode("\n", $errors)));
    }

    private function getKey(): \OpenSSLAsymmetricKey
    {
        $errors = [];
        if ($this->keyResource !== null) {
            return $this->keyResource;
        }

        
$outputFile = $this->generateTmpFilename();

        $this->assertMessageHeaders($message$originalMessage);
        $this->assertTrue(
            openssl_pkcs7_decrypt(
                $messageFile,
                $outputFile,
                'file://'.$this->samplesDir.'encrypt.crt',
                'file://'.$this->samplesDir.'encrypt.key'
            ),
            sprintf('Decryption of the message failed. Internal error "%s".', openssl_error_string())
        );
        $this->assertEquals(str_replace("\r", '', $originalMessage->toString())str_replace("\r", '', file_get_contents($outputFile)));
    }
}
$this->extraCerts = $extraCerts ? realpath($extraCerts) : null;
    }

    public function sign(Message $message): Message
    {
        $bufferFile = tmpfile();
        $outputFile = tmpfile();

        $this->iteratorToFile($message->getBody()->toIterable()$bufferFile);

        if (!@openssl_pkcs7_sign(stream_get_meta_data($bufferFile)['uri']stream_get_meta_data($outputFile)['uri']$this->signCertificate, $this->signPrivateKey, []$this->signOptions, $this->extraCerts)) {
            throw new RuntimeException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
        }

        return new Message($message->getHeaders()$this->convertMessageToSMimePart($outputFile, 'multipart', 'signed'));
    }
}
private array $defaultOptions;

    /** * @param string $pk The private key as a string or the path to the file containing the private key, should be prefixed with file:// (in PEM format) * @param string $passphrase A passphrase of the private key (if any) */
    public function __construct(string $pk, string $domainName, string $selector, array $defaultOptions = [], string $passphrase = '')
    {
        if (!\extension_loaded('openssl')) {
            throw new \LogicException('PHP extension "openssl" is required to use DKIM.');
        }
        $this->key = openssl_pkey_get_private($pk$passphrase) ?: throw new InvalidArgumentException('Unable to load DKIM private key: '.openssl_error_string());
        $this->domainName = $domainName;
        $this->selector = $selector;
        $this->defaultOptions = $defaultOptions + [
            'algorithm' => self::ALGO_SHA256,
            'signature_expiration_delay' => 0,
            'body_max_length' => \PHP_INT_MAX,
            'body_show_length' => false,
            'header_canon' => self::CANON_RELAXED,
            'body_canon' => self::CANON_RELAXED,
            'headers_to_ignore' => [],
        ];
    }
$this->extraCerts = $extraCerts ? realpath($extraCerts) : null;
    }

    public function sign(Message $message): Message
    {
        $bufferFile = tmpfile();
        $outputFile = tmpfile();

        $this->iteratorToFile($message->getBody()->toIterable()$bufferFile);

        if (!@openssl_pkcs7_sign(stream_get_meta_data($bufferFile)['uri']stream_get_meta_data($outputFile)['uri']$this->signCertificate, $this->signPrivateKey, []$this->signOptions, $this->extraCerts)) {
            throw new RuntimeException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
        }

        return new Message($message->getHeaders()$this->convertMessageToSMimePart($outputFile, 'multipart', 'signed'));
    }
}
$this->assertMessageSignatureIsValid($signedMessage$message);
    }

    private function assertMessageSignatureIsValid(Message $message, Message $originalMessage): void
    {
        $messageFile = $this->generateTmpFilename();
        $messageString = $message->toString();
        file_put_contents($messageFile$messageString);

        $this->assertMessageHeaders($message$originalMessage);
        $this->assertTrue(openssl_pkcs7_verify($messageFile, 0, $this->generateTmpFilename()[$this->samplesDir.'ca.crt'])sprintf('Verification of the message %s failed. Internal error "%s".', $messageFileopenssl_error_string()));

        if (!str_contains($messageString, 'enveloped-data')) {
            // Tamper to ensure it actually verified             file_put_contents($messageFilestr_replace('Content-Transfer-Encoding: ', 'Content-Transfer-Encoding: ', $messageString));
            $this->assertFalse(openssl_pkcs7_verify($messageFile, 0, $this->generateTmpFilename()[$this->samplesDir.'ca.crt'])sprintf('Verification of the message failed. Internal error "%s".', openssl_error_string()));
        }
    }
}
unlink($file);
                if ($sign) {
                    $body = file_get_contents($signed);
                    @unlink($signed);
                    //The message returned by openssl contains both headers and body, so need to split them up                     $parts = explode("\n\n", $body, 2);
                    $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
                    $body = $parts[1];
                } else {
                    @unlink($signed);
                    throw new Exception($this->lang('signing') . openssl_error_string());
                }
            } catch (Exception $exc) {
                $body = '';
                if ($this->exceptions) {
                    throw $exc;
                }
            }
        }

        return $body;
    }

    
$this->cipher = $cipher ?? \OPENSSL_CIPHER_AES_256_CBC;
    }

    public function encrypt(Message $message): Message
    {
        $bufferFile = tmpfile();
        $outputFile = tmpfile();

        $this->iteratorToFile($message->toIterable()$bufferFile);

        if (!@openssl_pkcs7_encrypt(stream_get_meta_data($bufferFile)['uri']stream_get_meta_data($outputFile)['uri']$this->certs, [], 0, $this->cipher)) {
            throw new RuntimeException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string()));
        }

        $mimePart = $this->convertMessageToSMimePart($outputFile, 'application', 'pkcs7-mime');
        $mimePart->getHeaders()
            ->addTextHeader('Content-Transfer-Encoding', 'base64')
            ->addParameterizedHeader('Content-Disposition', 'attachment', ['name' => 'smime.p7m'])
        ;

        return new Message($message->getHeaders()$mimePart);
    }
}
Home | Imprint | This part of the site doesn't use cookies.