Sunday, 18 January 2009

RSA in C# and Java

Following up on the previous post, follows an implementation of RSA in C# and Java.

First the Java version that generates a public key:

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
BigInteger publicExponent =rsaPublicKey.getPublicExponent();
BigInteger modulus = rsaPublicKey.getModulus();

with the public exponent and the modulus, you can export this key in an xml file or stream that will be used by the C# client to read the public key.

The C# part:

var rsaCryptoServiceProvider = new RSACryptoServiceProvider();
const string keyfileName = "PKI2.xml";
var streamReader = new StreamReader(@"C:\TEMP\RSAJavaPubKey.xml");

string publicKey = streamReader.ReadToEnd();

Now what?

Let's say you are using Rendez-Vous as a protocol and you are looking for a way to cipher messages between the client and the server. the Java server can generate a public key on start-up, initiate a handshake with the C# (or Java client). The client generates a symmetric key for DES-3 or AES, the client then encrypts the symmetric key with the server's public key, sends it to the server which deciphers the symmetric key, and then you have your SSL-like protocol on top of RV.

This obviously does not solve the man in the middle attack.

No comments:

Blog Archive