Wednesday, November 3, 2010

RSACryptoServiceProvider (.NET C#)

Long ago I wrote a file server that provided encrypted passwords at login. To encrypt the passwords I used RSACryptoServiceProvider. It is a reasonably simple way to generate a public and private key so you can encrypt information and pass it back and forth. The code below passes a new public key (RSAParameters) to the client in the form of an XML serialized object. The code missing in this example is the actual Socket interaction back and forth. The server side also has an RSA.Decrypt call later used to check the validity of the sent password.


   1:  // Server Side
   2:  RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
   3:  RSAParameters zParams = RSA.ExportParameters(false); // false avoids exporting the private key!
   4:  MemoryStream zStream = new MemoryStream();
   5:  XmlSerializer zXSerial  = new XmlSerializer(zParams.GetType());
   6:  zXSerial.Serialize(zStream, zParams);
   7:  // send public key to client
   8:  ...
   9:  // decrypt and check password
  10:   
  11:   
  12:  // Client Side
  13:  RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
  14:  RSAParameters zParams = new RSAParameters();
  15:  XmlSerializer zXSerial = new XmlSerializer(zParams.GetType());
  16:  MemoryStream zStream = new MemoryStream(arrayPostHeader);
  17:  zStream.Seek(0, SeekOrigin.Begin);
  18:  zParams = (RSAParameters)zXSerial.Deserialize(zStream);
  19:  RSA.ImportParameters(zParams);
  20:  arrayEncrypted = RSA.Encrypt(m_zEncoder.GetBytes(sPassword), false);
  21:  // send to server
(line 16) arrayPostHeader is a byte[] related to the Socket message to be sent back to the server
(line 20) arrayEncrypted is a byte[] and sPassword is a string

I recall being very glad that encryption was simple to setup and use!

Looking  back at my old code I can see that line 15 really should just be a typeof. There's really no need to create a new object if you just need the type.

No comments:

Post a Comment