Continue reading or the gory details ...
openssl genrsa -out key.pem 1024
Second, now that you have an RSA key you'll need to generate the public piece of the key which will be given to your partner (the person/interface you're sending the signed request to so they can validate your signature):
openssl rsa -in key.pem -pubout -outform DER -out pubkey.der
Note that my public key is DER encoded (-outform DER). Normally, you might generate a PEM encoded key, but a DER encoded key is slightly easier to handle in Java. A PEM encoded key is actually a DER encoded key in base64 format with a header. In Java, if you give someone a PEM key, they have to parse out the header and then base64 un-encode the key to get the bytes.
Finally, use PHP to generate a signature that will be used to digitally sign the request. In this example, the data I need to sign is stored in the variable $toSign below. Typically, $toSign might contain a URL of the request, and some type of API key.
<?php
$signature = null;
$toSign = "http://example.com/resources/bogus";
// Read the private key from the file.
$fp = fopen("key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);
// Compute the signature using OPENSSL_ALGO_SHA1
// by default.
openssl_sign($toSign, $signature, $pkeyid);
// Free the key.
openssl_free_key($pkeyid);
// At this point, you've got $signature which
// contains the digital signature as a series of bytes.
// If you need to include the signature on a URL
// for a request to be sent to a REST API, use
// PHP's bin2hex() function.
$hex = bin2hex( $signature );
$toSign .= "/" . $hex;
echo $toSign;
?>
This was tested on RHEL4 U7, with PHP version 4.3.9. I'm sure it will work on PHP 5+, but I haven't tried it. Hope this helps someone else out there.


Did you find this post helpful, or at least, interesting?