This post finishes my epic about the implementation of RSA encryption. See the part I and part II of my post about RSA encryption for C++/Delphi (CryptoAPI) and PHP (OpenSSL) applications.
The main problem we faced was incompatibility of key formats. CryptoAPI uses PRIVATEKEYBLOB and PUBLICKEYBLOB formats to export and import RSA keys while OpenSSL extension for PHP uses PEM format. In order to use both libraries in communicating applications we needed some tool to convert keys from one format to another. The only tool we found for this was OpenSSL 1.0.x beta. Notice that earlier versions of OpenSSL do not support CryptoAPI BLOBs.
Update: It was found later that CryptoAPI has native functions for key conversion. See “Update” section at the bottom of the post.
Below is a command line syntax example for conversion of private key from PEM to PRIVATEKEYBLOB format:
openssl rsa -inform PEM -in private.pem -outform MS\ PRIVATEKEYBLOB -out private.blob
And this example converts PUBLICKEYBLOB to PEM format:
openssl rsa -pubin -inform MS\ PUBLICKEYBLOB -in public.blob -outform PEM -out public.pem
Notice that backslash (\) in format names. You need to type it as it actually escapes the space character.
However, we found some drawbacks in usage of OpenSSL 1.0.x beta:
- There was no Windows build of it available at the time of the post but we wanted to convert keys on Windows.
- We also wanted to convert keys directly in our code w/o any need for external application.
As far as PRIVATEKEYBLOB, PUBLICKEYBLOB and PEM format structures are known, we decided to develop code that will read and write them using low-level functions. It actually took 1-2 days for me to develop that code so I don’t think it’s a really hard task.
Later we faced another problem: PHP versions prior to 5.2 don’t support openssl_pkey_get_details function. Once again, handling key formats directly helped us to resolve the issue by providing a replacement for the function.
So, let me explain how you can implement reading/writing PEM, DER, PRIVATEKEYBLOB and PUBLICKEYBLOB formats with some code examples in PHP for PEM and DER formats and in C++/VCL for CryptoAPI BLOBs. As the task was a part of a commercial project I cannot post a complete working example here. But I will do my best helping you to assemble such code on your own. You can also request our service at Pumka.net.