downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

openssl_csr_export_to_file> <openal_stream
[edit] Last updated: Mon, 01 Nov 2010

view this page in

CVIII. OpenSSL

Introduction

Cette extension utilise les fonctions de OpenSSL pour générer et vérifier les signatures, ainsi que pour sceller (chiffrer) et ouvrir (déchiffrer) les données. OpenSSL offre beaucoup de fonctionnalités que ce module n'offre pas actuellement. Quelques-unes pourront être ajoutées dans le futur.

Pré-requis

Afin de pouvoir utiliser les fonctions OpenSSL, vous devez installer les fonctions OpenSSL. PHP depuis les version 4.0.5 et 4.3.1 fonctionnent avec openSSL >= 0.9.5. Les autres versions (PHP <=4.0.4pl1 et >= 4.3.2) nécessitent OpenSSL >= 0.9.6.

Avertissement

Vous êtes vivement encouragé à utiliser la version la plus récente d'OpenSSL afin d'éviter certaines vulnérabilités sur votre serveur web.

Installation

Pour utiliser le support OpenSSL de PHP, vous devez aussi compiler PHP avec l'option de configuration --with-openssl[=DIR].

Note aux utilisateurs Win32 : Afin d'activer ce module dans l'environnement Windows, vous devez copier les bibliothèques libeay32.dll depuis le dossier DLL de PHP/Win32 dans le dossier système SYSTEM32 de votre machine (par exemple : C:\WINNT\SYSTEM32 ou C:\WINDOWS\SYSTEM32).

De plus, si vous envisagez de générer des clés et de signer des messages, vous devez installer un fichier openssl.cnf valide sur votre système. Depuis PHP 4.3.0, une configuration simple est incluse dans le dossier openssl de la distribution Windows. Si vous utilisez PHP PHP 4.2.0 ou plus ancien, et que ces fichiers manquent, vous pouvez les télécharger sur le site d'OpenSSL ou en téléchargeant les fichiers de configuration de PHP 4.3.0.

Note aux utilisateurs Win32 : PHP va rechercher le fichier openssl.cnf suivant la tactique suivante :

  • La variable d'environnement OPENSSL_CONF, si elle est définie, sera utilisée comme chemin (comprenant le fichier) vers le fichier de configuration.

  • La variable d'environnement SSLEAY_CONF, si elle est définie, sera utilisée comme chemin (comprenant le fichier) vers le fichier de configuration.

  • Le fichier openssl.cnf sera supposé se trouver dans le dossier des certificats, tel que configuré lors de la compilation de la bibliothèque openssl. Cela signifie généralement c:\usr\local\ssl\openssl.cnf.

Dans votre installation, vous devrez décider si vous allez installer le fichier dans c:\usr\local\ssl\openssl.cnf ou si vous allez le faire ailleurs et configurer une variable d'environnement (possiblement par site virtuel). Notez qu'il est possible de remplacer le chemin par défaut en utilisant le paramètre configargs des fonctions qui requièrent un fichier de configuration.

Configuration à l'exécution

Cette extension ne définit aucune directive de configuration.

Paramètres clés/certificats

Un bon nombre de fonctions OpenSSL demandent une clé et un certificat comme paramètres. PHP 4.0.5 et plus récent utilisait des clés ou certificats sous forme de ressource, retournée par l'une des fonctions openssl_get_xxx(). Les versions ultérieures utilisent l'une des méthodes suivantes :

  • Certificats

    1. Une ressource X.509 retournée par openssl_x509_read()

    2. Une chaîne au format file://path/to/cert.pem; Le fichier ainsi repéré doit contenir un certificat, encodé au format PEM

    3. Une chaîne contenant le contenu d'un certificat, encodé au format PEM.

  • Clés publiques/privées

    1. Une ressource clé, retournée par la fonction openssl_get_publickey() ou openssl_get_privatekey()

    2. Pour les clés publiques seulement : une ressource X.509

    3. Une chaîne avec le format : file://path/to/file.pem. Le fichier doit contenir une clé privée, ou un certificat, encodé au format PEM (il peut contenir les deux).

    4. Une chaîne contenant une clé ou un certificat encodé au format PEM

    5. Pour les clés privées, vous pouvez aussi utiliser la syntaxe array($key, $passphrase), où $key représente une clé spécifiée par un fichier ou une représentation textuelle comme cité ci-dessus, et $passphrase représente une chaîne contenant la passe-phrase de cette clé privée.

