Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : OpenSSL Functions

OpenSSL Functions


This module uses the functions of » OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.


In order to use the OpenSSL functions you need to install the » OpenSSL package. PHP between versions 4.0.5 and 4.3.1 will work with OpenSSL >= 0.9.5. Other versions (PHP <=4.0.4 and >= 4.3.2) require OpenSSL >= 0.9.6.


You are strongly encouraged to use the most recent OpenSSL version, otherwise your web server could be vulnerable to attack.


To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR].

Note to Win32 Users:

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the systems PATH), it is not recommended. This extension requires the following files to be in the PATH: libeay32.dll

Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf on your system. As of PHP 4.3.0, we include a sample configuration file in the openssl folder of our win32 binary distribution. If you are using PHP 4.2.0 or later and are missing the file, you can obtain it from » the OpenSSL home page or by downloading the PHP 4.3.0 release and using the configuration file from there.

PHP will search for the openssl.cnf using the following logic:

  • the OPENSSL_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
  • the SSLEAY_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
  • The file openssl.cnf will be assumed to be found in the default certificate area, as configured at the time that the openssl DLL was compiled. This is usually means that the default filename is c:\usr\local\ssl\openssl.cnf.

In your installation, you need to decide whether to install the configuration file at c:\usr\local\ssl\openssl.cnf or whether to install it someplace else and use environmental variables (possibly on a per-virtual-host basis) to locate the configuration file. Note that it is possible to override the default path from the script using the configargs of the functions that require a configuration file.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:

  • Certificates

    1. An X.509 resource returned from openssl_x509_read()
    2. A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate
    3. A string containing the content of a certificate, PEM encoded
  • Public/Private Keys

    1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
    2. For public keys only: an X.509 resource
    3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)
    4. A string containing the content of a certificate/key, PEM encoded
    5. For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key

Certificate Verification

When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Purpose checking flags

X509_PURPOSE_CRL_SIGN (integer)
X509_PURPOSE_ANY (integer)

Padding flags


Key types


PKCS7 Flags/Constants

The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:


Constant Description
PKCS7_TEXT Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur.
PKCS7_BINARY Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format.
PKCS7_NOINTERN When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however.
PKCS7_NOVERIFY Do not verify the signers certificate of a signed message.
PKCS7_NOCHAIN Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTS When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example).
PKCS7_NOATTR Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included.
PKCS7_DETACHED When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if you do not specify any flags to openssl_pkcs7_sign(). If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME.
PKCS7_NOSIGS Don't try and verify the signatures on a message


These constants were added in 4.0.6.

Signature Algorithms

Used as default algorithm by openssl_sign() and openssl_verify().
OPENSSL_ALGO_MD5 (integer)
OPENSSL_ALGO_MD4 (integer)
OPENSSL_ALGO_MD2 (integer)

These constants were added in 5.0.0.


OPENSSL_CIPHER_RC2_40 (integer)
OPENSSL_CIPHER_RC2_128 (integer)
OPENSSL_CIPHER_RC2_64 (integer)

These constants were added in 4.3.0.

Version constants


These constants were added in 5.2.0.

Table of Contents

openssl_csr_export_to_file — Exports a CSR to a file
openssl_csr_export — Exports a CSR as a string
openssl_csr_get_public_key — Returns the public key of a CERT
openssl_csr_get_subject — Returns the subject of a CERT
openssl_csr_new — Generates a CSR
openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate
openssl_error_string — Return openSSL error message
openssl_free_key — Free key resource
openssl_get_privatekey — Alias of openssl_pkey_get_private()
openssl_get_publickey — Alias of openssl_pkey_get_public()
openssl_open — Open sealed data
openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.
openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message
openssl_pkcs7_encrypt — Encrypt an S/MIME message
openssl_pkcs7_sign — Sign an S/MIME message
openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message
openssl_pkey_export_to_file — Gets an exportable representation of a key into a file
openssl_pkey_export — Gets an exportable representation of a key into a string
openssl_pkey_free — Frees a private key
openssl_pkey_get_details — Returns an array with the key details
openssl_pkey_get_private — Get a private key
openssl_pkey_get_public — Extract public key from certificate and prepare it for use
openssl_pkey_new — Generates a new private key
openssl_private_decrypt — Decrypts data with private key
openssl_private_encrypt — Encrypts data with private key
openssl_public_decrypt — Decrypts data with public key
openssl_public_encrypt — Encrypts data with public key
openssl_seal — Seal (encrypt) data
openssl_sign — Generate signature
openssl_verify — Verify signature
openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
openssl_x509_export_to_file — Exports a certificate to file
openssl_x509_export — Exports a certificate as a string
openssl_x509_free — Free certificate resource
openssl_x509_parse — Parse an X509 certificate and return the information as an array
openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it

Code Examples / Notes » ref.openssl

richard ablewhite

Windows users be warned that you need the following file in system32:
It has to go in system32, is not picked up from php/dlls


