Sunday, 8 May 2016

RSA algorithm demo in MonoDevelop and GtkSharp

This article will present a demo of using RSA in Monodevelop using GtkSharp UI framework. As you know, the Mono project offers an implementation of .NET framework, such as BCL, CLR, MSIL and so on - and also the classes in System.Security.Cryptography! So let us delve into the details of doing some RSA crypto! First off, the GUI looks like this:


In MonoDevelop we use the Stetic GUI Designer to build the GUI!





Cool! We can build apps that runs on Linux and Windows with Monodevelop! Now over to the code of this app!




using System;
using Gtk;
using System.Text;
using System.Security.Cryptography; 
using System.Security; 
using System.IO; 

public partial class MainWindow: Gtk.Window
{

 private RSACryptoServiceProvider _rsa;
 private RSAParameters _rsaPrivateKey;
 private RSAParameters _rsaPublicKey;
 private byte[] _cipherBytes; 
 private byte[] _decipherBytes; 
 private byte[] _plainTextBytes;

 public MainWindow () : base ("Pango")
 {
  Application.Init ();
  Build ();
  SetupControls ();
  Application.Run ();
 }

 private void SetupControls(){
  Gdk.Color color = new Gdk.Color (255, 30, 80);
     lblP.ModifyFont (Pango.FontDescription.FromString ("Purisa 10")); 
  //lblP.ModifyBg (StateType.Normal, new Gdk.Color (255, 80, 10));
 }

 protected void OnDeleteEvent (object sender, DeleteEventArgs a)
 {
  Application.Quit ();
  a.RetVal = true;
 }

 protected void btnRsaSetupClick (object sender, EventArgs e)
 {
  _rsa = new RSACryptoServiceProvider ();
 
  StringWriter writer = new StringWriter (); 
  string rsaSetupXml = _rsa.ToXmlString (true);
  writer.Write (rsaSetupXml); 
  //tbRsaSetup.Buffer.Text = writer.ToString ();
  writer.Close ();

  _rsaPrivateKey = _rsa.ExportParameters (true);
  _rsaPublicKey = _rsa.ExportParameters (false); 

  SetupControls ();
  DisplayRsaSetup (_rsaPrivateKey);
 } 

 private void DisplayRsaSetup (RSAParameters rsaParams){
  try {
   lblPValue.Text = Convert.ToBase64String (rsaParams.P);
   lblQValue.Text = Convert.ToBase64String (rsaParams.Q);
   lblModulusValue.Text = Convert.ToBase64String (rsaParams.Modulus);
   lblDValue.Text = Convert.ToBase64String(rsaParams.D);
   lblEValue.Text = Convert.ToBase64String (rsaParams.Exponent);

  } catch (Exception err) {
   Console.WriteLine (err.Message);
  }

 }

 protected void btnEncryptClicked (object sender, EventArgs e)
 {
  if (_rsa == null)
   return;
  _plainTextBytes = Encoding.UTF8.GetBytes (textViewPlainText.Buffer.Text);
  _cipherBytes = _rsa.Encrypt (_plainTextBytes, false);
  textviewEncrypted.Buffer.Text = Convert.ToBase64String(_cipherBytes);
 }

 protected void btnDecryptClicked (object sender, EventArgs e)
 {
  textviewDecrypted.Buffer.Text = string.Empty; 

  if (_rsa == null)
   return;
  if (_cipherBytes == null)
   return; 
  _decipherBytes = _rsa.Decrypt (_cipherBytes, false); 

  textviewDecrypted.Buffer.Text = Encoding.UTF8.GetString(_decipherBytes); 
 }

}