Vérification de certificats

Lorsque vous appelez une fonction qui va vérifier une signature ou un certificat, le paramètre cainfo doit être un tableau contenant les noms d'un dossier et d'un fichier indiquant les tiers de confiance. Si un dossier est spécifié, il doit être correct, car openssl va l'utiliser.

Constantes pré-définies

Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.

Options de validations générales

X509_PURPOSE_SSL_CLIENT (entier)

X509_PURPOSE_SSL_SERVER (entier)

X509_PURPOSE_NS_SSL_SERVER (entier)

X509_PURPOSE_SMIME_SIGN (entier)

X509_PURPOSE_SMIME_ENCRYPT (entier)

X509_PURPOSE_CRL_SIGN (entier)

X509_PURPOSE_ANY (entier)

Options de remplissage (Padding)

OPENSSL_PKCS1_PADDING (entier)

OPENSSL_SSLV23_PADDING (entier)

OPENSSL_NO_PADDING (entier)

OPENSSL_PKCS1_OAEP_PADDING (entier)

Types de clés

OPENSSL_KEYTYPE_RSA (entier)

OPENSSL_KEYTYPE_DSA (entier)

OPENSSL_KEYTYPE_DH (entier)

Constantes/options PKCS7

Les fonctions S/MIME utilisent des options qui sont spécifiées par un champ de bits. Les valeurs valides sont :

Tableau 1. Constantes PKCS7

ConstanteDescription
PKCS7_TEXT Ajoute le texte plein en clair dans les en-têtes du message signé/chiffré. Lors du déchiffrement ou la vérification, il supprime purement et simplement ces données. Si le message chiffré ou signé n'est pas du type MIME, une erreur surviendra.
PKCS7_BINARY Normalement, le message est converti au format canonique qui utilise effectivement des CR et LF comme fin de ligne, comme demandé dans les spécifications de S/MIME. Lorsque cette option est activée, le message ne sera pas converti. Cela sert lorsque vous manipulez des données binaires qui ne sont pas au format MIME.
PKCS7_NOINTERN Lors de la vérification d'un message, les certificats (s'il y en a) inclus dans le message sont normalement utilisés pour rechercher le certificat de signature. Avec cette option, seul le certificat spécifié par le paramètre extracerts de la fonction openssl_pkcs7_verify() est utilisé. Les certificats fournis peuvent toujours être utilisés, avec un niveau de confiance réduit.
PKCS7_NOVERIFY Ne vérifie pas les certificats des signataires d'un message signé.
PKCS7_NOCHAIN N'enchaîne pas les vérifications des signataires de certificats. C'est-à-dire, n'utilise pas les certificats contenu dans le message.
PKCS7_NOCERTS Lors de la signature d'un message, le certificat du signataire est normalement inclus. Avec cette option, c'est désactivé. Cela va réduire la taille du message, mais le vérificateur devra avoir une copie locale du certificat du signataire (passée au paramètre extracerts, avec la fonction openssl_pkcs7_verify()).
PKCS7_NOATTR Normalement, lorsqu'un message est signé, un jeu d'attributs contenant l'heure de signature et l'algorithme symétrique supporté, est inclus dans le message. Avec cette option, il n'est pas inclus.
PKCS7_DETACHED Lors de la signature d'un message, utilise la signature en texte clair, avec le type MIME "multipart/signed". C'est la valeur par défaut du paramètre flags pour la fonction openssl_pkcs7_sign(). Si vous annulez cette option, le message sera signé de manière opaque, ce qui résiste mieux à la traduction des relais emails (certains serveurs mail anciens corrompent les messages), mais empêche la lecture par les client emails qui ne connaissent pas S/MIME.
PKCS7_NOSIGS Ne vérifie pas les signatures d'une message

