Guide For Building C# Apps On Ubuntu: Cryptographic Helpers

Introduction and Background

In the previous posts, I have shown how you can use MonoDevelop IDE of Mono Project to get started programming C# applications on Linux environment and for the operating system I used Linux distro, Ubuntu operating system. However, since all of the topics are covered already and I am just skimming through the snippets and small portions of the data that I can share, this is another post in the series before I continue to write a guide for this, in a compiled form. In this post, I am going to talk about cryptographic support provided in Mono itself, for Ubuntu.

However, you can always write your own compiled modules that run the cryptographic services and you can also write your own modules that represent the procedures and steps shown in the certified algorithms for cryptography. But, in this post I will talk about the built-in classes and objects provided to you for these services.

I have also talked about security tweaks a lot before, and I would like you to read my previous posts about security in .NET framework too, A few tips for security in .NET framework. Since this is much more about Ubuntu and C# programming using Mono Project, I recommend that you read the previous posts in this series of articles.
So basically this is another post in the series of Ubuntu programming using C# language; Mono Project has been a great tool for C# geeks. In this post I am going to talk about the hashing algorithms, and what else Mono Project has for us!

Security APIs in Mono

No wonder Mono is influenced based on .NET’s philosophy and C# language, but still it lacks many things when it comes to the core APIs, such as security API. It does not have a full package of the APIs in it. For example, on .NET framework the support has been increased to SHA256, SHA512 and more, whereas on Mono there are not many flavors currently added and you only have to stick to either one of the provided, or you would have to manage the base algorithms and write your own implementation of the algorithms, which, definitely, would be hard job! Until Mono introduces some new algorithms, let’s stick to the provided ones and learn about them, how to use them and what they can serve us with.

In Mono APIs, you get two namespaces for security algorithms. The algorithms can be for simple encryption and decryption or it may be for the password hashing purposes. Now, these two are different in many ways, however they are categorized under “Cryptography” in computer science.
  1. Encrypting/decrypting: is a process in which you encode the data in such a way, that a special secret key is required to bring the data back in its original form. It is used while securing the data from potential spywares, because each time you have to access the data, you need to pass a special secret key with it.

  2. Hashing: is a process, typically used for passwords, but is not only restricted to passwords. Hashing is a technique in which data is encrypted, in such a way that it is impossible to be converted back to its original form.
Mono namespaces provide you with objects that allow you to work around with these functions and add a layer of security to your applications. Now, let us first of all, talk about password hashing and then we will get into the encryption and decryption techniques provided in Mono runtimes for developers.

During the article, I will only focus on the objects provided in System.Security.Cryptography, however you can still use Mono.Security.Cryptography, but the recommended one is the native .NET framework’s cryptography namespace.

Hashing the passwords
 
Hashing the passwords has been widely used in every network based application, or online application. Hashing is a process that is not just restricted to the passwords only, as I have already said, the hashing has been widely used to determine the file consistency. Most of the software packages are introduced with MD5 or SHA hash values, they are used to determine if the file is in its real form or if it has been tampered with on its way to your machine. This ensures that the software package that you are installing is actually the “safe” package and has not been mixed with any malware or spyware content. The code from open source communities, such as Ubuntu, Linux and other open-source projects are widely exposed to such attacks, and if you install such packages they make expose your private data and even ask you for some revenue, that happens in cases of ransomware. Linux.Encoder.1 was one of such viruses, that encrypted the user data and then asked them to pay revenue to get their data back. However, hashing is a very simple task in .NET framework at least.
 
Usually, there are many algorithms provided in every framework that can be used in your applications, most commonly used are:
  1. MD5
  2. SHA-128
  3. SHA-256
  4. SHA-512
  5. So on…
Now, before I move any further, I should warn that you should never ever use MD5 for hashing the passwords. MD5 algorithm is very weak and a simple rainbow table attack would expose the passwords. In many cases, you should use SHA-128, or SHA-512. But the recommended one is SHA-256, because of the digest that it creates and the security that it has. I would personally recommend that you use SHA-256, if you want to store a small size of digest (hashed password string; in hex), otherwise, my personal advice is to store SHA-512.

The benefit of having SHA-512 over SHA-256, is that you can minimize the chances of collisions while generating the hashes for the passwords. A collision would typically occur when the hash results are similar for different values. The thing is that the hash function would return a hashed string to a limited size, but it can get an input of any size. Bigger files of larger byte arrays may result in a collision. So, to overcome the collision you may want to generate a hash of bigger size.
Now, talking of hashing the passwords, let me share how to hash the passwords in C#. The procedure is actually similar, if you have a code for .NET on Windows, same would be used on Mono on Ubuntu. Have a look below:
  1. // Function to hash the passwords  
  2. public static string HashPassword(string message)  
  3. {  
  4.     // Create a new instance of the SHA-256,  
  5.     // you should use SHA256Managed instead of SHA256 object.  
  6.     using(var algo = new SHA256Managed())  
  7.     {  
  8.         var bytes = System.Text.Encoding.UTF8.GetBytes(message);  
  9.         var hashedBytes = algo.ComputeHash(bytes);  
  10.   
  11.         // The hash has been computed, to convert those bytes to string  
  12.         // I will use the following code, you may use your own  
  13.         // code to convert the byte array to string  
  14.         System.Text.StringBuilder builder = new System.Text.StringBuilder();  
  15.         foreach(byte bite in hashedBytes)   
  16.         {  
  17.             builder.Append(bite.ToString("x2"));  
  18.         }  
  19.   
  20.         // Return it to the caller, to write it.  
  21.         return builder.ToString();  
  22.     }  
  23. }  