Use this for simple public/private key encryption.
* Point to your config file
define("OPEN_SSL_CONF_PATH", "/usr/share/ssl/openssl.cnf");
* Length of time certificate is valid (in days)
define("OPEN_SSL_CERT_DAYS_VALID", 365);
* Passphrase required with private key
define("OPEN_SSL_PASSPHRASE", "lkdfjbjeyrasdfvkajwdeblsolkdkdjfbvzslalsmdbfvksb");
* Enter description here...
define("OPEN_SSL_PUBKEY_PATH", "/docs/domains/"); // Public key path
* A wrapper class for a simple subset of the PHP OpenSSL functions. Use for public key encryption jobs.
* <code>
* // To configure
* // 1. Set OPEN_SSL_CONF_PATH to the path of your openssl.cnf file.
* // 2. Set OPEN_SSL_PASSPHRASE to any passphrase.
* // 3. Use the OpenSSL::do_csr method to generate your private and public keys (see next section).
* // 4. Save the private key somewhere offline and save your public key somewhere on this machine.
* // 5. Set OPEN_SSL_PUBKEY_PATH to the public key's path.
* // To generate keys
* $ossl = new OpenSSL;
* $ossl->do_csr();
* $privatekey = $ossl->privatekey;
* $publickey = $ossl->publickey;
* unset($ossl);
* // Encrypt
* $text = "Secret text";
* $ossl = new OpenSSL;
* $ossl->encrypt($text);
* $encrypted_text = $ossl->crypttext;
* $ekey = $ossl->ekey;
* unset($ossl);
* // Decrypt
* $ossl = new OpenSSL;
* $decrypted_text = $ossl->decrypt($encrypted_text, $privatekey, $ekey);
* unset($ossl);
* @author Matt Alexander ( [based on code by Alex Poole (]
* @copyright 2007
class OpenSSL {
  public $privatekey;
  public $publickey;
  public $csr;
  public $crypttext;
  public $ekey;
  public function encrypt($plain) {
     // Turn public key into resource
     $publickey = openssl_get_publickey(is_file(OPEN_SSL_PUBKEY_PATH)? file_get_contents(OPEN_SSL_PUBKEY_PATH) : OPEN_SSL_PUBKEY_PATH);
     // Encrypt
     openssl_seal($plain, $crypttext, $ekey, array($publickey));
     // Set values
     $this->crypttext = $crypttext;
     $this->ekey = $ekey[0];

  public function decrypt($crypt, $privatekey, $ekey="") {
     // Turn private key into resource
     $privatekey = openssl_get_privatekey((is_file($privatekey)? file_get_contents($privatekey) : $privatekey), OPEN_SSL_PASSPHRASE);
     // Decrypt
     openssl_open($crypt, $plaintext, $ekey, $privatekey);
     // Return value
     return $plaintext;
  public function do_csr(
  $countryName = "UK",
  $stateOrProvinceName = "London",
  $localityName = "Blah",
  $organizationName = "Blah1",
  $organizationalUnitName = "Blah2",
  $commonName = "Joe Bloggs",
  $emailAddress = ""
  ) {        
     $dn = array(
        "countryName" => $countryName,
        "stateOrProvinceName" => $stateOrProvinceName,
        "localityName" => $localityName,
        "organizationName" => $organizationName,
        "organizationalUnitName" => $organizationalUnitName,
        "commonName" => $commonName,
        "emailAddress" => $emailAddress
     $config = array(
        "config" => OPEN_SSL_CONF_PATH
     $privkey = openssl_pkey_new();
     $csr = openssl_csr_new($dn, $privkey, $config);
     $sscert = openssl_csr_sign($csr, null, $privkey, OPEN_SSL_CERT_DAYS_VALID, $config);
     openssl_x509_export($sscert, $this->publickey);
     openssl_pkey_export($privkey, $this->privatekey, OPEN_SSL_PASSPHRASE, $config);
     openssl_csr_export($csr, $this->csr);


There is a note below regarding the need to copy BOTH ssleay32.dll AND libeay32.dll to a folder in the system PATH on Win32 systems.
That is absolutely true.  It should be noted also that Windows will search the Windows system directories before it will search the PATH.  If you have existing .dlls in these directories - rename (rather than deleting in case you need to undo your changes) them and copy over the latest version of these files.
Key locations may include the /i386, /windows/system32, and ~/apache/.../modules directories.
I also updated my ~/subversion/bin directory.

yabba dabba

The php4 distribution for Windows/IIS has a README-SSL.txt which strongly implies that just the path needs to be added to the OPENSLL_CONF variable in the server's environment variables. Be sure to add the file name and extension too.
E.g.: c:\php-4.3.11\openssl\openssl.cnf


The openssl functions were disabled in Debian release 3.0 (woody), but as of release 3.1 (sarge) they're available again.


Sorry, the code in my previous note doesn't work... the last line should read:
$csr = openssl_csr_new(array('commonName'=>'MyCSR'),$pkey,$config);

skippy zuavra net

In case you're wondering what's a "correctly hashed" directory for the use with cainfo: it's simply a directory which contains CA public certificates in PEM/X.509 format. You can get such certificates either from the CA's website (they advertise it in visible places) or from your browser. In Explorer for instance you can click on the little yellow padlock, go to the CA entry and export it.
The only trick with the directory is that file names must be in the form "hash.#". The "hash" part is the 8-digit hex hash of the certificate, while the # part is a number which serves to differentiate certificates which give the same hash (yes, it can happen with certificates coming from the same CA). Usually # is 0, but you also can use 1, 2 and so on when having more certs with the same hash.
In order to obtain the hash of a certificate you can use the openssl command line utility like this:
openssl x509 -hash -in certfile.cer | head -1

php ~at~ wwwcrm dot komm

If you want to use PHP for public / private key encryption jobs without needing to know the ins and outs of the Open SSL extension, the following may be of interest:
This class was unavailable for a long while (server problems) but is now back up. Apologies to those who clicked through and got a 404
I hope it is useful to you...

igor dot gorshkov

I generate certificates in such a way.
$config = array("config" => "d:/sslcert/openssl.cnf");
$dn = array(
  "countryName" => "RU",
  "stateOrProvinceName" => "Russia",
  "localityName" => "Saint-Petersburg",
  "organizationName" => "temp",
  "organizationalUnitName" => "temp",
  "commonName" => "temp",
  "emailAddress" => ""
$privkey_enc = openssl_pkey_new($config);
$csr = openssl_csr_new($dn, $privkey_enc, $config);
$sscert = openssl_csr_sign($csr, null, $privkey_enc, 365);
openssl_x509_export_to_file($sscert, "d:/cert_enc.crt");
openssl_pkey_export_to_file($privkey_enc, "d:/privkey_enc.pem");
As a result all the received certificates have identical serial number (00). But it should not be! How to avoid it?


FreeBSD Ports tree php5-openssl uses openssl-0.9.8a.  This is a problem, as if you install these two ports and attempt to open an HTTPS URL within PHP, it will fail with this error from openssl_error_string(): error:140A90A1:SSL routines:func(169):reason(161) which is SSL_R_LIBRARY_HAS_NO_CIPHERS or "library has no ciphers"
This is because the openssl library now requires you to load your ciphers manually -- all ciphers are not automatically loaded for you.
I don't believe the php5-openssl module has been updated to do this before opening an SSL connection (as of 5.0.5).
Using openssl-0.9.7i seems to work; symlinking to prevents the php5-openssl port from trying to install openssl-0.9.8a.  So install openssl-stable (0.9.7i) from ports first, symlink 2nd, then install php5-openssl 3rd, and you should be OK.


For working of openssl in windows platform IIS webserver, we need to enable in php.ini, tne copy libeay32.dll and ssleay32.dll to the php folder (or windows's system32 folder) and add both dll's path to the window's PATH variable. It seems to be working for me after I did these changes.

peter dot mescalchin @ geemail dot com

For w32 users to enable OpenSSL support. As well as copying "libeay32.dll" to the windows system32 folder you also need to copy "ssleay32.dll".  The documentation above should probably be updated to note this.
This requirement was documented at the libcurl pages:


For newbies (as me):
If you want to try at home on win32, you can learn how to install apache+ssl on this url:
Versions on English, Spanish and French.
Just I have read and install and run perfectly.


Debian maintainers have disabled the openssl support because it seems to help break apache on startup.  ( and
- Norman

dan -at- nospam danschafer dot nettt

Currently, all OpenSSL Functions defined in PHP only utilize the PEM format.  Use the following code to convert from DER to PEM and PEM to DER.
$pem_data = file_get_contents($cert_path.$pem_file);
$pem2der = pem2der($pem_data);
$der_data = file_get_contents($cert_path.$der_file);
$der2pem = der2pem($der_data);
function pem2der($pem_data) {
  $begin = "CERTIFICATE-----";
  $end   = "-----END";
  $pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));
  $pem_data = substr($pem_data, 0, strpos($pem_data, $end));
  $der = base64_decode($pem_data);
  return $der;
function der2pem($der_data) {
  $pem = chunk_split(base64_encode($der_data), 64, "\n");
  $pem = "-----BEGIN CERTIFICATE-----\n".$pem."-----END CERTIFICATE-----\n";
  return $pem;


"You need to have a valid openssl.cnf installed for this function to operate correctly" includes most openssl functions. You can force php to find your openssl.cnf file as follows:
$config = array('config'=>'/path/to/openssl.cnf');
$pkey = openssl_pkey_new($config);
$csr = openssl_csr_new('MyCSR',$pkey,$config);

Change Language

Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Haru PDF Functions
hash Functions
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker