Archive

Tag Archives: DECRYPTION

One of the way to protect the data of the user visiting your website or accessing you application through network is by using SSL. SSL Also know as Secure Socket Layer. SSL was first developed by netscape. It was enhanced from version 1.0 to 3.0. Its latest version is known as TLS (Transport Layer Security) 1.2. for further details visit

http://en.wikipedia.org/wiki/Transport_Layer_Security

From the framework 2.0 it is also provided as the part of the libraries and with that we can develop our server or client application further on that. The class used for purpose is SslStream and it available in System.Net.Security namspace. For developing a server running on SSL we need a SSL certificate which contains the public and the private key. Sample for the server and the client application with complete information on the SslStream class is available in MSDN

http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx

In the 2 Part of this post i will try to put a sample application(server and client) working on the SSL

Here is one sample class which can be used for 4 different kind of symmetric encryption
1. DES
2. RC2
3. Rijndeal
4. TripleDES


Before using the class there is one important thing to know which is the size of the key. It varies as you change the encryption type for example

  • DES support 64 bits.
  • RC2 40 to 128 Bits with increment of 8 Bits only.
  • Rijndeal support key lengths of 128, 192, or 256 bits.
  • and TripleDES supports 128 bits to 192 bits in increments of 64 bits.
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Crypto
{
    public enum SymmetricAlgorimthType{ DES, RC2, Rijndael, TripleDES };

    class SymmetricCryptogarphy    
    {
        private SymmetricAlgorimthType _algorithmType = 
SymmetricAlgorimthType.DES;

        public SymmetricCryptogarphy(SymmetricAlgorimthType algorithmKey)
        {
            _algorithmType = algorithmKey;
        }

        public SymmetricAlgorimthType AlgorithmType
        {
            get { return _algorithmType; }
        }

        public SymmetricAlgorithm GenerateKey()
        {
            SymmetricAlgorithm algoKey;

            algoKey = GetCryptoServiceProvider(_algorithmType);
            algoKey.GenerateKey();
            algoKey.GenerateIV();
            return algoKey;
        }

        public SymmetricAlgorithm GenerateKey(int keySize)
        {
            SymmetricAlgorithm algoKey;

            algoKey = GetCryptoServiceProvider(_algorithmType);
            algoKey.KeySize = keySize;
            algoKey.GenerateKey();
            algoKey.GenerateIV();
            return algoKey;
        }

        public SymmetricAlgorithm GenerateKey(int blockSize, int keySize)
        {
            SymmetricAlgorithm algoKey;

            algoKey = GetCryptoServiceProvider(_algorithmType);

            algoKey.BlockSize = blockSize;
            algoKey.KeySize = keySize;
            algoKey.GenerateKey();
            algoKey.GenerateIV();
            return algoKey;
        }

        public byte[] EncryptData(SymmetricAlgorithm key, string data)
        {
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream encStream = new CryptoStream(memoryStream,
              key.CreateEncryptor(), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(encStream);

            sw.WriteLine(data);
            sw.Close();
            encStream.Close();

            byte[] buffer = memoryStream.ToArray();
            memoryStream.Close();

            return buffer;
        }

        public string DecryptData(SymmetricAlgorithm key, byte[] data)
        {
            MemoryStream memoryStream = new MemoryStream(data);

            CryptoStream encStream = new CryptoStream(memoryStream,
              key.CreateDecryptor(),CryptoStreamMode.Read);
              StreamReader sr = new StreamReader(encStream);

            string val = sr.ReadLine();
            sr.Close();
            encStream.Close();
            memoryStream.Close();

            return val;
        }

        private SymmetricAlgorithm GetCryptoServiceProvider(SymmetricAlgorimthType algorithmType)
        {
            switch (algorithmType)
            {
                case SymmetricAlgorimthType.DES:
                    return new DESCryptoServiceProvider();
                case SymmetricAlgorimthType.RC2:
                    return new RC2CryptoServiceProvider();
                case SymmetricAlgorimthType.Rijndael:
                    return new RijndaelManaged();
                case SymmetricAlgorimthType.TripleDES:
                    return new TripleDESCryptoServiceProvider();
                default:
                    return new DESCryptoServiceProvider();
            }
        }
    }
}

This time we will perform RSA Encryption(Asymmetric encryption) with the help of the RSACryptoServiceProvider Class. Now its key length depends upon the Cryptographic Provider you have. For MS Base Cryptographic Provider you can have key length from 384 to 512 bits in increment of 8 bits where as if you have installed MS Enhanced Cryptographic Provider then you can have key of 384 to 16384 bits in increment of 8 bits.


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

class CryptRSA    
{

static void main()
{
UnicodeEncoding bytConvertor = new UnicodeEncoding();
byte[] plainData = bytConvertor.GetBytes("Sample data");
RSACryptoServiceProvider RSAServiceProvider = new RSACryptoServiceProvider();

byte[] enData = Encrypt(plainData, RSAServiceProvider.ExportParameters(false));
Console.WriteLine("Encrypted Output: {0}", bytConvertor.GetString(enData));

byte[] deData = Decrypt(enData, RSAServiceProvider.ExportParameters(true));
Console.WriteLine("Decrypted Output: {0}", bytConvertor.GetString(deData));
}

static private byte[] Encrypt(byte[] DataToEncrypt, RSAParameters keyInfo)
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.ImportParameters(keyInfo);
return RSA.Encrypt(DataToEncrypt, false);
}

static private byte[] Decrypt(byte[] DataToDecrypt, RSAParameters keyInfo)
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.ImportParameters(keyInfo);
return RSA.Decrypt(DataToDecrypt, false);
}
}

