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

search for in the

openssl_csr_export_to_file> <openal_stream
Last updated: Sat, 24 Mar 2007

view this page in

CXI. OpenSSL funkce

Úvod

Toto rozšíření využívá funkce » OpenSSL pro tvorbu a ověřování podpisů a pečetění (kódování) a otvírání (dekódování) dat. OpenSSL nabízí mnoho vlastností, které tato extenze v současnosti nepodporuje. Některé z nich mohou být v budoucnu přidány.

Požadavky

Abyste mohli používat tyto funkce, musíte nainstalovat » OpenSSL. PHP-4.0.4pl1 potřebuje OpenSSL >= 0.9.6, ale PHP-4.0.5 a vyšší budou pracovat i s OpenSSL >= 0.9.5.

Instalace

Abyste v PHP mohli používat funkce OpenSSL, musíte PHP zkompilovat s volbou --with-openssl[=DIR].

Poznámka pro uživatele Win32: Aby toto rozšíření fungovalo ve Windows, musíte zkopírovat soubor libeay32.dll z adresáře DLL Win32 distribuce do adresáře SYSTEM32. (Např.: C:\WINNT\SYSTEM32 nebo C:\WINDOWS\SYSTEM32)

Navíc, pokud máte v úmyslu používat funkce generování klíčů a podepisování certifikátů, musíte na váš systém nainstalovat platný openssl.cnf. Do PHP 4.3.0 jsme připojili ukázkový konfigurační soubor do adresáře openssl Win32 distribuce. Pokud používáte 4.2.0 nebo novější a tento soubor vám chybí, můžete ho stáhnout z » domácí stránky OpenSSL nebo stáhněte PHP 4.3.0 a použijte konfigurační souboru z něj.

PHP bude hledat openssl.cnf tímto postupem:

  • Proměnná prostředí OPENSSL_CONF, pokud je nastavena, bude použita jako cesta (včetně názvu souboru) konfiguračního souboru.
  • Proměnná prostředí SSLEAY_CONF, pokud je nastavena, bude použita jako cesta (včetně názvu souboru) konfiguračního souboru.
  • Bude se předpokládat, že soubor openssl.cnf bude nalezen ve výchozí oblasti certifikátů, která byla zkonfigurována při kompilaci DLL knihovny openssl. To obvykle znamená, že výchozí název souboru je c:\usr\local\ssl\openssl.cnf.

Ve své instalaci se musíte rozhodnout, zda nainstalujete konfigurační soubor do c:\usr\local\ssl\openssl.cnf nebo zda ho nainstalujete někam jinam a pro nalezení konfiguračního souboru použijete proměnnou prostředí (pravděpodpobně jako per-virtual-host). Vemte na vědomí, že výchozí cestu lze změnit v parametru configargs funkcí, které potřebují konfigurační soubor.

Konfigurace běhu

Toto rozšíření nemá definováno žádné konfigurační direktivy.

Typy prostředků

Parametry s klíči/certifikáty

Několik openssl funkcí potřebuje parametr s klíčem nebo certifikátem. PHP 4.0.5 a starší musí pro klíč a certifikát používat resource vrácený některou z funkcí openssl_get_xxx. Pozdější verzi mohou používat libovolnou z těchto metod:

  • Certifikáty

    1. X.509 zdroj vrácený funkcí openssl_x509_read()
    2. Řetězec ve formátu file://path/to/cert.pem; uvedený soubor musí obsahovat PEM-zakódovaný certifikát
    3. Řetězec obsahující PEM-zakódovaný certifikát

  • Veřejné a soukromé klíče

    1. Zdroj klíče vrácený funkcí openssl_get_publickey() nebo openssl_get_privatekey()
    2. Pouze veřejné klíče: zdroj X.509
    3. Řetězec ve formátu file://path/to/file.pem - uvedený soubor musí obsahovat PEM-zakódovaný certifikát / veřejný klíč (může obsahovat oba)
    4. Řetězec obsahující obsah certifikátu / klíče, PEM-zakódovaný
    5. Pro soukromé klíče lze také použít syntaxi array($key, $heslo) kde $key reprezentuje klíč zadaný pomocí file:// nebo textového uvedení zmíněného výše a $heslo reprezentuje řetězec obsahující heslo pro tento soukromý klíč

Ověření certifikátu

Když voláte funkci, která ověřuje podpis / certifikát, parametr cainfo je pole obsahující názvy souborů a adresářů, které určují umístění souborů důvěryhodných CA. Pokud je zadán adresář, musí to být správně uspořádaný adresář s hashi tak, jak ho používá příkaz openssl.

