Thursday, November 6, 2008

.NET and PHP Encryption

For a project I'm currently researching at work, we are going to be doing some encrypted communication with a third-party.  Normally, if both companies were using .NET, that would be simple; however, this company uses PHP on Linux, which complicates things a bit.

I talked with their developer, and he was planning on using the PHP functions openssl_public_encrypt() and openssl_private_decrypt() for the encryption and decryption. I did some research, and found this page that described the .NET equivalents. That got me started, but the next problem was that he sent his public key in PEM format, which looks like this:
-----BEGIN PUBLIC KEY-----
(base-64 encoded data here)
-----END PUBLIC KEY-----
From what I could gather, .NET can't read this format, at least not with the built-in classes. I did more research and found this tool which converts between PEM and .NET (and other) formats. When run on the PEM-format public key, this generates a file that looks like this:

<rsakeyvalue>
<modulus>(base-64 encoded data)</modulus>
<exponent>(data)</exponent>
</rsakeyvalue>

This is directly usable by the .NET class RSACryptoServiceProvider using the FromXmlString() method. The same tool can be used to convert the private key to an Xml file, which can be read in using the same class and method.  Once the keys are read in, you can use the Encrypt() and Decrypt() methods on your data.