January 7, 2015

WCF Project Templates in Visual Studio

Article is copying from my publish article at experts-exchange.com

Project templates provide the class structure and definition of service contracts, data contracts and other important features in Visual Studio for Windows Communication Foundation. Using these predefined template helps you to write a service with minimal code interaction and it will lead you to build more advanced services for your projects.

There are four different types of templates present in Visual Studio. The first two are the most commonly used to build, test and deploy SOA architectural applications.

1. WCF Service Library: 

The WCF Service Library project (C#) consists of three files; IService1.cs, Service1.cs and App.config. The WCF Service Library project (VB.Net) is consists of three files; IService1.vb, Service1.vb and App.config.

This type of project is suitable when we are focused on building the services first and deployment later.

  • IService File: This is the interface where the WCF service attributes are applied. In this file you place the definitions of data contract methods/operations.
  • Service File: This file is inherited from IService interface file and includes the implementations of defined interface's data contract methods/operations. 
  • Application Configuration File: In this file, you place the definitions of secure HTTP binding, endpoints of services and other important features.


2. WCF Service Application:
The WCF Service Application project (C#) is consists of four files; IService1.cs, Service1.svc, Service1.svc.cs and Web.config. The WCF Service Application project (VB.Net) is consists of four files; IService1.vb, Service1.svc, Service1.svc.vb and Web.config.

This type of project template creates a web site to be deployed to a virtual directory and hosts a service in that website.

  • Service Contract File (IService): The service contract interface file where you place the definitions of data contract operations.
  • Service Host File (Service1.svc) and Service Implemnetation File (Service1.svc.cs): This file is inherited from the service contract file and implements the data contract operations.
  • Web Configuration File: In this file, you place the definitions of secure HTTP binding, endpoints of services and other important features.

3. WCF Workflow Service Application:
The workflow (WF) service application can be accessed like a web service. It defines distinguish templates for XAML and other imperative programming models. We can create sequential and state machine workfow projects using these templates.


4. Syndication Service Application:

This type of project template provides the syndication functionality in an application in which you can easily work with feeds in ATOM, RSS and other custom formats as a WCF service. These are allowed you to read and create them and also expose them on service endpoints.

Now hopefully, you'll understand the different project templates in WCF which will be create as per the demand and the requirement.

January 6, 2015

Encryption - Decryption using AES Algorithm

Article is copying from my publish article at experts-exchange.com

You can find plenty of algorithms on the Internet that provide the Encryption - Decryption functionality. One of them is the AES algorithm. AES stands for "Advanced Encryption Standard".

The Advanced Encryption Standard was established by US National Institute of Standards and Technology in 2001. It was based; on the work of two Belgian cryptographers, Joan Daemen and Vincent Rijmen, who submitted the proposal to NIST during the selection process.

In the AES algorithm, there is a terminology we use called 'Cipher Mode'. There are different types Cipher Modes present in the algorithm. Based on your specific needs and requirements you can select the Cipher Modes. Let's have a look at what these are and how they differentiate from other cipher modes.

1. Electronic Code Book Mode: This mode doesn't require any feedback to be applied. You pass the plain text/data using this and and get the resulted Cipher data from it directly. The main disadvantage is that this mode will return the same cipher data on passing the same type of plain text in loop; if you pass 'Hello, World!' three times in this mode then it will return same cipher data in each iteration. That is why this mode is considered as 'Vulnerable' and not recommended for use.

2. Cipher Block Chaining Mode: This mode is required to add the feeback to modify the pre-encrypted data; with the feedback it will make each cipher data different from previous result. This mode is commonly used to secure applications.

3. Cipher Feedback Mode: This mode works like a Stream Cipher where data being processed can be shorter values rather than a larger block. In this mode, instead of passing the data to AES, it gets the XORed value that is generated from AES engine on the basis of previous message history. Here only XOR function is applied to the data and returns the smaller widths of data as compared to block size.

4. Output Feedback Mode: This mode is quite similar with Cipher Feedback Mode, but does not use the Stream Cipher due to the weakness when the data width that doesn't match the blocksize of encryption algorithm.

5. Counter Mode: This mode is also very common and used in to secure an application where count value of blocksized is maintained and encrypted using XOR. 

I'm going to use the C# Console Application in order to test AES algorithm different approaches. In this post I'm going to define two techniques of AES algorithm in order to Encrypt - Decrypt data.

1. First Technique: Using Aes Class which is inherited from SymmetricAlgorithm

Main Method:


const string original = "Here is some data to encrypt!";
Console.WriteLine("Data to encypt/decrypt: " + original + "\n");

Console.WriteLine("New Technique");

// Create a new instance of the Aes class. This generates a new key and initialization vector (IV)
using (var aes = Aes.Create())
{
    if (aes == null) return;
    // Encrypt the string to an array of bytes
    var encrypted = AesMode.NewEncryptMethod(original, aes.Key, aes.IV);

    // Decrypt the bytes to a string 
    var decrypted = AesMode.NewDecryptMethod(encrypted, aes.Key, aes.IV);

    //Display the encrypted data and the decrypted data
    Console.WriteLine("Encrypted: {0}", Convert.ToBase64String(encrypted));
    Console.WriteLine("Decrypted: {0}", decrypted);
}

Classes Used:


public static byte[] NewEncryptMethod(string plainText, byte[] key, byte[] iv)
{
    // Check arguments. 
    if (plainText == null || plainText.Length <= 0)
        throw new ArgumentNullException("plainText");
    if (key == null || key.Length <= 0)
        throw new ArgumentNullException("key");
    if (iv == null || iv.Length <= 0)
        throw new ArgumentNullException("key");
    byte[] encrypted = { };

    // Create an Aes object with the specified key and IV
    using (var aes = Aes.Create())
    {
        if (aes == null) return encrypted;
        aes.Key = key;
        aes.IV = iv;

        // Create a decrytor to perform the stream transform.
        var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

        // Create the streams used for encryption. 
        using (var msEncrypt = new MemoryStream())
        {
            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    //Write all data to the stream.
                    swEncrypt.Write(plainText);
                }

                encrypted = msEncrypt.ToArray();
            }
        }
    }

    // Return the encrypted bytes from the memory stream. 
    return encrypted;
}