Předdefinované konstanty

Tyto konstanty jsou definovány tímto rozšířením a budou k dispozici pouze tehdy, bylo-li rozšíření zkompilováno společně s PHP nebo dynamicky zavedeno za běhu.

Přepínače ověření účelu

X509_PURPOSE_SSL_CLIENT (integer)
X509_PURPOSE_SSL_SERVER (integer)
X509_PURPOSE_NS_SSL_SERVER (integer)
X509_PURPOSE_SMIME_SIGN (integer)
X509_PURPOSE_SMIME_ENCRYPT (integer)
X509_PURPOSE_CRL_SIGN (integer)
X509_PURPOSE_ANY (integer)

Přepínače vycpávky

OPENSSL_PKCS1_PADDING (integer)
OPENSSL_SSLV23_PADDING (integer)
OPENSSL_NO_PADDING (integer)
OPENSSL_PKCS1_OAEP_PADDING (integer)

Typy klíčů

OPENSSL_KEYTYPE_RSA (integer)
OPENSSL_KEYTYPE_DSA (integer)
OPENSSL_KEYTYPE_DH (integer)

Přepínače / konstanty PKCS7

S/MIME funkce používají přepínače, kterou jsou specifikovány jako bitové pole, které může obsahovat jednu nebo více následujících hodnot:

Tabulka 208. PKCS7 konstanty

KonstantaPopis
PKCS7_TEXTpřidá "text/plain content type" hlavičky k zakódovaným/podepsaným zprávám. Při dekódování nebo ověřování odstraní tyto hlavičky z výstupu - když není rozkódovaná nebo ověřená zpráva MIME typu text/plain, dojde k chybě.
PKCS7_BINARYza normálních okolností je zdrojová zpráva převedená do "kanonického" formátu, který používá pro konce řádků používá CR a LF: tak, jak to požaduje S/MIME specifikace. Když je zapnuta tato volba, nedojde k žádnému převodu. To se hodí v případě manipulace s binárními daty, která nemusí být v MIME formátu.
PKCS7_NOINTERNpři ověřování zprávy jsou za normálních okolností certifikáty obsažené ve zprávě (pokud nějaké existují) prohledávané na výskyt podpisového certifikátu. S touto volbou se použijí pouze certifikáty zadané v parametru extracerts funkce openssl_pkcs7_verify(). Zadané certifikáty ale stále mohou být použity jako nedůvěryhodné CA.
PKCS7_NOVERIFYneověřovat certifikát podepisovatele podepsané zprávy.
PKCS7_NOCHAINnespojovat ověření podepisovatelových certifikátů: to znamená nepoužívat certifikáty v podepsané zprávě jako nedůvěryhodné CA.
PKCS7_NOCERTSpři podepisování zprávy je za normálních okolností připojen certifikát podepisovatele - s touto volbou tomu tak není. To způsobí snížení velikosti podepsané zprávy, ale ověřovatel musí mít kopii podepisovatelova certifikátu k dispozici lokálně (například předanou v parametru extracerts funkce openssl_pkcs7_verify()).
PKCS7_NOATTRPokud je zpráva podepsána za normálních okolností, je připojena sada atributů obsahující čas podpisu a podporované symetrické algoritmy. S touto volbou není připojena.
PKCS7_DETACHEDPři podpisu zprávy použije podpis čitelného text spolu s MIME typem multipart/signed. To je výchozí nastavení, pokud ve funkci openssl_pkcs7_sign() nezadáte parametr flags. Pokud tuto volbu vypnete, bude zpráva podepsána za použití neprůhledného podepsání, které je více odolné vůči překladům e-mailových bran, ale nelze přečíst klienty, kteří nepodporují S/MIME.
PKCS7_NOSIGSNezkoušet a neověřovat podpisy zprávy

Poznámka: Tyto konstanty byly přidány ve verzi 4.0.6.

Obsah

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 — Uvolnit prostředky klíče
openssl_get_privatekey — Připravit soukromý PEM klíč k použití
openssl_get_publickey — Získat z certifikátu veřejný klíč a připravit ho k použití
openssl_open — Otevřít zapečetěná data
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 (bits, pkey, type)
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 — Zapečetit (zakódovat) data
openssl_sign — Generate signature
openssl_verify — Ověřit podpis
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


openssl_csr_export_to_file> <openal_stream
Last updated: Sat, 24 Mar 2007
 
add a note add a note User Contributed Notes
OpenSSL funkce
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 11: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

openssl_csr_export_to_file> <openal_stream
Last updated: Sat, 24 Mar 2007
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites