Monday, 16 May 2016

How to ensure the integrity of information in .NET using Digital Signature Algorithm DSA

This article will concern the topic of digital signature. There are several ways to ensure the integrity of the information or data that is sent. This concerns the concept of non-repudiation, the case that the sender cannot deny that he or she is the true sender of that data. We also can check that the data is correct, so digital signature can act as some sort of checksum - but for the entire message. We are also concerned that the information is authentic and original and not tampered with by an attacker. Digital Signature Algorithm in .NET or DSA uses the SHA-1 Secure Hash Algorithm. There are today more powerful methods to sign data, such as the RSACryptoServiceProvider. But we will in this article use DSACryptoServiceProvider. DSA is today not considered failsafe. There are security vulnerabilities. However, for ordinary use - it is not that easy to break. Just like in RSA, there is a public and private key. The API is very similar to RSACryptoServiceProvider. The following console application shows some central API calls on a DSACryptoServiceProvider.

using System;
using System.Security.Cryptography;
using System.Text;

namespace DSASignDemo
{
    class Program
    {

        // ReSharper disable once UnusedParameter.Local
        static void Main(string[] args)
        {
            var dsa = new DSACryptoServiceProvider(1024);
            var publicDsaParameters = dsa.ExportParameters(false);
            var privateDsaParameters = dsa.ExportParameters(true);
            string inputText = "Burgers and coca cola";
            byte[] inputData = Encoding.Unicode.GetBytes(inputText);
            byte[] signedBytes = SignData(inputData, privateDsaParameters);
            bool isVerified = VerifyData(inputData, signedBytes, publicDsaParameters);

            Console.WriteLine("Input text: " + inputText);
            Console.WriteLine("Signed text: " + Convert.ToBase64String(signedBytes));

            if (isVerified)
                Console.WriteLine("The message was verified");
            else
                Console.WriteLine("The message was not verified");

            byte[] hashData = ComputeHash(inputData);
            Console.WriteLine("SHA-1 computed hash: " + Convert.ToBase64String(hashData));

            bool isHashSame = CompareHash(inputText, Convert.ToBase64String(hashData)); 
            if (isHashSame)
                Console.WriteLine("Hash is the same");
            else 
                Console.WriteLine("Hash is not same");

            byte[] signedHashData = dsa.SignHash(hashData, "SHA1");

            Console.WriteLine("Signed hash: ");
            Console.WriteLine(Convert.ToBase64String(signedHashData));

            bool isVerifiedHash = dsa.VerifyHash(hashData, "SHA1", signedHashData);
            if (isVerifiedHash)
                Console.WriteLine("Hash is verified");
            else
                Console.WriteLine("Hash is not verified");



            Console.WriteLine("Press the any key to continue ..");
            Console.ReadKey();  
        }

        static bool CompareHash(string inputText, string hashText)
        {
            string computedHash = Convert.ToBase64String(ComputeHash(Encoding.Unicode.GetBytes(inputText)));
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;
            return comparer.Compare(computedHash, hashText) == 0; 
        }

        static byte[] ComputeHash(byte[] inputData)
        {
            var shaManaged = new SHA1Managed();
            byte[] hashBytes = shaManaged.ComputeHash(inputData);
            return hashBytes;
        }

        static byte[] SignData(byte[] inputData, DSAParameters dsaParameters)
        {
            try
            {
                var dsa = new DSACryptoServiceProvider();
                dsa.ImportParameters(dsaParameters);
                return dsa.SignData(inputData);
            }
            catch (CryptographicException cge)
            {
                Console.WriteLine(cge.Message);
                return null;
            }
        }

        static bool VerifyData(byte[] inputData, byte[] signedData, DSAParameters dsaParmeters)
        {
            try
            {
                var dsa = new DSACryptoServiceProvider();
                dsa.ImportParameters(dsaParmeters);
                return dsa.VerifyData(inputData, signedData); 
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                return false;
            }
        }




    }
}


A sample output of running this console application is:
 


Input text: Burgers and coca cola
Signed text: su7Qv+O58MyOzFjWXXx6bq9xAz9GtJ30+N8pmEYA4qFwmCdU04+qWg==
The message was verified
SHA-1 computed hash: b4o//84sCZ5cUY6cfewNia9yHYI=
Hash is the same
Signed hash:
xWExD3udQWayE2nfVDY+w8o/VuuBlKRng5Oe5XZ1zBAJO90BG+dbcA==
Hash is verified
Press the any key to continue ..