public static string NewDecryptMethod(byte[] cipherText, byte[] key, byte[] iv)
{
    // Check arguments. 
    if (cipherText == null || cipherText.Length <= 0)
        throw new ArgumentNullException("cipherText");
    if (key == null || key.Length <= 0)
        throw new ArgumentNullException("key");
    if (iv == null || iv.Length <= 0)
        throw new ArgumentNullException("key");

    // Declare the string used to hold 
    // the decrypted text. 
    string plainText;

    // Create an Aes object 
    // with the specified key and IV. 
    using (var aes = Aes.Create())
    {
        if (aes == null) return null;
        aes.Key = key;
        aes.IV = iv;

        // Create a decrytor to perform the stream transform.
        var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

        // Create the streams used for decryption. 
        using (var msDecrypt = new MemoryStream(cipherText))
        {
            using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (var srDecrypt = new StreamReader(csDecrypt))
                {
                    // Read the decrypted bytes from the decrypting stream and place them in a string
                    plainText = srDecrypt.ReadToEnd();
                }
            }
        }
    }

    return plainText;
}

2. Second Technique: Using Cipher Mode "ECB" and a priavate key


Main Method:


const string original = "Here is some data to encrypt!";
Console.WriteLine("Data to encypt/decrypt: " + original + "\n");

Console.WriteLine("\nOld Technique");

var encryptData = AesMode.OldEncryptMethod(original);
var decryptData = AesMode.OldDecryptMethod(encryptData);

//Display the encrypted data and the decrypted data
Console.WriteLine("Encrypted: {0}", encryptData);
Console.WriteLine("Decrypted: {0}", decryptData);

Classes Used:

// A key used to encode and later decode the data
private const string PrivateKey = "@pRiVaTeKeY123";

/// <summary>
/// OldEncryptMethod
/// </summary>
/// <param name="plainData">Contains plain data to encrypt</param>
/// <returns>Encrypt Data</returns>
public static string OldEncryptMethod(string plainData)
{
    byte[] result;
    var utf8Encoding = new UTF8Encoding();
    var hashProvider = new MD5CryptoServiceProvider();
    var tDesKey = hashProvider.ComputeHash(utf8Encoding.GetBytes(PrivateKey));
    var tDesAlgorithm = new TripleDESCryptoServiceProvider
    {
        Key = tDesKey,
        Mode = CipherMode.ECB,
        Padding = PaddingMode.PKCS7
    };

    var dataToEncrypt = utf8Encoding.GetBytes(plainData);

    try
    {
        var encryptor = tDesAlgorithm.CreateEncryptor();
        result = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
    }
    finally
    {
        tDesAlgorithm.Clear();
        hashProvider.Clear();
    }

    return Convert.ToBase64String(result);
}

/// <summary>
/// OldDecryptMethod
/// </summary>
/// <param name="encryptData">Contains encrypt data to decrypt</param>
/// <returns>Decrypt Data</returns>
public static string OldDecryptMethod(string encryptData)
{
    byte[] results;
    var utf8Encoding = new UTF8Encoding();
    var hashProvider = new MD5CryptoServiceProvider();
    var tDesKey = hashProvider.ComputeHash(utf8Encoding.GetBytes(PrivateKey));
    var tDesAlgorithm = new TripleDESCryptoServiceProvider
    {
        Key = tDesKey,
        Mode = CipherMode.ECB,
        Padding = PaddingMode.PKCS7
    };

    var dataToDecrypt = Convert.FromBase64String(encryptData);

    try
    {
        var decryptor = tDesAlgorithm.CreateDecryptor();
        results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
    }
    finally
    {
        tDesAlgorithm.Clear();
        hashProvider.Clear();
    }

    return utf8Encoding.GetString(results);
}

Hope it helps you to perform your action in fast pace. Stay tuned!