for changing serial no of cert following is the solution:
<?php
$sscert = openssl_csr_sign($csr, $cacert, $privkey, $days,$config,$serial);
?>
CX. OpenSSL Funktionen
Einführung
Dieses Modul nutzt die Funktionen von » OpenSSL zur Erzeugung und Überprüfung von Signaturen und zum versiegeln (verschlüsseln) und öffnen (entschlüsseln) von Daten. OpenSSL bietet viele Möglichkeiten die dieses Modul zum jetzigen Zeitpunkt nicht unterstützt. Einige dieser Möglichkeiten werden vielleicht in zukünftigen Versionen zur Verfügung stehen.
Anforderungen
Bevor Sie die Openssl-Funktionen nutzen können, müssen Sie das » OpenSSL Paket installieren. PHP zwischen 4.0.5 und 4.3.1 funktionieren mit OpenSSL >= 0.9.5. Andere Versionen (PHP <=4.0.4pl1 and >= 4.3.2) setzen OpenSSL >= 0.9.6 voraus.
| Warnung |
| Es wird dringnd empfohlen die aktuellste OpenSSL Version zu verwenden, anderenfalls könnte Ihr Webserver anfällig für Attacken sein. |
Installation
Um Openssl mit PHP nutzen zu können, müssen Sie PHP mit der Option --with-openssl[=DIR] übersetzen.
Hinnweis für Win32 Benutzer: Um dieses Modul unter Windows benutzen zu können, müssen Sie die Datei libeay32.dll vom DLL Ordner Ihrer PHP/Win32 Binärdistribution in den SYSTEM32 Ordner von Windows kopieren.(Zum Beispiel nach: C:\WINNT\SYSTEM32 oder C:\WINDOWS\SYSTEM32).
Wenn Sie vorhaben, Schlüssel erzeugende und Zertifikats signierende Funktionen zu benutzen, müssen Sie eine gültige Konfigurationsdatei für OpenSSL, openssl.cnf, installieren. Ab PHP 4.3.0 finden Sie bei der win32 Binärdistribution im Ordner openssl eine Beispielkonfigurationsdatei, die Sie benutzen können. Falls Sie PHP 4.2.0 oder eine höhere Version benutzen und diese Datei in Ihrer Distribution fehlt, finden Sie diese Datei auf der » OpenSSL Homepage, oder Sie laden sich PHP 4.3.0 herunter und verwenden die in diesem Paket enthaltene Datei.
PHP verwendet folgende Logik um die Konfigurationsdatei openssl.cnf zu finden:
- Die Umgebungsvariable OPENSSL_CONF wird, falls gesetzt, als Pfad zur Konfigurationsdatei benutzt (den Dateinamen mit eingeschlossen).
- Die Umgebungsvariable SSLEAY_CONF wird, falls gesetzt, als Pfad zur Konfigurationsdatei benutzt (den Dateinamen mit eingeschlossen).
- PHP sucht die Datei openssl.cnf an dem Ort, der bei der Kompilierung der openssl DLL als Speicherort für Zertifikate angegeben wurde. Üblicherweise ist der Standarddateiname c:\usr\local\ssl\openssl.cnf.
Damit diese Datei gefunden wird, müsssen Sie sich bei der Installation entscheiden, entweder die Konfigurationsdatei unter c:\usr\local\ssl\openssl.cnf anzulegen, oder diese Datei an einem anderen Ort abzulegen und Umgebungsvariablen zu benutzen (möglicherweise auf Basis verschiedener Virtual-Host Konfigurationen). Bei Funktionen, die diese Konfigurationsdatei benötigen, ist es möglich, durch die Angabe des Parameters configargs den Standardpfad zu dieser Datei in einem Skript zu überschreiben.
Laufzeit Konfiguration
Diese Erweiterung definiert keine Konfigurationseinstellungen in der php.ini.
Resource Typen
Schlüssel/Zertifikat Parameter
Ziemlich viele der OpenSSL Funktionen benötigen einen Schlüssel- oder einen Zertifikatparameter. PHP 4.0.5 und frühere Versionen müssen eine Schlüssel- oder Zertifikatsresource nutzen, die von einer der openssl_get_xxx Funktionen zurückgegeben wird. Spätere Versionen können eine der folgenden Methoden benutzen:
Zertifikate
- Eine X.509 Resource die von openssl_x509_read zurückgegeben wird.
- Eine Zeichenkette mit dem Format file://pfad/zu/cert.pem; die angegebene Datei muss ein PEM verschlüsseltes Zertifikat enthalten.
- Eine Zeichenkette die den Inhalt eines Zertifikats enthält, PEM verschlüsselt.
Öffentliche/Private Schlüssel
- Eine Schlüsselresource die von openssl_get_publickey() oder openssl_get_privatekey() zurückgegeben wird.
- Nur für öffentliche Schlüssel: eine X.509 Resource.
- Eine Zeichenkette mit dem Format file://pfad/zu/datei.pem - die angegebene Datei muss ein PEM verschlüsseltes Zertifikat/privaten Schlüssel enthalten (kann auch beides enthalten).
- Eine Zeichenkette die den Inhalt eines Zertifikats/Schlüssels enthält, PEM verschlüsselt.
- Für private Schlüssel können Sie auch die Syntax array($key, $passphrase) verwenden. $key repräsentiert einen Schlüssel, den Sie entweder mit der Notation file:// oder dem textlichen Inhalt wie oben angeben. $passphrase ist eine Zeichenfolge, die die Passphrase für den privaten Schlüssel enthält.
Zertifikat Nachweis
Wenn Sie eine Funktion aufrufen, die eine Signatur/ein Zertifikat überprüft, ist der Parameter cainfo ein Array, das Datei- und Verzeichnisnamen enthält, die auf vertrauenswürdige CA Dateien verweisen. Falls Sie ein Verzeichnis angeben, muss dies ein korrekt geformtes gehashdes Verzeichnis sein, in der Art, wie es der Befehl openssl verwenden würde.
Vordefinierte Konstanten
Folgende Konstanten werden von dieser Erweiterung definiert und stehen nur zur Verfügung, wenn die Erweiterung entweder statisch in PHP kompiliert oder dynamisch zur Laufzeit geladen wurde.
Die S/MIME Funktionen nutzen Flags die sich dadurch auszeichnen, dass sie ein Bitfeld benutzen, das einen oder mehrere der folgenden Werte enthalten kann:
Tabelle 192. PKCS7 KONSTANTEN
| Konstante | Beschreibung |
|---|---|
| PKCS7_TEXT | Fügt den Inhaltstyp Header text/plain einer verschlüsselten/signierten Nachricht hinzu. Wenn Sie entschlüsseln oder überprüfen, werden diese Header von der Ausgabe entfernt. Entspricht die entschlüsselte oder geprüfte Nachricht nicht dem MIME Typ text/plain, tritt ein Fehler auf. |
| PKCS7_BINARY | Normalerweise wird die Nachricht in ein "kanonisches" Format konvertiert, das effektiv CR und LF als Zeilende benutzt, wie von der S/MIME Spezifikation gefordert. Wird diese Option angegeben, findet keine Konvertierung statt. Das kann sich als nützlich erweisen, wenn Sie es mit binären Daten zu tun haben, die nicht dem MIME Format entprechen. |
| PKCS7_NOINTERN | Wenn Sie eine Nachricht überprüfen, werden in der Nachricht enthaltene Zertifikate (falls es welche gibt) nach dem unterzeichnenden Zertifikat durchsucht. Mit dieser Option werden nur Zertifikate benutzt, die mit dem Parameter extracerts in der Funktion openssl_pkcs7_verify() angegeben wurden. Die mitgelieferten Zertifikate können aber dennoch als nicht vertrauenswürdige CAs benutzt werden. |
| PKCS7_NOVERIFY | Keine Überprüfung des signierenden Zertifikats einer signierten Nachricht. |
| PKCS7_NOCHAIN | Keine Verknüpfung der Überprüfung des Zertifikats mit den Zertifikaten des Unterzeichners: das bedeutet, die Zertifikate in der signierten Nachricht werden nicht als nicht vertrauenswürdige CAs benutzt. |
| PKCS7_NOCERTS | Beim Signieren einer Nachricht wird normalerweise das Zertifikat des Unterzeichnenden mit in die Nachricht aufgenommen - mit dieser Option wird das Zertifikat nicht mit aufgenommen. Diese Option verringert die Größe der signierten Nachricht, aber der Überprüfende muss eine lokale Kopie des Zertifikats vom Unterzeichnenden besitzen (zum Beispiel durch Angabe des Parameters extracerts in der Funktion openssl_pkcs7_verify()). |
| PKCS7_NOATTR | Beim Signieren einer Nachricht wird normalerweise eine Reihe von Attributen mit angehängt. Diese enthalten die Zeit der Signierung und die unterstützen symmetrischen Algorithmen. Mit dieser Option werden diese Attribute nicht mit aufgenommen. |
| PKCS7_DETACHED | Beim Signieren einer Nachricht wird Klartext-Signierung verwendet mit dem MIME Typ multipart/signed. Das ist der Standard, wenn Sie keinen optionalen Parameter flags an die Funktion openssl_pkcs7_sign() übergeben. Wenn Sie diese Option ausschalten wird die Nachricht mit einer undurchsichtigen Signatur unterzeichnet. Dieses Verhalten ist robuster gegenüber der Übersetzung durch Mail-Relays, kann aber nicht mit Mailprogrammen gelesen werden, die nicht den S/Mime Standard unterstützen. |
| PKCS7_NOSIGS | Kein Versuch und keine Überprüfung der Signaturen einer Nachricht. |
Anmerkung: Diese Konstanten wurden in 4.0.6 hinzugefügt.
- OPENSSL_ALGO_SHA1 (integer)
- Wird als Standard-Algorithmus für die Funktionen openssl_sign() und openssl_verify() verwendet.
- OPENSSL_ALGO_MD5 (integer)
- OPENSSL_ALGO_MD4 (integer)
- OPENSSL_ALGO_MD2 (integer)
Anmerkung: Diese Konstanten wurden in 5.0.0 hinzugefügt.
Anmerkung: Diese Konstanten wurden in 4.3.0 hinzugefügt.
Anmerkung: Diese Konstanten wurden in 5.2.0 hinzugefügt.
Inhaltsverzeichnis
- openssl_csr_export_to_file — Exportiert ein CSR in eine Datei
- openssl_csr_export — Exportiert einen CSR als Zeichenkette
- 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 — Erzeugt einen CSR
- openssl_csr_sign — Signiert einen CSR mit einem anderen Zertifikat (oder sich selbst) und generiert ein Zertifikat
- openssl_error_string — Liefert eine OpenSSL Fehlermeldung
- openssl_free_key — Freigabe einer Schlüsselressource
- openssl_get_privatekey — Liefert einen privaten Schlüssel
- openssl_get_publickey — Extrahiert einen öffentlichen Schlüssel aus einem Zertifikat und bereitet ihn für den Gebrauch vor
- openssl_open — Öffnet versiegelte Daten
- openssl_pkcs7_decrypt — Entschlüssen einer S/MIME verschlüsselten Nachricht
- openssl_pkcs7_encrypt — Verschlüsseln einer S/MIME Nachricht
- openssl_pkcs7_sign — Signieren einer S/MIME Nachricht
- openssl_pkcs7_verify — Überprüft die Unterschrift einer mit S/MIME unterschriebenen Nachricht
- openssl_pkey_export_to_file — Liefert eine exportierbare Representation eines Schlüssels in einer Datei
- openssl_pkey_export — Liefert eine exportierbare Representation eines Schlüssels in einem 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 — Liefert einen privaten Schlüssel
- openssl_pkey_get_public — Extrahiert einen öffentlichen Schlüssel aus einem Zertifikat und bereitet diesen zur Nutzung vor
- openssl_pkey_new — Erzeugt einen neuen privaten Schlüssel
- openssl_private_decrypt — Entschlüsselt Daten mit einem privaten Schlüssel
- openssl_private_encrypt — Verschlüsselt Daten mit einem privaten Schlüssel
- openssl_public_decrypt — Entschlüsselt Daten mit einem öffentlichen Schlüssel
- openssl_public_encrypt — Verschlüsselt Daten mit einem öffentlichen Schlüssel
- openssl_seal — Verschlüsselt (versiegelt) Daten
- openssl_sign — Erzeugen einer Unterschrift
- openssl_verify — Überprüft eine Unterschrift
- openssl_x509_check_private_key — Überprüft, ob ein privater Schlüssel zu einem Zertifikat passt
- openssl_x509_checkpurpose — Überprüft ob ein Zertifikat für einen bestimmten Zweck benutzt werden kann
- openssl_x509_export_to_file — Exportiert ein Zertifikat in eine Datei
- openssl_x509_export — Exportiert ein Zertifikat in eine Zeichenkette
- openssl_x509_free — Freigabe einer Zertifikats Resource
- openssl_x509_parse — Analyse eines X509 Zertifikats und Rückgabe der Information in einem Array
- openssl_x509_read — Analysiert ein X.509 Zertitifikat und gibt eine Ressource-Kennung zurück
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.
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!
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.
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
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.
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);
}
}
?>
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
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?
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;
}
?>
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
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
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
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
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.
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);
"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);
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
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.
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
