<?php

if ( !function_exists( 'hex2bin' ) ) {
    function hex2bin( $str ) {
        $sbin = "";
        $len = strlen( $str );
        for ( $i = 0; $i < $len; $i += 2 ) {
            $sbin .= pack( "H*", substr( $str, $i, 2 ) );
                                                }

        return $sbin;
                                                            }
                                                            }

function P_SIGN_DECRYPT($P_SIGN, $ACTION, $RC, $RRN, $ORDER, $AMOUNT)
{
$InData = array (
			'ACTION' => $ACTION,
			'RC' => $RC,
			'RRN' => $RRN,
			'ORDER' => $ORDER ,
			'AMOUNT' => $AMOUNT
		);

foreach($InData as $Id => $Filed) if ($Filed!= '-'  ) : $MAC .= strlen ($Filed).$Filed; else: $MAC .=$Filed; endif;
//$MD5_Hash_In = strtoupper (md5 ($MAC)); 
$MD5_Hash_In = strtoupper (hash('sha256',$MAC));


$P_SIGNBIN = hex2bin ($P_SIGN);

$RSA_KeyPath = 'victoria_pub.pem';
$RSA_Key = file_get_contents ($RSA_KeyPath);
if (!$RSA_KeyResource = openssl_get_publickey($RSA_Key)) die ('Failed get public key');

if (!openssl_public_decrypt ($P_SIGNBIN,$DECRYPTED_BIN,$RSA_Key))
{
		while ($msg = openssl_error_string()) echo $msg . "<br />\n";
		die ('Failed decrypt');
	}

$DECRYPTED = strtoupper( bin2hex ($DECRYPTED_BIN));
$Prefix = '3031300D060960864801650304020105000420';
$DECRYPTED_HASH=str_replace($Prefix,'',$DECRYPTED);
//$DECRYPTED_HASH=str_replace('3031300D060960864801650304020105000420','',$DECRYPTED);

if ($DECRYPTED_HASH==$MD5_Hash_In) {
$RESULT="OK";
} else {
$RESULT="NOK";
}
 
return $RESULT;

}

?>