RC4 Stream Cipher

I recently started to look at some other cryptography ciphers outside what is included in my development platform of choice, .NET, and started reading up on RC4. RC4 is a stream cipher.

Stream Ciphers

A stream cipher is a symmetric key cipher where plain-text digits are combined with a pseudo-random cipher digit stream (key-stream). In a stream cipher each plain-text digit is encrypted one at a time with the corresponding digit of the key-stream, to give a digit of the cipher-text stream. With a stream cipher a digit is typically a bit and the combining operation an exclusive-or (XOR).

RC4 Stream Cipher
RC4 Stream Cipher

The pseudo-random key-stream is typically generated serially from a random seed value using digital shift registers. The seed value serves as the cryptographic key for decrypting the cipher-text stream.

Stream ciphers represent a different approach to symmetric encryption from block ciphers. Block ciphers operate on large blocks of data n a fixed block size. Stream ciphers typically execute at a higher speed than block ciphers and have lower hardware complexity.

RC4 Stream Cipher

In cryptography, RC4 (also known as ARC4 or ARCFOUR meaning Alleged RC4) is the most widely used software stream cipher and is used in popular protocols such as Transport Layer Security (TLS) (to protect Internet traffic) and WEP (to secure wireless networks). While remarkable for its simplicity and speed in software, RC4 has weaknesses that argue against its use in new systems.

RC4 was designed by Ron Rivest of RSA Security in 1987. RC4 was initially a trade secret, but in September 1994 a description of it was anonymously posted to a mailing list. The leaked code was confirmed to be genuine as its output was found to match that of proprietary software using licensed RC4. Because the algorithm is known, it is no longer a trade secret. The name RC4 is trademarked, so RC4 is often referred to as ARCFOUR or ARC4 (meaning alleged RC4) to avoid trademark problems.

Advertisements

Cryptography in .NET Talk at the DotNet Notts Usergroup

Meetup at DotNet Notts
Meetup at DotNet Notts

On January 26th 2015 I will be doing a talk at the DotNet Notts usergroup in Nottingham UK. The talk will be on Pragmatic Cryptography in .NET. The talk synopsis is as follows.

Data security is something that we as developers have to take seriously when developing solutions for our organizations. Cryptography can be a deeply complicated and mathematical subject but as developers we need to be pragmatic and use what is available to us to secure our data without disappearing down the mathematical rabbit hole.

In this talk Stephen Haunts will take you through what is available in the .NET framework for enterprise desktop and server developers to allow you to securely protect your data to achieve confidentiality, data integrity and non-repudiation of exchanged data. Stephen will cover the following:

Cryptographically secure random number generation.

Hashing and Authenticated Hashes.

Symmetric Encryption with DES, TripleDES, and AES.

The pitfalls of key exchange

Asymmetric Encryption with RSA.

Hybrid Encryption by using Symmetric and Asymmetric encryption together.

Digital Signatures.

Serializing POCO’s to Byte Arrays in C#

I have recently had a need to serialize objects in .NET down to a byte array to send to another system for a project that I was working on, so I thought I would share some of the code.

I have written about serializing POCO objects into XML before on this blog.

In the rest of this post I will show a simple implementation of a class called ObjectSerialize that adds a set of extension methods onto the base object class.

ObjectSerialize Class
ObjectSerialize Class

The ObjectSerialize class contains 2 public methods, Serialize and DeSerialize. These methods will be available as extension methods on the base object method in .NET. There are also 2 private methods (Compress and Decompress) that apply GZip compression to the object being serialized to ensure the byte arrays are as compact as possible.

Lets take a look at the Serialize method.

public static byte[] Serialize(this Object obj)
{
    if (obj == null)
    {
        return null;
    }

    using (var memoryStream = new MemoryStream())
    {
        var binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, obj);
        var compressed = Compress(memoryStream.ToArray());

        return compressed;
    }
}

This method takes an object and then serialises the object into a MemoryStream using a BinaryFormatter. The MemoryStream is then run thorough the compress method to apply the GZip compression. The resulting byte array is then returned.

Cryptography in .NET : Digital Signatures

I have previously written a number of articles on Cryptography in .NET, like the following :

Part 1 – Advanced Encryption Standard (AES)

Part 2 – RSA

Part 3 – Random Numbers and Hashes

Part 4 – Hybrid Encryption Protocols

Block Encrypter .NET Library for secure AES Encryption

In this article I will show you how to create and use Digital Signatures in .NET.

A digital signature is a mathematical scheme that demonstrates the authenticity of a message or document. A valid digital signature gives the recipient reason to believe that the message was created by a known sender, such that the sender cannot deny having sent the message (authentication and non-repudiation) and that the message was not altered in transit (integrity). Digital signatures are commonly used for software distribution, financial transactions, and in other cases where it is important to detect forgery or tampering.

