<?php
function P_SIGN_ENCRYPT($OrderId, $Timestamp,$trtType,$Amount)
{
	$MAC  = '';
	$RSA_KeyPath = 'secure/key.pem';
	$RSA_Key = file_get_contents ($RSA_KeyPath);
	$Data = array (
			'ORDER' => $OrderId,
			'NONCE' => '11111111000000011111',
			'TIMESTAMP' => $Timestamp,
			'TRTYPE' => $trtType,
			'AMOUNT' => $Amount
		);
		
	if (!$RSA_KeyResource = openssl_get_privatekey ($RSA_Key)) die ('Failed get private key');
	$RSA_KeyDetails = openssl_pkey_get_details ($RSA_KeyResource);
	$RSA_KeyLength = $RSA_KeyDetails['bits']/8;
	
	foreach ($Data as $Id => $Filed) $MAC .= strlen ($Filed).$Filed;
	
	$First = '0001';
	$Prefix = '003020300C06082A864886F70D020505000410';
	$MD5_Hash = md5 ($MAC); 
	$Data = $First;
	
	$paddingLength = $RSA_KeyLength - strlen ($MD5_Hash)/2 - strlen ($Prefix)/2 - strlen ($First)/2;
	for ($i = 0; $i < $paddingLength; $i++) $Data .= "FF";
	
	$Data .= $Prefix.$MD5_Hash;
	$BIN = pack ("H*", $Data);
	
	if (!openssl_private_encrypt ($BIN, $EncryptedBIN, $RSA_Key, OPENSSL_NO_PADDING)) 
	{
		while ($msg = openssl_error_string()) echo $msg . "<br />\n";
		die ('Failed encrypt');
	}
	
	$P_SIGN = bin2hex ($EncryptedBIN);
	
	return strtoupper ($P_SIGN);
}

?>