So, basically, what I have done is that I have just used that algorithm and I have got what I was expecting from it. Now, the way we call it defines how we use it. In this sample, I will be calling it to write the hash of it, to the screen and nothing else.
  1. Console.WriteLine("Enter the string to work on:");  
  2.   
  3. // Get the message  
  4. string message = Console.ReadLine();  
  5.   
  6. // Hash the password.  
  7. string hashedStr = Crypto.HashPassword(message);  
  8. Console.WriteLine("Hashed string is: " + hashedStr);  
Basically, we have already created the function that does the thing for us. So we are only calling it in this code. So, if I run the above code it would be something like this.

console
Figure 1: Working of the hashing algorithm on the word, “Afzaal”.

You would store this hashed string in your database when you want to save it. Never save the passwords or sensitive information that you do not want to get back in the actual form, in plain-text form.

Adding some salt to the hash

Now since we are talking about hashing the passwords, it is necessary to add a specific string text to the actual string, which acts as salt to the data. The procedure is very much simple and straightforward, you simply add extra string to the actual string and then find the hash for it. Where you add the salt is your choice, you can append it, prepend it, or insert it at the medians or what-so-ever, that is your choice.
  1. HashPassword (password + salt); // OK  
  2. HashPassword (salt + password); // OK  
  3. HashPassword (salt + password + salt); // OK  
But only thing that you should consider is that you should use the same method to get the hash again, because if you calculate hash differently, their hash value would be different.

message
         Figure 2: Demonstration of the hashing a string message using salt.

When to use hashing?

You can use the following list items to determine when to use hashing functions on your data.
  1. When you want to secure your data from potential sights.
  2. When your data is valuable only for comparison and not required in its raw form. Passwords are a good example of this type of data.
  3. When you want to check if the file system is tampered with.
References:

If you want to learn more about hashing functions, you should go and read the following links:
Encryption and decryption of data

Now that we have already talked about the hashing of the passwords and the data, we can now continue to talk about the encryption and decryption of data in Mono using C#. Encryption and decryption techniques are used to hide the data from unwanted users. It can be shared with other users, and they can also view it, but any user who is not required to be using or viewing the information can be removed from the list of viewers.

encryption and decryption
Image courtesy: This image demonstrates how encryption and decryption is done.

Now we will talk about the coding practices in encryption and decryption. The plain-image, pseudocode and algorithm is very much easy, however, the coding in .NET environment is also very much easy. In the coming sections, you will be shown and taught how to use .NET objects, to perform security restrictions in your applications.

As far as the algorithms are concerned, just like in case of hashing, there are a lot of encryption and decryption algorithms: AES, Rijndael, DES etc. All of them are used, but there are some problems with the later ones and that is why AES algorithm is recommended. However, in my case, I will use Rijndael algorithm, you can change it to AES (and you should change it to AES, I am only using it for demonstration purposes!).

What we do, is that we actually divide the process in a number of steps:
  1. Create the object for algorithm; Rijndael in this case.
  2. Case the memory stream to hold the data.
  3. Create a cryptostream for that memory stream.
  4. Create a stream writer/reader based on encryption or decryption process undergoing.
  5. Return the encrypted or decrypted text.
Each encryption algorithm would require you to pass a special “Key” that would be used for encryption and decryption. The key is the backbone. Without that key, data cannot be converted back to its original form. That is why, keys are kept secretly, in safe places so that potential hackers cannot get to the data. So for demonstration, let’s use the IDE to write some code in it.

1. Encryption function

First of all, let us write a function that encrypts the data as we mentioned in the steps above. A hash function would return an array of bytes, so we would define our custom function to do the same, so that later when working with the values, we can change the data in any form, or save it just the way that it is.
  1. public static byte[] Encrypt(string data)  
  2. {  
  3.     byte[] bytes = null;  
  4.     // Instantiate the algorithm  
  5.     using(var rjndl = new RijndaelManaged())   
  6.     {  
  7.         // Set up the properties  
  8.         rjndl.Key = key;  
  9.         rjndl.IV = iv;  
  10.   
  11.         // Create the memory stream  
  12.         using(MemoryStream stream = new MemoryStream())   
  13.         {  
  14.             // Create the crypto stream  
  15.             using(CryptoStream cStream = new CryptoStream(stream, rjndl.CreateEncryptor(), CryptoStreamMode.Write)) {  
  16.                 // Create the stream writer to write the data.  
  17.                 using(StreamWriter writer = new StreamWriter(cStream))  
  18.                 {  
  19.                     writer.Write(data);  
  20.                 }  
  21.             }  
  22.   
  23.             // Convert the stream of encrypted text, to array.  
  24.             bytes = stream.ToArray();  
  25.         }  
  26.     }  
  27.   
  28.     // Return the bytes.  
  29.     return bytes;  
  30. }  
This function is enough, this would encrypt the data and would provide us with the bytes of the data, in encrypted form. We can then convert those bytes to string, or save then in BLOB format or what-so-ever as required. I will demonstrate the usage in a later section, currently I just want to jump to the decryption part.

2. Decryption function

As name suggests, it is an inverse of the encryption function. The steps required are similar, only that we create a decryptor object for the cryptostream and then start reading the stream in a decryptor object using the same key that was used to encrypt the data in this bytes form. If you use a different key, results are “unknown”.

The following code does the thing for us:
  1. public static string Decrypt(byte[] data)  
  2. {  
  3.     string message = null;  
  4.   
  5.     // Instantiate the algorithm  
  6.     using(var rjndl = new RijndaelManaged())  
  7.     {  
  8.         // Set up the properties  
  9.         rjndl.Key = key;  
  10.         rjndl.IV = iv;  
  11.   
  12.         // Create the memory stream with the bytes of data  
  13.         using(MemoryStream stream = new MemoryStream(data))  
  14.         {  
  15.   
  16.             // Create the stream with the decryptors  
  17.             using(CryptoStream cStream = new CryptoStream(stream, rjndl.CreateDecryptor(), CryptoStreamMode.Read)) {  
  18.   
  19.                 // Create a stream reader for the crypto stream  
  20.                 using(StreamReader reader = new StreamReader(cStream))   
  21.                 {  
  22.                     // Read the data to the end.  
  23.                     message = reader.ReadToEnd();  
  24.                 }  
  25.             }  
  26.         }  
  27.     }  
  28.   
  29.     // Return the message.  
  30.     return message;  
  31. }  
We now have the counterpart of our encryption/decryption algorithm or service (call it what you like!). Now that we have both of our functions ready, we can now test the function and see if it works in our cases for encryption and decryption.
 
I am going to enter my name, and then I will get the encrypted text plus the decryption function would be executed to get the data back.

The following is the main function,
  1. Console.WriteLine(“Enter the string to work on: ”);  
  2.   
  3. // Get the message  
  4. string message = Console.ReadLine();  
  5. Crypto.Setup(); // Look at the code block below!  
  6.   
  7. // Run the logic  
  8. var encrypted = Crypto.Encrypt(message);  
  9. var decrypted = Crypto.Decrypt(encrypted);  
  10.   
  11. string encryptedStr = null;  
  12. StringBuilder strBuilder = new StringBuilder();  
  13. foreach(var b in encrypted)   
  14. {  
  15.     strBuilder.Append(b.ToString("x2"));  
  16. }  
  17.   
  18. encryptedStr = strBuilder.ToString();  
  19.   
  20. Console.WriteLine("Original text was '" + message + "', it was encrypted to: \n" + encryptedStr);  
  21. Console.WriteLine("Decrypted text is: " + decrypted);  
The output of this program was,

output
Figure 4: Encryption and decryption function on “Afzaal Ahmad Zeeshan” string.

Pretty simple, right? :-) So, finally we have encrypted and decrypted the text in Ubuntu using Mono Project…

Tips:
  1. Consider changing the Rijndael to AES.
  2. Keep a strong key, use the provided functions to generate a “strong” random key.
  3. Decrypt when needed.
Using Rijndael or AES?
 
Rijndael and AES can be confusing somehow. Don’t worry, I was also confused as to which is better and which is not. The thing is, Rijndael algorithm was developed along with numerous other algorithms, to come on top as “best algorithm for encryption and decryption“. Rijndael won, and was selected as AES algorithm.
Does that make sense? It should… If that doesn’t, read this blog post.

Points of Interest

This is another post in the series of “Programming C# on Ubuntu” articles. In this, I have talked about cryptographic programming in Mono Project on Ubuntu. The services are similar to what we have in .NET framework on Windows operating system. However, there are some other namespaces provided by Mono itself, but still, .NET namespaces rule them out. The services that you can find in .NET are amazing, and C# language itself is just perfect language to be used for any project! I am writing this guide, to share the beauty of C# on cross-platform environments too, for those who are unaware of this currently.

In this post, you were given a few tips and you were shown how to perform cryptographic functions on your data, including hashing the passwords, and encrypting and decrypting the data on your machine. Cryptography can greatly influence your application’s performance, and your users would like the privacy and other services that you have for them, such as encryption and decryption of the data, using which they can save their data from unwanted users, and yes, hackers!

In later post, I will talk about NuGet package managements, and then I will head over to writing a guide, in the form of a book itself. See you in the later posts.

Up Next
    Ebook Download
    View all
    Learn
    View all