Due to lack of example the following code may be useful to some.
# Demo code for openssl_pkcs7_sign() and openssl_pkcs7_encrypt() to sign and encrypt for Paypal EWP.
#
# generate and self sign certificat
# % openssl genrsa -out my-private-key.pem 2048
# % openssl req -new -key my-private-key.pem -x509 -days 3650 -out my-public-key.pem
#
function demo_paypal_encrypt( $webform_hash )
{
$MY_PUBLIC_KEY = "file:///usr/local/etc/paypal/my-public-key.pem";
$MY_PRIVATE_KEY = "file:///usr/local/etc/paypal/my-private-key.pem";
$PAYPAL_PUBLIC_KEY = "file:///usr/local/etc/paypal/paypal_cert_pem.txt";
//Assign Build Notation for PayPal Support
$webform_hash['bn']= 'MyWebRef.PHP_EWP2';
$data = "";
foreach ($webform_hash as $key => $value)
if ($value != "")
$data .= "$key=$value\n";
$file_msg = sprintf( "/tmp/pp-msg-%d.txt", getmypid() );
$file_sign = sprintf( "/tmp/pp-sign-%d.mpem", getmypid() );
$file_bsign = sprintf( "/tmp/pp-sign-%d.der", getmypid() );
$file_enc = sprintf( "/tmp/pp-enc-%d.txt", getmypid() );
if ( file_exists( $file_msg ) ) unlink( $file_msg );
if ( file_exists( $file_sign ) ) unlink( $file_sign );
if ( file_exists( $file_bsign ) ) unlink( $file_bsign );
if ( file_exists( $file_enc ) ) unlink( $file_enc );
$fp = fopen( $file_msg, "w" );
if ( $fp ) {
fwrite($fp, $data );
fclose($fp);
}
// sign part of html form message
openssl_pkcs7_sign(
$file_msg,
$file_sign,
$MY_PUBLIC_KEY,
array( $MY_PRIVATE_KEY, "" ), /// private key, password
array(),
PKCS7_BINARY
);
// convert PEM to DER
$pem_data = file_get_contents( $file_sign );
$begin = "Content-Transfer-Encoding: base64";
$pem_data = trim( substr($pem_data, strpos($pem_data, $begin)+strlen($begin)) );
$der = base64_decode( $pem_data );
$fp = fopen( $file_bsign, "w" );
if ( $fp ) {
fwrite($fp, $der );
fclose($fp);
}
// you could verify correct DER signature by:
// % openssl smime -verify -CAfile $MY_PUBLIC_KEY -inform DER -in $file_bsign
//encrypt the message, with Paypal public key
openssl_pkcs7_encrypt(
$file_bsign,
$file_enc,
$PAYPAL_PUBLIC_KEY,
array(),
PKCS7_BINARY,
OPENSSL_CIPHER_3DES );
$data = file_get_contents( $file_enc );
$data = substr($data, strpos($data, $begin)+strlen($begin));
$data = "-----BEGIN PKCS7-----\n". trim( $data ) . "\n-----END PKCS7-----";
// cleanup
if ( file_exists( $file_msg ) ) unlink( $file_msg );
if ( file_exists( $file_sign ) ) unlink( $file_sign );
if ( file_exists( $file_bsign ) ) unlink( $file_bsign );
if ( file_exists( $file_enc ) ) unlink( $file_enc );
return( $data );
}