Friday, 25 July 2014

Using AES encryption in C#

What is AES  ?

The Advanced Encryption Standard (AES) is a specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology (NIST) in 2001.[4]


AES is based on the Rijndael cipher[5] developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen, who submitted a proposal to NIST during the AES selection process.[6] Rijndael is a family of ciphers with different key and block sizes.

For AES, NIST selected three members of the Rijndael family, each with a block size of 128 bits, but three different key lengths: 128, 192 and 256 bits.


Using AES encryption in C#

1. Encrypting data :

The following function takes 3 parameters
    1-The first parameter is byte array of the data that has to be encrypted .
    2-The second parameter is the key that will be used to encrypt the data
    3-Third parameter is the initialization vector .
The function returns the encrypted byte array .

AesCryptoServiceProvider :

Performs symmetric encryption and decryption using the Cryptographic Application Programming Interfaces (CAPI) implementation of the Advanced Encryption Standard (AES) algorithm.


CreateEncryptor :  This function takes key and IV to create a symmetric encryptor object with the current Key property and initialization vector (IV) . If Key or IV is null the GenerateKey method is called to create a new random Key or IV .

 public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)  
     {  
       AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();  
       //Block size : Gets or sets the block size, in bits, of the cryptographic operation.  
       dataencrypt.BlockSize = 128;  
       //KeySize: Gets or sets the size, in bits, of the secret key  
       dataencrypt.KeySize = 128;  
       //Key: Gets or sets the symmetric key that is used for encryption and decryption.  
       dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
       //IV : Gets or sets the initialization vector (IV) for the symmetric algorithm  
       dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
       //Padding: Gets or sets the padding mode used in the symmetric algorithm  
       dataencrypt.Padding = PaddingMode.PKCS7;  
       //Mode: Gets or sets the mode for operation of the symmetric algorithm  
       dataencrypt.Mode = CipherMode.CBC;  
       //Creates a symmetric AES encryptor object using the current key and initialization vector (IV).  
       ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);  
       //TransformFinalBlock is a special function for transforming the last block or a partial block in the stream.   
       //It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of   
       //information returned at the end might be larger than a single block when padding is added.  
       byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);  
       crypto1.Dispose();  
       //return the encrypted data  
       return encrypteddata;  
     }  

Decrypting data :

 The following function takes 3 parameters
    1-The first parameter is byte array of the data that has to be decrypted .
    2-The second parameter is the key that will be used to decrypt the data
    3-Third parameter is the initialization vector .
The function returns the decrypted byte array .


     private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)  
     {  

       AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();  
       keydecrypt.BlockSize = 128;  
       keydecrypt.KeySize = 128;  
       keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
       keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
       keydecrypt.Padding = PaddingMode.PKCS7;  
       keydecrypt.Mode = CipherMode.CBC;  
       ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);  
      
       byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);  
       crypto1.Dispose();  
       return returnbytearray;  
     }  

Monday, 14 July 2014

Simulating Key Press in C#

Simulating a key press or a combination of keys in c# can be done using the keybd_event() function .  This function is useful to simulate Key presses to the window with focus .


C# Signature:

[DllImport("user32.dll")]  
  public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo); 

Parameters

bVk [in]
Type: BYTE
A virtual-key code. The code must be a value in the range 1 to 254. For a complete list, see Virtual Key Codes.
bScan [in]
Type: BYTE
A hardware scan code for the key.
dwFlags [in]
Type: DWORD
Controls various aspects of function operation. This parameter can be one or more of the following values.

ValueMeaning

KEYEVENTF_EXTENDEDKEY
0x0001
If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224).

KEYEVENTF_KEYUP
0x0002
If specified, the key is being released. If not specified, the key is being depressed.


dwExtraInfo [in]
Type: ULONG_PTR
An additional value associated with the key stroke.

Return value

This function does not return a value.


Example 1 : The following code will simulate the pressing of keyboard button "A" . 
//import the dll 
//put this code when the class starts
[DllImport("user32.dll")]  
  public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);  
 const uint KEYEVENTF_EXTENDEDKEY = 0x0001;  
 // call this function when you want to simulate the key press .  
 // presses the key  
  keybd_event((byte)Keys.A, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
  Thread.Sleep(200);  
 //releases the key  
  keybd_event((byte)Keys.A, 0, 2, 0);  



Example 2 : The following code will simulate the pressing of keyboard button "\" (backslash). 
VkKeyScan function : This function function translates a character to the corresponding virtual-key code and shift state for the current keyboard .

C# Signature:

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern short VkKeyScan(char ch);



//import the dll   
 //put this code when the class starts  
 [DllImport("user32.dll")]  
  public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);  
 const uint KEYEVENTF_EXTENDEDKEY = 0x0001;  
 [DllImport("user32.dll")]  
  public static extern short VkKeyScan(char z);  
 // call this function when you want to simulate the key press .  
 // presses the key  
  keybd_event((byte)VkKeyScan('\\'), 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
 Thread.Sleep(200);  
 //releases the key  
  keybd_event((byte)VkKeyScan('\\'), 0, 2, 0);  

Simulating combination of key presses .

The following code will Open task manager by pressing control , shift and escape and then releasing all the keys .

//pressing keys

 keybd_event((byte)Keys.RControlKey, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
 keybd_event((byte)Keys.RShiftKey, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
 keybd_event((byte)Keys.Escape, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);  
 //releasing all keys
 keybd_event((byte)Keys.Escape, 0, 2, 0);  
  keybd_event((byte)Keys.RShiftKey, 0, 2, 0);  
  keybd_event((byte)Keys.RControlKey, 0, 2, 0);