Showing posts with label Private Key. Show all posts
Showing posts with label Private Key. Show all posts

Wednesday, May 24, 2017

PHP - Sign Request Data With OpenSSL Private Key Pair

Below is a PHP code snippet to sign request data with OpenSSL private key. It's used to handshake with server to communicate with the server.

function signRequestParams($options)
{
    $private_key = openssl_pkey_get_private(readServerFile("./XeroCerts/privatekey.pem"));
    $sbs = escapeUrlEntity(normalizeParameters($options));
    openssl_sign($sbs, $signature, $private_key);
    openssl_free_key($private_key);
    return base64_encode($signature);
}

function readServerFile($file_path)
{
    $fp = fopen($file_path, "r");
    $file_contents = fread($fp, 8192);
    fclose($fp);
    return $file_contents;
}

function normalizeParameters($parameters)
{
    $elements = array();
    ksort($parameters);
    foreach ($parameters as $paramName => $paramValue) {
        /* If name contains "be_ignored" will be ignored */
        if (preg_match('/be_ignored/', $paramName))
            continue;
        if (is_array($paramValue)) {
            sort($paramValue);
            foreach ($paramValue as $element)
                array_push($elements, escapeUrlEntity($paramName) . '=' . escapeUrlEntity($element));
            continue;
        }
        array_push($elements, escapeUrlEntity($paramName) . '=' . escapeUrlEntity($paramValue));
    }
    return join('&', $elements);
}

function escapeUrlEntity($string)
{
    if ($string === 0)
        return 0;
    if (empty($string))
        return '';
    if (is_array($string))
        throw new Exception('Array passed to escapeUrlEntity');

    $string = rawurlencode($string);
    $string = str_replace('+', '%20', $string);
    $string = str_replace('!', '%21', $string);
    $string = str_replace('*', '%2A', $string);
    $string = str_replace('\'', '%27', $string);
    $string = str_replace('(', '%28', $string);
    $string = str_replace(')', '%29', $string);
    return $string;
}

$options = array(
    "card.PAN" => "4564710000000004",
    "card.CVN" => "847",
    "card.expiryMonth" => "12",
    "card.expiryYear" => "20"
);

$signature = signRequestParams($options);
echo "Signature=$signature";

Output will be as below:

Signature=UC/uRPTaNxMV02a9I/KlWL/BA8..............6Fx1hjEYHWXN0U=