Digital signatures are often used to implement a digital analog to hand written signatures. In broader terms this refers to any electronic data that carries the intent of a signature. Digital signatures employ a type of asymmetric cryptography. For messages sent through a non-secure channel, a properly implemented digital signature gives the receiver reason to believe the message was sent by the claimed sender. Digital signatures are equivalent to traditional handwritten signatures in many respects, but properly implemented digital signatures are more difficult to forge than the handwritten type. Digital signature schemes, in the sense used here, are cryptographic based, and must be implemented properly to be effective. Digital signatures can also provide non-repudiation, meaning that the signer cannot successfully claim they did not sign a message, while also claiming their private key remains secret.

Example Digital Signature Flow
Example Digital Signature Flow

A digital signature scheme consists of three algorithms

  • A key generation algorithm that generates a private and public key, such as RSA.
  • A signing algorithm that, given a message and a private key, produces a signature.
  • A signature verifying algorithm that, given a message, public key and a signature, either accepts or rejects the message’s claim to authenticity.

Two main properties are required. First, the authenticity of a signature generated from a fixed message and fixed private key can be verified by using the corresponding public key. Secondly, it should be computationally infeasible to generate a valid signature for a party without knowing that party’s private key. A digital signature is an authentication mechanism that enables the creator of the message to attach a code that act as a signature. It is formed by taking the hash of message and encrypting the message with creator’s private key.

Forcing an Application to a Single Instance in C#

In this short code snippet, I want to show a simple technique for ensuring only one instance of your .NET application can run at a time.

The technique is below :

    using System.Threading;
    using System.Windows;

    namespace MyApplication
    {
	    public partial class App : Application
	    {
	        private Mutex _mutex;

	        public App()
	        {
	            bool aIsNewInstance;

	            _mutex = new Mutex(true, @"Global\" + "MyUniqueWPFApplicationName", out aIsNewInstance);

	            GC.KeepAlive(_mutex);

	            if (aIsNewInstance) return;

	            MessageBox.Show("There is already an instance running.",
	                "Instance already running.",
	                MessageBoxButton.OK, MessageBoxImage.Information);

	            Current.Shutdown();
	        }
	    }
    }

What happens is that a Mutex is created when the application starts up and it is given a unique name, in this case, “MyUniqueWPFApplicationName“. If another instance of the application is started up and the Mutex is already created with that name, the application will shut down. You will also notice that there is a prefix to the name (Global\) that makes the unique name global to a sever running terminal services. If you leave off this prefix, then the mutex is considered local.

APR Calculator Code Open Sourced

Last year I wrote an article about some code to help calculate the Annual Percentage Rate for a loan. The code discussed how to calculate APR’s that were compliant with the United Kingdoms Financial Conduct Authorities FCAMCOB 10.3 Formula for calculating APR.

APR

Even though all the code in contained in the article, I have received many requests for a Visual Studio project containing the code and all the unit tests that cover the test scenarios in the original article, so what I have done is open source the code on Codeplex. It seems many people have found this code useful, which is great, so I hope that by open sourcing it, more people will get use out of it.

Using Async and Await to update the UI Thread Part 2

In a previous article on async and await, I showed a very simple example of how to run some code asynchronously. Then in the 2nd article I showed an example of updating the user interface in the main thread from an async method.

The code below (from the previous article) would execute a long running task which in this case counts to 5,000,000. As the task was running, on a set interval, the UI would be updated. This effectively decoupled the running of the task from the updating of the UI. You could have the task update the UI every 10ms, or you could update every 5 seconds. It really depends on what you are trying to do.

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsAsync
{
    public partial class Form1 : Form
    {
        private readonly SynchronizationContext synchronizationContext;
        private DateTime previousTime = DateTime.Now;

        public Form1()
        {
            InitializeComponent();
            synchronizationContext = SynchronizationContext.Current;
        }

        private async void ButtonClickHandlerAsync(object sender, EventArgs e)
        {
            button1.Enabled = false;
            var count = 0;

            await Task.Run(() =>
            {
                for (var i = 0; i <= 5000000; i++)
                {
                    UpdateUI(i);
                    count = i;
                }
            });

            label1.Text = @"Counter " + count;
            button1.Enabled = true;
        }

        public void UpdateUI(int value)
        {
            var timeNow = DateTime.Now;

            if ((DateTime.Now - previousTime).Milliseconds <= 50) return;

            synchronizationContext.Post(new SendOrPostCallback(o =>
            {
                label1.Text = @"Counter " + (int)o;
            }), value);             

            previousTime = timeNow;
        }
    }
}

A reader on Reddit suggested that you can write this code in a much more succinct way as shown below. The code is much simpler to see what’s going on, but the behaviour is slightly different. In this example, the code similarly counts upto 5,000,000 and updates the UI label. The await statement here will correctly restore the synchronisation context to update the UI thread which means you don’t have to deal with it manually (I didn’t realise that at the time). To enable the asynchrony of the task in this example we need to have a Task.Delay(1) as we are not using any other asynchronous objects in .NET for file or DB access for example.