php的openssl sign,PHP: openssl_pkcs7_sign - Manual

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 );

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值