Note that the output will differ per run, where it says signed text and SHA-1 computed hash and signed hash. The reason is that the DSA algorithm will choose a random number in part of its steps and the resulting output will give different results. The boolean values here should of course be consistent, i.e. give consistens checks. Some things to note here: - Using the constructor we ask for at least a 1024 bit sized BigNum in the constructor of the DSACryptoServiceProvider to be used to generate the large primes that is involved in the DSA algorithm. - We actually use the private key of DSA to sign data and the public key to verify the data. DSA is an assymetric cryptographic algoritm and the order in which the keys are used is kind of reversed to RSA. It is the sender that sign the data and the receiver that verifies the data with a public key. - For speed, we can sometimes choose to just compute a hash like SHA-1 and then sign this hash. We can then verify hash. This is much quicker than signing large data. So first off, we can compute a SHA-1 hash, then sign the hash and then include this signed hash appended to the message, then let the receiver just verify the signed hash. The receiver will then use the hash and the signed hash and verify the hash and the fact that the message integrity is kept. We must tell the method VerifyHash which algorithm that is used. An overview of the hash algorithm names you can use in one of the arguments of SignHash and VerifyHash methods is available here: https://msdn.microsoft.com/en-us/library/system.security.cryptography.hashalgorithmname(v=vs.110)

How to do async calls without locking the UI thread in WPF

WPF developers that have worked with async await have most likely run into problems with avoiding race conditions with the UI thread, either making the entire UI lock up or burden the UI thread and cause clients not responding. This article will show you how to avoid this. The way to do this is to await using another thread and afterwards use that result back again on the WPF thread to do the updates in the UI. We use ThreadPool.QueueUserWorkItem for this. As you can see, we user an inner method marked with async keyword to await the results. This is done to avoid the classic "async proliferation" seen in async code, where the async keyword spreads upwards to all methods. We instead use an outher method and call the async method and use the Result of the Task returned. We could do some quality checking here, to check if the Task succeeded of course. The Task object contains status information about if the results are really available or not and Result will throw an exception if there was an error in the retrieval of the async results from the lower layers of the software app layers. Example code:

DispatcherUtil.AsyncWorkAndUiThreadUpdate(Dispatcher.CurrentDispatcher, () => GetSomeItems(someId),
 x => GetSomeItemsUpdateUIAfterwards(x), displayWaitCursor:true);
//Note here that we retrieve the data not on the UI thread, but on a dedicated thread and after retrieved the
//result, we do an update in the GUI. 
private List<SomeItemDataContract> GetSomeItems(int someId)
        {
         var retrieveTask = GomeSomeItemsInnerAsync(someId);
         return retrieveTask.Result;
        }
 
private async Task<List<SomeItemDataContract>> GetSomeItemsInnerAsync(int someId)
        {
         List<SomeItemDataContract> retrieveTask = await SomeServiceAgent.GetSomeItems(someId);
         return retrieveTask;
        }

private void GetSomeItemsUpdateUIAfterwards(SomeItemDataContract x){
 if (x != null){
  //Do some UI stuff - remember RaisePropertyChanged
 }
}


Utility method:

public static void AsyncWorkAndUiThreadUpdate<T>(Dispatcher currentDispatcher, Func<T> threadWork, Action<T> guiUpdate, 
bool displayWaitCursor = false)
        {
         if (displayWaitCursor)
          PublishMouseCursorEvent<T>(Cursors.Wait);

         // ReSharper disable once UnusedAnonymousMethodSignature 
         ThreadPool.QueueUserWorkItem(delegate(object state)
            {
              T resultAfterThreadWork = threadWork();
              // ReSharper disable once UnusedAnonymousMethodSignature
              currentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<T>(delegate {
       
              if (displayWaitCursor)
               PublishMouseCursorEvent<T>(Cursors.Arrow);
 
              guiUpdate(resultAfterThreadWork);
           }), resultAfterThreadWork);

            });
 
        }

The PublishMouseCursorEvent publishes a prism event that is captured by a Bootstrapper class, but what you choose to do here is of course up to you. One way is to subscribe such an event (either a CompositePresentationEvent as in Prism or an ordinary CLR event for example):
private void OnCursorEvent(CursorEventArg eventArg)
{
 if (eventArg != null)
 {
 Mouse.OverrideCursor = eventArg.Cursor;
 }
}

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!