As you can see in the code, we instantiate a new RSACryptoServiceProvider instance. We use the Encrypt and Decrypt method, using the second argument set to false to not use the OAEP padding, that is the Optimal Assymetric Encryption Padding for compability. Setting false here for padding will use the PKCS# instead. PKCS stands for Public Key Cryptography Standards. I have tested also with the parameters set to true i OAEP, and it seems to work nice also with Monodevelop - so you could use both types of padding. Note that we use the ExportParameters methods of the RSACryptoServiceProvider to the the RSAParameters object. In assymetric encryption, we must guard our private key and expose our public key. This is a comprehensive demo of the RSA algorithm. We would use the ExportParameters method with the parameters set to false to not include the private key. To export the RSA parameters with more compability, you can export the parameters as XML. You can use the ToXmlString() method to export the XML as a string. You can either export the RSA parameters as a string or to a file, and you can then use the method FromXmlString() to import the RSA parameters.

 {
  _rsa = new RSACryptoServiceProvider ();
 
  StringWriter writer = new StringWriter (); 
  string rsaSetupXml = _rsa.ToXmlString (true);
  writer.Write (rsaSetupXml); 
  //tbRsaSetup.Buffer.Text = writer.ToString ();
  writer.Close ();

As you can see in the code above, you can use a StringWriter to write to a string, but you can also use a FileStream to write the contents out to a file. Using the ToXmlString - you will export the information needed for a public key by setting the argument of this method to FALSE. To include private key information, you would provide the value TRUE here. In the RSA algorithm the following is belonging to the "PUBLIC Domain":
  • Modulus
  • Public exponent E
The "PRIVATE Domain" contains the additional information:
  • Private exponent D
  • Prime P
  • Prime Q
Private domain will also reveal the values DQ, DP, InverseQ that is given by this extra information. The security of the RSA algorithm relies on the toughness of prime factorization of large prime numbers. RSA will use large numbers and the public key only contains the modulus (product) of the prime numbers and a public exponent E that the sender will use this information as a public key to encrypt the information. The receiver, which knows the private key can then decrypt the information with this extra information. So the key note here is to guard your private key and share your public key! And that you can do RSA encryption when making applications for Linux of course, with Monodevelop! The .NET Framework is already there for you to use and it is very updated. To work with this sample, a download link is shown below. Bunzip the file using the command: tar xjvf RsaDemo.tar.bz2 Monodevelop project with RsaDemo

tar xjvf Symmetric.tar.bz2 

Just so you know:
tar - Tape ARchiver
And the options:
x - extract
v - verbose output (lists all files as they are extracted)
j - deal with bzipped file
f - read from a file, rather than a tape device

"tar --help" will give you more options and info

After unpacking, just open the solution in MonoDevelop.

So .NET Developers - Start your engines - Start developing for Linux!

Friday, 6 May 2016

Symmetric crypto algorithms in C# with MonoDevelop and GTK-Sharp

Using MonoDevelop and GTK-Sharp (GTK#) offers a .NET developer to develop applications for other platforms such as applications in Linux and other OS-es. Let's look more at the very able MonoDeveloper IDE and GTK-Sharp. As a .NET developer who has written .NET applications for many years, MonoDevelop has fully matured into a very good platform to develop a multitiude of applications. GTK# resembles .NET Windows Forms in many ways. We will here use some symmetric crypto algorithms in .NET that is available with Mono framework. The demo provides Digital Encryption Standard (DES) and Triple-DES, plus the Advanced Encryption Standard (AES) - Rijndael. The GUI will look like this:

The GUI is designed with the GUI designer Stetic in Monodevelop, for developing GTK#-applications. We can choose the Mode of the cryptographic algorithm, default here is Cipher Block Chaining. We can also set the padding of the cryptographic algorithm. Note that not all combinations are legal. I have tested with Rijndael, Cipher Block Chaining and padding set to Zeros, which seems to be working ok. You can use the demo here to test out other combinations. You can also generate different Initialization Vectors and Keys to use with the algorithm.

The code to achieve the encryption and decryption is listed below:

using System;
using System.Security.Cryptography;
using Gtk;
using System.IO;

public partial class MainWindow: Gtk.Window
{

 private SymmetricAlgorithm _symmetricAlgorithm; 
 private byte[] _intializationVector; 
 private byte[] _key;
 private byte[] _cipherBytes;



 public MainWindow () : base (Gtk.WindowType.Toplevel)
 {
  Build ();
 }

 protected void OnDeleteEvent (object sender, DeleteEventArgs a)
 {
  Application.Quit ();
  a.RetVal = true;
 }

 protected void btnGenerateIVClick (object sender, EventArgs e)
 {
     _symmetricAlgorithm = CreateSymmetricAlgorithm (); 

  _symmetricAlgorithm.GenerateIV ();
  _intializationVector = _symmetricAlgorithm.IV;

  lbInitializationVector.Text = Convert.ToBase64String(_symmetricAlgorithm.IV);

//  MessageDialog msgBox = new MessageDialog (null, DialogFlags.Modal, 
//                      MessageType.Info, ButtonsType.Ok, "Why hello world!");
//  msgBox.Run ();
//  msgBox.Destroy ();
 }

 protected void btnEncrypt_Click (object sender, EventArgs e)
 {
  _symmetricAlgorithm = CreateSymmetricAlgorithm (); //ensure that we use the selected algorithm
  _cipherBytes = Encrypt(textviewPlainText.Buffer.Text);
  textviewCipher.Buffer.Text = Convert.ToBase64String(_cipherBytes); 
 }

 private byte[] Encrypt(string text){
  byte[] encrypted;
  ICryptoTransform encryptor = _symmetricAlgorithm.CreateEncryptor (_key, _intializationVector);
  using (MemoryStream msEncrypt = new MemoryStream ()) {
   using (CryptoStream csEncrypt = new CryptoStream (msEncrypt, encryptor, CryptoStreamMode.Write)) {
    using (StreamWriter swWriter = new StreamWriter (csEncrypt)) {
     swWriter.Write (text);
    }
    encrypted = msEncrypt.ToArray (); 
   }

  }
  return encrypted;
 }

 private string Decrypt(byte[] cipherBytes){
  try {
   ICryptoTransform decryptor = _symmetricAlgorithm.CreateDecryptor (_key, 
    _intializationVector);
   using (MemoryStream msEncrypt = new MemoryStream (cipherBytes)) {
    using (CryptoStream csEncrypt = new CryptoStream (msEncrypt, decryptor,
     CryptoStreamMode.Read)) {
     using (StreamReader sReader = new StreamReader (csEncrypt)) {
      string decrypted = sReader.ReadToEnd();
      return decrypted;
     }
    } 
   }
  } catch (Exception err) {
   Console.WriteLine (err.Message);
  }
  return string.Empty;
 }

 private SymmetricAlgorithm CreateSymmetricAlgorithm(){
  SymmetricAlgorithm sa = null;
  if (rbDES.Active)
   sa = DESCryptoServiceProvider.Create ();
  if (rbThreeDES.Active)
   sa = TripleDESCryptoServiceProvider.Create ();
  if (rbRijndael.Active)
   sa = RijndaelManaged.Create ();

  if (sa == null)
   sa = DESCryptoServiceProvider.Create (); 

  if (_intializationVector != null)
   sa.IV = _intializationVector;
  if (_key != null)
   sa.Key = _key;

  sa.Mode = GetCipherMode ();
  sa.Padding = GetPadding ();
  return sa;
 }

 private PaddingMode GetPadding(){
  if (rbPaddingNone.Active)
   return PaddingMode.None;
  if (rbPaddingZeros.Active)
   return PaddingMode.PKCS7;
  if (rbPaddingAnsiX923.Active)
   return PaddingMode.ANSIX923;
  if (rbPaddingISO1126.Active)
   return PaddingMode.ISO10126;
  return PaddingMode.Zeros;
 }

 private CipherMode GetCipherMode(){
  if (rbCBC.Active)
   return CipherMode.CBC;
  if (rbCFB.Active)
   return CipherMode.CFB;
  if (rbCTS.Active)
   return CipherMode.CTS;
  if (rbECB.Active)
   return CipherMode.ECB;
  if (rbOFB.Active)
   return CipherMode.OFB;

  return CipherMode.CBC;
 }

 protected void btnKeyClick (object sender, EventArgs e)
 {
  _symmetricAlgorithm = CreateSymmetricAlgorithm ();     

  _symmetricAlgorithm.GenerateKey ();  
  _key = _symmetricAlgorithm.Key;
  lblKey.Text = Convert.ToBase64String (_symmetricAlgorithm.Key);
 }

 protected void btnDecryptClick (object sender, EventArgs e)
 {
  _symmetricAlgorithm = CreateSymmetricAlgorithm (); //ensure that we use the selected algorithm
  string decrypted = Decrypt(Convert.FromBase64String(textviewCipher.Buffer.Text));
  textviewDecrypted.Buffer.Text = decrypted; 
 }
}











To open up this sample, I have uploaded the MonoDevelop project as a tar.bz2 file available for download here: Sample project Monodevelop in this article To unzip the tar bunzip2 file, just the following command:
tar xjvf Symmetric.tar.bz2 

Just so you know:
tar - Tape ARchiver
And the options:
x - extract
v - verbose output (lists all files as they are extracted)
j - deal with bzipped file
f - read from a file, rather than a tape device

"tar --help" will give you more options and info

After unpacking, just open the solution in MonoDevelop.





Wednesday, 4 May 2016

Creating a simple MD5 application using GTK# and Monodevelop

Let's look at building a simple application using GTK# and Monodevelop! I created this application using a Ubuntu 16.04 Xenial AMD64 Distribution of Linux running inside an Oracle VM VirtualBox on my Windows 10 Machine! First off, this article will show a very simple application written in Monodevelop IDE using GTK# to build a GUI. It resembles somewhat Windows Forms if you come from a Visual Studio background, such as I do. The application just takes some text input (plaintext) and computes a MD5 hash. Simple stuff. Defining the following form in MainWindow of the GTK# application: Moving over to the code bit, I define the following in MainWindow (Source of the form), which is the code behind:

using System;
using System.Linq;
using Gtk;
using System.Security.Cryptography;
using System.Text;


public partial class MainWindow: Gtk.Window
{
 public MainWindow () : base (Gtk.WindowType.Toplevel)
 {
  Build ();
  btnMd5.Clicked += OnBtnClick;
 }

 protected void OnDeleteEvent (object sender, DeleteEventArgs a)
 {
  Application.Quit ();
  a.RetVal = true;
 }

 protected void OnBtnClick (object sender, EventArgs args)
 {
  var md5 = MD5CryptoServiceProvider.Create ();
  byte[] plainTextBytes = Encoding.UTF8.GetBytes (tbPlainText.Buffer.Text); 
  byte[] hashBytes = md5.ComputeHash (plainTextBytes); 
  var sbuilder = new StringBuilder (); 

  sbuilder.Append(string.Join("",
  hashBytes.Select(x => x.ToString("x2")))); 
  tbHash.Buffer.Text = sbuilder.ToString();
 }

}



The code above instantiates a MD5CryptoServiceProvder instance, then computes a hash. We get a string representation of the MD5 hash using a StringBuilder and we use ToString("x2") - which assembles a hexidecimal string for us, which is the common way to represent a MD5 hash. A MD5 hash produces 128 bits = 16 bytes = 32 hexidecimal digits. A hexadecimal value can be 0-9 and A-F = 16 different values = one half byte.

We build up our GUI using the GUI designer inside Monodevelop. The GUI designer for GTK# in Monodevelop is called Stetic.
Stetic