Note : Ces constantes ont été ajoutées en PHP 4.0.6.

Algorithme de signature

OPENSSL_ALGO_SHA1 (entier)

Utilisé comme algorithme par défaut pour les fonctions openssl_sign() et openssl_verify().

OPENSSL_ALGO_MD5 (entier)

OPENSSL_ALGO_MD4 (entier)

OPENSSL_ALGO_MD2 (entier)

Note : Ces constantes ont été ajoutées depuis PHP 5.0.0.

Table des matières
openssl_csr_export_to_file -- Exporte une CSR vers un fichier
openssl_csr_export -- Exporte un CSR vers un fichier ou une variable
openssl_csr_new -- Génère une CSR
openssl_csr_sign -- Signe un CSR avec un autre certificat
openssl_error_string -- Retourne le message d'erreur OpenSSL
openssl_free_key -- Libère les ressources
openssl_get_privatekey -- Alias de openssl_pkey_get_private()
openssl_get_publickey -- Alias de openssl_pkey_get_public()
openssl_open -- Ouvre des données scellées
openssl_pkcs7_decrypt -- Déchiffre un message S/MIME
openssl_pkcs7_encrypt -- Chiffre un message S/MIME
openssl_pkcs7_sign -- Signe un message S/MIME
openssl_pkcs7_verify -- Vérifie la signature d'un message S/MIME
openssl_pkey_export_to_file -- Sauve une clé au format ASCII dans un fichier
openssl_pkey_export -- Lit une représentation exportable de la clé dans une chaîne ou un fichier
openssl_pkey_free -- Libère une clé privée
openssl_pkey_get_private -- Lit une clé privée
openssl_pkey_get_public -- Extrait une clé privée d'un certificat, et la prépare
openssl_pkey_new -- Génère une nouvelle clé privée
openssl_private_decrypt -- Déchiffre des données avec une clé privée
openssl_private_encrypt -- Chiffre des données avec une clé privée
openssl_public_decrypt -- Déchiffre des données avec une clé publique
openssl_public_encrypt -- Chiffre des données avec une clé publique
openssl_seal -- Scelle des données
openssl_sign -- Signe les données
openssl_verify -- Vérifie une signature
openssl_x509_check_private_key -- Vérifie si une clé privée correspond à un certificat
openssl_x509_checkpurpose -- Vérifie l'usage d'un certificat
openssl_x509_export_to_file -- Exporte un certificat vers un fichier
openssl_x509_export -- Exporte un certificat vers une variable
openssl_x509_free --  Libère les ressources prises par un certificat
openssl_x509_parse -- Analyse un certificat X509
openssl_x509_read --  Analyse un certificat X.509 et retourne une ressource


openssl_csr_export_to_file> <openal_stream
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes OpenSSL
rahuul at yours dot com 23-Mar-2010 11:43
for changing serial no of cert following is the solution:

<?php
$sscert
= openssl_csr_sign($csr, $cacert, $privkey, $days,$config,$serial);
?>
web at mburda dot com 18-Jun-2008 09:45
There is a little problem with Matt Alexander's code below.
Both public and private key are generated internally and saved into OpenSSL class object properties but only private key is then used.
Public key is taken from an external file and if it differs from the one stored internally, OpenSSL fails to decrypt the text.
stephen_at_liberty-irm_dot_com 09-Mar-2008 03:14
This note is primarily aimed at folks storing encrypted things in MySQL as I'm unfamiliar with other database setups. If you store, for example, a credit card number that has been encrypted by openssl_public_encrypt inside of a database, the column type for the column you are storing the number in must be a blob. This is because "the result might contain arbitrary byte values" (MySQL Reference Manual). Basically, if you try to store it in a VARCHAR, LONGTEXT, etc, certain parts of the encrypted data may be dropped, truncated, etc. This will of course make the data impossible to decrypt. Hopefully this will help someone, because it had me stumped for about an hour!
jts 27-Nov-2007 02:07
Win32 users having trouble getting php_openssl to work should make sure that they replace ALL the versions of libeay32.dll and ssleay32.dll, with the ones included with PHP.  This is especially true while using Apache2 and OpenSSL together, as some OpenSSL win32 packages include older versions of these two files.
daevid at daevid dot com 19-Nov-2007 06:04
There doesn't seem to be a function here to test if a cert is valid (i.e. not corrupt)... This bash snippet should help. Sorry it's not PHP. slap it in a system(); call or make it a bash script and call it that way or something...

