OpenSSL functions OpenSSL Introduction This module uses the functions of OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. PHP-4.0.4pl1 requires OpenSSL >= 0.9.6, but PHP-4.0.5 and greater with also work with OpenSSL >= 0.9.5. Please keep in mind that this extension is still considered experimental! OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future. 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 An X.509 resource returned from openssl_x509_read A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate A string containing the content of a certificate, PEM encoded Public/Private Keys A key resource returned from openssl_get_publickey or openssl_get_privatekey For public keys only: an X.509 resource 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) A string containing the content of a certificate/key, PEM encoded 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 the 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. 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: PKCS7 CONSTANTS 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 the flags parameter to openssl_pkcs7_sign if you do not specify any flags. 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.
openssl_error_string Return openSSL error message Description mixed openssl_error_string void Returns an error message string, or false if there are no more error messages to return. openssl_error_string returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information. The parameters/return type of this function may change before it appears in a release version of PHP <function>openssl_error_string</function> example // lets assume you just called an openssl function that failed while($msg = openssl_error_string) echo $msg . "<br>"; This function was added in 4.0.6. openssl_free_key Free key resource Description void openssl_free_key resource key_identifier openssl_free_key frees the key associated with the specified key_identifier from memory. openssl_get_privatekey Prepare a PEM formatted private key for use Description resource openssl_get_privatekey mixed key string passphrase Returns a positive key resource identifier on success, or false on error. openssl_get_privatekey parses the PEM formatted private key specified by key and prepares it for use by other functions. The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase). openssl_get_publickey Extract public key from certificate and prepare it for use Description resource openssl_get_publickey mixed certificate Returns a positive key resource identifier on success, or false on error. openssl_get_publickey extracts the public key from an X.509 certificate specified by certificate and prepares it for use by other functions. openssl_open Open sealed data Description bool openssl_open string sealed_data string open_data string env_key mixed priv_key_id Returns true on success, or false on error. If successful the opened data is returned in open_data. openssl_open opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal for more information. <function>openssl_open</function> example // $sealed and $env_key are assumed to contain the sealed data // and our envelope key, both given to us by the sealer. // fetch private key from file and ready it $fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r"); $priv_key = fread($fp, 8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); // decrypt the data and store it in $open if (openssl_open($sealed, $open, $env_key, $pkeyid)) echo "here is the opened data: ", $open; else echo "failed to open data"; // free the private key from memory openssl_free_key($pkeyid); See also openssl_seal. openssl_seal Seal (encrypt) data Description int openssl_seal string data string sealed_data array env_keys array pub_key_ids Returns the length of the sealed data on success, or false on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys. openssl_seal seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key. <function>openssl_seal</function> example // $data is assumed to contain the data to be sealed // fetch public keys for our recipients, and ready them $fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r"); $cert = fread($fp, 8192); fclose($fp); $pk1 = openssl_get_publickey($cert); // Repeat for second recipient $fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r"); $cert = fread($fp, 8192); fclose($fp); $pk2 = openssl_get_publickey($cert); // seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys // $ekeys[0] and $ekeys[1] respectively. openssl_seal($data, $sealed, $ekeys, array($pk1,$pk2)); // free the keys from memory openssl_free_key($pk1); openssl_free_key($pk2); See also openssl_open. openssl_sign Generate signature Description bool openssl_sign string data string signature mixed priv_key_id Returns true on success, or false on failure. If successful the signature is returned in signature. openssl_sign computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted. <function>openssl_sign</function> example // $data is assumed to contain the data to be signed // fetch private key from file and ready it $fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r"); $priv_key = fread($fp, 8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); // compute signature openssl_sign($data, $signature, $pkeyid); // free the key from memory openssl_free_key($pkeyid); See also openssl_verify. openssl_verify Verify signature Description int openssl_verify string data string signature mixed pub_key_id Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error. openssl_verify verifies that the signature is correct for the specified data using the public key associated with pub_key_id. This must be the public key corresponding to the private key used for signing. <function>openssl_verify</function> example // $data and $signature are assumed to contain the data and the signature // fetch public key from certificate and ready it $fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r"); $cert = fread($fp, 8192); fclose($fp); $pubkeyid = openssl_get_publickey($cert); // state whether signature is okay or not $ok = openssl_verify($data, $signature, $pubkeyid); if ($ok == 1) echo "good"; elseif ($ok == 0) echo "bad"; else echo "ugly, error checking signature"; // free the key from memory openssl_free_key($pubkeyid); See also openssl_sign. openssl_pkcs7_decrypt Decrypts an S/MIME encrypted message Description bool openssl_pkcs7_decrypt string infilename string outfilename mixed recipcert mixed recipkey Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and it's associated private key specified by recipcert and recipkey. The decrypted message is output to the file specified by outfilename <function>openssl_pkcs7_decrypt</function> example // $cert and $key are assumed to contain your personal certificate and private // key pair, and that you are the recipient of an S/MIME message $infilename = "encrypted.msg"; // this file holds your encrypted message $outfilename = "decrypted.msg"; // make sure you can write to this file if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key)) echo "decrypted!"; else echo "failed to decrypt!"; This function was added in 4.0.6. openssl_pkcs7_encrypt Encrypt an S/MIME message Description bool openssl_pkcs7_encrypt string infilename string outfilename mixed recipcerts array headers long flags openssl_pkcs7_encrypt takes the contents of the file named infilename and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts, which is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that will be prepended to the data after it has been encrypted. flags can be used to specify options that affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line. <function>openssl_pkcs7_encrypt</function> example // the message you want to encrypt and send to your secret agent // in the field, known as nighthawk. You have his certificate // in the file nighthawk.pem $data = <<<EOD Nighthawk, Top secret, for your eyes only! The enemy is closing in! Meet me at the cafe at 8.30am to collect your forged passport! HQ EOD; // save message to file $fp = fopen("msg.txt", "w"); fwrite($fp, $data); fclose($fp); // encrypt it if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", "nighthawk.pem", array("To" => "nighthawk@agent.com", // keyed syntax "From: HQ <hq@cia.com>", // indexed syntax "Subject" => "Eyes only"))) { // message encrypted - send it! exec(ini_get("sendmail_path") . " < enc.txt"); } This function was added in 4.0.6. openssl_pkcs7_sign sign an S/MIME message Description bool openssl_pkcs7_sign string infilename string outfilename mixed signcert mixed privkey array headers long flags string extracertsfilename openssl_pkcs7_sign takes the contents of the file named infilename and signs them using the certificate and it's matching private key specified by signcert and privkey parameters. headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt for more information about the format of this parameter. flags can be used to alter the output - see PKCS7 constants - if not specified, it defaults to PKCS7_DETACHED. extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used. <function>openssl_pkcs7_sign</function> example // the message you want to sign so that recipient can be sure it was you that // sent it $data = <<<EOD You have my authorization to spend $10,000 on dinner expenses. The CEO EOD; // save message to file $fp = fopen("msg.txt", "w"); fwrite($fp, $data); fclose($fp); // encrypt it if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem", array("mycert.pem", "mypassphrase"), array("To" => "joes@sales.com", // keyed syntax "From: HQ <ceo@sales.com>", // indexed syntax "Subject" => "Eyes only")) { // message signed - send it! exec(ini_get("sendmail_path") . " < signed.txt"); } This function was added in 4.0.6. openssl_pkcs7_verify Verifies the signature of an S/MIME signed message Description bool openssl_pkcs7_verify string filename int flags string outfilename array cainfo string extracerts openssl_pkcs7_verify reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns true if the signature is verified, false if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error. flags can be used to affect how the signature is verified - see PKCS7 constants for more information. If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format. If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter. If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs. This function was added in 4.0.6. openssl_x509_checkpurpose Verifies if a certificate can be used for a particular purpose Description bool openssl_x509_checkpurpose mixed x509cert int purpose array cainfo string untrustedfile Returns true if the certificate can be used for the intended purpose, false if it cannot, or -1 on error. openssl_x509_checkpurpose examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose. cainfo should be an array of trusted CA files/dirs as described in Certificate Verification. untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file. <function>openssl_x509_checkpurpose</function> purposes Constant Description X509_PURPOSE_SSL_CLIENT Can the certificate be used for the client side of an SSL connection? X509_PURPOSE_SSL_SERVER Can the certificate be used for the server side of an SSL connection? X509_PURPOSE_NS_SSL_SERVER Can the cert be used for Netscape SSL server? X509_PURPOSE_SMIME_SIGN Can the cert be used to sign S/MIME email? X509_PURPOSE_SMIME_ENCRYPT Can the cert be used to encrypt S/MIME email? X509_PURPOSE_CRL_SIGN Can the cert be used to sign a certificate revocation list (CRL)? X509_PURPOSE_ANY Can the cert be used for Any/All purposes?
These options are not bitfields - you may specify one only!
This function was added in 4.0.6.
openssl_x509_free Free certificate resource Description void openssl_x509_free resource x509cert openssl_x509_free frees the certificate associated with the specified x509cert resource from memory. This function was added in 4.0.6. openssl_x509_parse Parse an X509 certificate and return the information as an array Description array openssl_x509_parse mixed x509cert bool shortnames openssl_x509_parse returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc. shortnames controls how the data is indexed in the array - if shortnames is true (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName. The structure of the returned data is (deliberately) not yet documented, as it is still subject to change. This function was added in 4.0.6. openssl_x509_read Parse an X.509 certificate and return a resource identifier for it Description resource openssl_x509_read mixed x509certdata openssl_x509_read parses the certificate supplied by x509certdata and returns a resource identifier for it. This function was added in 4.0.6.