Search code examples
phpsignphp-openssl

DSA algorithm : Sign in PHP


I need to sign a data on my server in php, and verify the signed data on my Java desktop application. My issue is that I don't succeed to generate a key that both languages accept...

My first try was to generate the key with Java KeyPairGenerator, but as shown in that question, I couldn't make openssl to read the key.

Now I generated the keys with openssl like that :

$openssl dsaparam 512 < /dev/random > dsaparam.pem
$openssl gendsa dsaparam.pem -out dsa_priv.pem
$openssl dsa -in dsa_priv.pem -pubout -out dsa_pub.pem

I now try to sign something with this code :

<?php
$data = "test";

$pkeyid = openssl_pkey_get_private("dsa_priv.pem");
echo openssl_sign($data, $signature, $pkeyid);
echo "<br/>";
echo $signature;
?>

Result ?

openssl_sign(): supplied key param cannot be coerced into a private key in ...

What am I doing wrong ? Can anyone help me generate a working DSA key and sign something with it ?


Solution

  • You are missing one important thing here. The openssl_pkey_get_private method takes either key as a string or a file with file:// protocol. The following example works as expected:

    $data = "test";
    
    $pkeyid = openssl_pkey_get_private("file://dsa_priv.pem");
    openssl_sign($data, $signature, $pkeyid);
    echo "\nSignature: " . base64_encode($signature) . "\n";
    

    And produces:

    Signature: MCwCFBpkSESngh+6ooMQZj7i+76t87QmAhQJTfyvvoZ4YFPd722R2qRnXD/Giw==