Java port of MSDN X509 certificate’s usage example

Documentation of X509Certificate2 class in MSDN has example that demostrates how to use it to encrypt and decrypt stream data.

Bytes in a stream are encrypted using AES symmetric algorythm. Secret key is stored in the same output stream and encrypted using X509 certificate’s public key. In order to read original contents of such stream first we need to read and decrypt secret key with certificate’s private key, then decrypt the rest of the stream with that secret key.

I have made a Java port of this example to demonstrate interoperability between two platforms. Files encrypted by C# program from the MSDN example are successfully decrypted by Java code listed below and vice versa.

Also it contains snippets for Java analogue of  BitConverter.GetBytes and BitConverter.ToInt32 methods. So it won’t be a surprise for you that byte type in Java is signed while in C# it is unsigned.

Certificates generated by makecert.exe from Visual Studio use 256-bit key, and you may get InvalidKeyException: Illegal key size. To avoid this you will need to install Unlimited Strength Java(TM) Cryptography Extension (JCE) Policy Files.

Full code with project for Netbeans is available in my github repository.