Search code examples
phpencryptionpublic-key-encryptionprivate-keyphp-openssl

How do I use an already given private key as a private key resource in PHP?


I am working on integrating the Walmart API. They require a digital signature with each API call. My code seems to be working up until I have to deal with the private key. Here is my function to generate a digital signature:

//Most of this code is from a Walmart API sample
function _GetWalmartAuthSignature($URL, $RequestMethod, $TimeStamp, $ConsumerId) {
    $WalmartPrivateKey = {given PEM formatted string};
    //Construct the authentication data we need to sign
    $AuthData = $ConsumerId."\n";
    $AuthData .= $URL."\n";
    $AuthData .= $RequestMethod."\n";
    $AuthData .= $TimeStamp."\n";

//THIS METHOD IS RETURNING FALSE!!!!
$PrivateKey = openssl_pkey_get_private($WalmartPrivateKey);

//Sign the data using sha256 hash
defined("OPENSSL_ALGO_SHA256") ? $Hash = OPENSSL_ALGO_SHA256 : $Hash = "sha256";
if (!openssl_sign($AuthData, $Signature, $privKey, $Hash)) {
    return null;
}

//Encode the signature and return
return base64_encode($Signature);

}

The openssl_pkey_get_private() func keeps returning false. So then my openssl_sign() func gives me the error: openssl_sign(): supplied key param cannot be coerced into a private key

I tried first creating a new key resource, using

$res = openssl_pkey_new(); 
openssl_pkey_export($res, $privKey);

and then saving my $WalmartPrivateKey to $privKey, but I got the same error. I tried using openssl_get_private_key(), but again- nothing worked.

I only know the very basics of public/private key encryption, and this is my first time using these functions.

Can anyone help me out?


Solution

  • I had a similar issue, and it was because the PEM format was wrong. Make sure you have the correct beginning and ending markers: "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----". Both markers must have exactly 5 dashes before and after the words, and the words must be all caps. Good luck!