Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openssl_verify(): supplied key param cannot be coerced into a public key for a .pem file

Tags:

php

openssl

Currently attempting to read a .pem public key to verify it through openssl.

/**
 * Check whether the signed message sent back by the server is
 * correct or not.
 */
function check($str, $MAC)
{
    $fp = fopen(
        dirname(__FILE__) . '/rsa_public_key.pem',
        'r'
    );

    $cert = fread($fp, 8192);

    fclose($fp);

    $pubkeyid = openssl_get_publickey($cert);

    return openssl_verify($str, $MAC, $pubkeyid);
}

With that said, upon executing my script, I receive this error:

openssl_verify(): supplied key param cannot be coerced into a public key in some/path at line X

Originally, I wrote this function to accept .cer certifications. Here's an explanation of the difference between all these different key formats. To my understanding .pem are similar to .cer, however, I could not for the life of me figure out how to allow my script to read my .pem file.

My question is - what do I need to do in order for my function to read this public key?

EDIT: Upon some Googling, I have tried using file_get_contents() to a particular path but I would receive the same error.

What could be causing this error?

like image 288
theGreenCabbage Avatar asked Oct 16 '14 14:10

theGreenCabbage


2 Answers

Upon opening this .pem file, it was all in one line. It appears each line requires the length of 64 characters, so I made sure each line was 64 lines, and it successfully parsed. Had nothing to do with .cer.

like image 128
theGreenCabbage Avatar answered Oct 05 '22 12:10

theGreenCabbage


In addition, the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- lines should contain exactly five dashes on each side. No more, no less. Six is right out.

There may or may not be a newline at the end of the final line.

Windows line endings (CR/LF) are allowed, even on *nix-hosted PHP.

like image 32
Seva Alekseyev Avatar answered Oct 05 '22 11:10

Seva Alekseyev