if [ "`openssl x509 -in /etc/certs/my.crt -noout -modulus`" = "`openssl rsa -in /etc/keys/my.key -noout -modulus`" ]; then echo "Match"; else echo "Different"; fi
kurian at net4ideas dot com 29-Oct-2007 08:01
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.
mattalexx at gmail dot com 29-Aug-2007 02:16
Use this for simple public/private key encryption.

<?php

/**
 * 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/mywebsite.com/docs/key.pem"); // 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 (mattalexx@gmail.com) [based on code by Alex Poole (php@wwwcrm.com)]
 * @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));
     
openssl_free_key($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);
     
openssl_free_key($privatekey);
     
     
// Return value
     
return $plaintext;
   }

   public function
do_csr(
  
$countryName = "UK",
  
$stateOrProvinceName = "London",
  
$localityName = "Blah",
  
$organizationName = "Blah1",
  
$organizationalUnitName = "Blah2",
  
$commonName = "Joe Bloggs",
  
$emailAddress = "openssl@domain.com"
  
) {        
     
$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);
   }
  
}

?>
ChronoFish 16-Aug-2007 11:17
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.

-CF
igor dot gorshkov at gmail dot com 27-Apr-2007 05:31
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" => "temp@temp.com"
);
$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?
dan -AT- NOSPAM danschafer DOT netTT 28-Mar-2007 10:58
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.

<?php
$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;
}
?>
Richard Ablewhite 04-Dec-2006 02:23
Windows users be warned that you need the following file in system32:

msvcr71.dll

It has to go in system32, is not picked up from php/dlls
yabba dabba 26-Jul-2006 11:23
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
peter dot mescalchin @ geemail dot com 16-May-2006 01:34
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:

http://curl.haxx.se/libcurl/php/install.html#windows
php ~at~ wwwcrm dot komm 16-Nov-2005 08:47
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:

http://www.karenandalex.com/php_stuff/_class_OpenSSL.phps

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...

Alex
beckman at purplecow dot com 08-Nov-2005 12:07
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 libcrypto.so.3 to libcrypto.so.4 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.
matt at NOSPAMopenflowsPLEASE dot org 08-Nov-2005 10:42
The openssl functions were disabled in Debian release 3.0 (woody), but as of release 3.1 (sarge) they're available again.
greensweater 31-Aug-2005 04:21
Sorry, the code in my previous note doesn't work... the last line should read:

$csr = openssl_csr_new(array('commonName'=>'MyCSR'),$pkey,$config);
greensweater 30-Aug-2005 09:54
"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);
skippy zuavra net 20-Oct-2004 05:38
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
jaz at ensn dot net 16-Sep-2004 11:18
For newbies (as me):
If you want to try at home on win32, you can learn how to install apache+ssl on this url: http://tud.at/programm/apache-ssl-win32-howto.php3

Versions on English, Spanish and French.

Just I have read and install and run perfectly.
norman at rasmussen dot org 02-Feb-2004 10:43
Debian maintainers have disabled the openssl support because it seems to help break apache on startup.  (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=193343 and http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=165699)

- Norman

 
show source | credits | sitemap | contact | advertising | mirror sites