Doing Encryption with various well know algorithm is not so easy. Writing those and managing is bit difficult. But microsoft provides assemblies/libraries and built in classes with the help of which you can peform encryption with even writting single code of encryption algorithm. 

There are two major kind of encryptions

1. Secret Key (Also know as Symmetric encryption since single key is used to encrypt and decrypt the data)

Here single shared key is maintained to secure the data from unauthorised access. These keys are used to perform the encryption and decryption of the data

2. Public Key

Here a pair of public and private key used in order to secure the data.

Now we will see example of Secret Key Encryption/Decryption (DES)


// Encrypt the string.

private void button1_Click(object sender, EventArgs e)
{
DESCryptoServiceProvider key = new DESCryptoServiceProvider();
byte[] buffer = Encrypt(textBox1.Text, key);
textBox2.Text = bytestostring(buffer);
textBox3.Text = Decrypt(buffer, key);
}

public static byte[] Encrypt(string PlainText, SymmetricAlgorithm key)
{
// Create a memory stream.
MemoryStream ms = new MemoryStream();

// Create a CryptoStream using the memory stream and the
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);

// Create a StreamWriter to write a string
// to the stream.
StreamWriter sw = new StreamWriter(encStream);

// Write the plaintext to the stream.
sw.WriteLine(PlainText);

// Close the StreamWriter and CryptoStream.
sw.Close();
encStream.Close();

// Get an array of bytes that represents
// the memory stream.
byte[] buffer = ms.ToArray();

// Close the memory stream.
ms.Close();

// Return the encrypted byte array.
return buffer;
}

// Decrypt the byte array.
public static string Decrypt(byte[] CypherText, SymmetricAlgorithm key)
{
// Create a memory stream to the passed buffer.
MemoryStream ms = new MemoryStream(CypherText);

// Create a CryptoStream using the memory stream and the
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);

// Create a StreamReader for reading the stream.
StreamReader sr = new StreamReader(encStream);

// Read the stream as a string.
string val = sr.ReadLine();

// Close the streams.
sr.Close();
encStream.Close();
ms.Close();

return val;
}

Here make sure that the key for the encryption and the decryption should be same in order to make it work properly. More on this will be posted soon.

Follow

Get every new post delivered to your Inbox.