Encryption and Decryption in C# – Data Encryption Standard (DES) Algorithm

In cryptography, Encryption is the process of encoding messages or information in such a way that only authorized parties can read it. It requires some secret information to transform the plain text to cipher text; it is usually referred as key.

Decryption is the process of converting encrypted data back into its original form, so it can be understood

There are many modern cryptographic methods used for encryption and decryption and it is classified in to two classes of key based algorithms.

1.     Symmetric Algorithm 

a.    Same key is used for both Encryption and Decryption. The key will be kept as secret.

b.     Symmetric Ciphers is divided into Stream and Block Ciphers.

i.      Stream Ciphers – It encrypts a single bit of plain text at a time.

ii.      Block Ciphers –    It takes number of bits and encrypts them as a single unit.

2.       Asymmetric Algorithm

a.       Different key is used for Encryption and Decryption. It is also called as public Key algorithm.

b.      Encryption key is public and the Decryption key will be kept as secret.

c.       By using this asymmetric algorithm, anyone can encrypt the message by using encryption key but the message can be decrypted only by using decryption key.

3.       Hybrid Encryption – Symmetric and Asymmetric algorithm are used together and it is called as Hybrid Encryption.

Algorithm Requirements:

1.       The Key will be kept secret and should be Random.

2.       It should not be possible to find the key even if the plain text and Cipher text are known.

 Types of Symmetric Encryption Algorithm:

1.       Data Encryption Standard (DES)

2.       Triple DES (3DES)

3.       Advanced Encryption Standard (AES)

Below is the example for encryption and decryption in C# using Triple DES algorithm.

using System.IO;
using System.Security;
using System.Security.Cryptography;
Public class Program
{
static void Main(string[] args)
{
var text = “This is Plain Text”;

var encryptedText = CryptoGraphyExample.EncryptPlainTextToCipherText(text);
var decryptedText = CryptoGraphyExample.DecryptCipherTextToPlainText(encryptedText);

Console.WriteLine(“Passed Text = ” + text);
Console.WriteLine(“EncryptedText = ” + encryptedText);
Console.WriteLine(“DecryptedText = ” + decryptedText);

Console.ReadLine();
}
}

public class CryptoGraphyExample
{
/// <summary>
/// This security key should be very complex and Random for encrypting the text. This playing vital role in encrypting the text.
/// </summary>
private const string _securityKey = “MyComplexPrivateKey”;

/// <summary>
/// This method is used to convert the plain text to Encrypted/Un-Readable Text format.
/// </summary>
/// <param name=”PlainText”>Plain Text to Encrypt before transferring over the network.</param>
/// <returns>Cipher Text</returns>
public static string EncryptPlainTextToCipherText(string PlainText)
{
//Getting the bytes of Input String.
byte[] toEncryptedArray = UTF8Encoding.UTF8.GetBytes(PlainText);

MD5CryptoServiceProvider objMD5CryptoService = new MD5CryptoServiceProvider();

//Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(_securityKey));

//De-allocatinng the memory after doing the Job.
objMD5CryptoService.Clear();

var objTripleDESCryptoService = new TripleDESCryptoServiceProvider();

//Assigning the Security key to the TripleDES Service Provider.
objTripleDESCryptoService.Key = securityKeyArray;

//Mode of the Crypto service is Electronic Code Book.
objTripleDESCryptoService.Mode = CipherMode.ECB;

//Padding Mode is PKCS7 if there is any extra byte is added.
objTripleDESCryptoService.Padding = PaddingMode.PKCS7;

var objCrytpoTransform = objTripleDESCryptoService.CreateEncryptor();

//Transform the bytes array to resultArray
byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptedArray, 0, toEncryptedArray.Length);

//Releasing the Memory Occupied by TripleDES Service Provider for Encryption.
objTripleDESCryptoService.Clear();

//Convert and return the encrypted data/byte into string format.
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

/// <summary>
/// This method is used to convert the Cipher/Encypted text to Plain Text.
/// </summary>
/// <param name=”CipherText”>Encrypted Text</param>
/// <returns>Plain/Decrypted Text</returns>
public static string DecryptCipherTextToPlainText(string CipherText)
{
byte[] toEncryptArray = Convert.FromBase64String(CipherText);

MD5CryptoServiceProvider objMD5CryptoService = new MD5CryptoServiceProvider();

//Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(_securityKey));

//De-allocatinng the memory after doing the Job.
objMD5CryptoService.Clear();

var objTripleDESCryptoService = new TripleDESCryptoServiceProvider();

//Assigning the Security key to the TripleDES Service Provider.
objTripleDESCryptoService.Key = securityKeyArray;

//Mode of the Crypto service is Electronic Code Book.
objTripleDESCryptoService.Mode = CipherMode.ECB;

//Padding Mode is PKCS7 if there is any extra byte is added.
objTripleDESCryptoService.Padding = PaddingMode.PKCS7;

var objCrytpoTransform = objTripleDESCryptoService.CreateDecryptor();

//Transform the bytes array to resultArray
byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

//Releasing the Memory Occupied by TripleDES Service Provider for Decryption.
objTripleDESCryptoService.Clear();

//Convert and return the decrypted data/byte into string format.
return UTF8Encoding.UTF8.GetString(resultArray);
}
}

Handling Errors in SQL Server (Try Catch & Transactions)

During development of any application, one of the most common things we need to take care of is Exception and Error handling.

TRY…CATCH blocks are the standard approach to exception handling in modern programming languages. Use and syntax are likely the same as normal programming language. Like Exception Handling in Programming Language, we can use nested Try-Catch block in SQL Server also.

Try block will catch the error and will throw it in the Catch block. Catch block then handles the scenario.

trycatch

TRANSACTIONS group a set of tasks into a single execution unit. Each transaction begins with a specific task and ends when all the tasks in the group successfully complete. If any of the tasks fails, the transaction fails. Therefore, a transaction has only two results: success or failure. Incomplete steps result in the failure of the transaction.

Users can group two or more Transact-SQL statements into a single transaction using the following statements:

  • Begin Transaction
  • Rollback Transaction
  • Commit Transaction

If anything goes wrong with any of the grouped statements, all changes need to be aborted. The process of reversing changes is called rollback in SQL Server terminology. If everything is in order with all statements within a single transaction, all changes are recorded together in the database. In SQL Server terminology, we say that these changes are committed to the database.

Example :

CREATE PROCEDURE UpdateSales
  @SalesPersonID INT,
  @SalesAmt MONEY = 0
AS
BEGIN

  BEGIN TRY
    BEGIN TRANSACTION;
      UPDATE SalesData
      SET SalesLastYear = SalesLastYear + @SalesAmt
      WHERE SalesPersonID = @SalesPersonID;
    COMMIT TRANSACTION;
  END TRY

  BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;

    -- @@TRANCOUNT returns number of active Transactions,
    -- BEGIN TRANSACTION will increment the transaction count by 1 & 
    -- COMMIT TRANSACTION will decrement the transaction count by 1
    DECLARE @ErrorNumber INT = ERROR_NUMBER();
    DECLARE @ErrorLine INT = ERROR_LINE();
    DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
    DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
    DECLARE @ErrorState INT = ERROR_STATE();

    PRINT 'Actual error number: ' + CAST(@ErrorNumber AS VARCHAR(10));
    PRINT 'Actual line number: ' + CAST(@ErrorLine AS VARCHAR(10));

    RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
  END CATCH

END

Authentication using LDAP (Active Directory) for ASP.NET applications

Authentication: The process of identifying an individual, usually based on a username and password.

Generally every applications needs user authentication and we have few ways

(Forms Authentication, Windows Authentication & Passport Authentication)

to authenticate the users in web applications. Most of the intranet asp.net web applications authenticate the users against active directory by using windows user name and passwords.

The main benefit of this LDAP (lightweight directory access protocol) authentication is application users do not maintain separate user name and password for each application. Users can able to use their windows user name and password for all application.

Namespace details:

System.DirectoryServices library plays main role on this functionality, this takes the user’s user name and password and validating against windows active directory.

Example:

using System.DirectoryServices;

String adPath = “LDAP://uzval.com”;

String DomainName = “uzval”;

public bool IsAuthenticated(string adPath, string domain, string username, string pwd)

{

string wholeString = username;

string firstBit = wholeString.Split(‘@’)[0];

username = firstBit;

string domainAndUsername = domain + @”\” + username;

DirectoryEntry entry = new DirectoryEntry(adPath, domainAndUsername, pwd);

try

{

//Bind to the native AdsObject to force authentication.

object obj = entry.NativeObject;

DirectorySearcher search = new DirectorySearcher(entry);

search.Filter = “(SAMAccountName=” + username + “)”;

//UserId

search.PropertiesToLoad.Add(“SAMAccountName”);

//CN or Display Name

search.PropertiesToLoad.Add(“cn”);

//Status

search.PropertiesToLoad.Add(“userAccountControl”);

SearchResult result = search.FindOne();

if (null == result)

{

return false;

}

else

{

Session[“ADUserID”] = string.Empty;

Session[“ADUserName”] = string.Empty;

Session[“ADuserAccountControl”] = string.Empty;

//ADUser UserId

Session[“ADUserID”] = result.Properties[“SAMAccountName”][0];

//AD UserName

Session[“ADUserName”] = result.Properties[“cn”][0];
//AD ENABLE/DISABLE Status Flag

                Session[“ADuserAccountControl”] = Convert.ToString(result.Properties[“userAccountControl”][0]);

//User Account Control values

//Allow all these ID’s to login- 512,544,4096,66048,590336,532480

//512 – Enable Account

//514 – Disable account

//544 – Account Enabled – Require user to change password at first logon

//4096 – Workstation/server

//66048 – Enabled, password never expires

//590336 – Enabled, User Cannot Change Password, Password Never Expires

//66050 – Disabled, password never expires

//262656 – Smart Card Logon Required

//532480 – Domain controller

}

}

catch (Exception ex)

{

return false;

//throw new Exception(“Error authenticating user. ” + ex.Message);

}

return true;

}

2015 in Review – Wish You Happy New Year

Wish You Happy Happy Happy New Year,

Time is free, but it’s priceless.
You can’t own it, but you can use it.
You can’t keep it, but you can spend it.
Once you’ve lost it, you can never get it back…

Years, Months, Weeks, Days, Hours , Minutes, Seconds… Its Transforming…

Hope we utilise our Time for well-being in a constructive way & we all have Good Health, Relationships, Prosperity, Contentment & Happiness.

Annual Report – 2015 for this blog

Here’s an excerpt:

In 2015 this blog was viewed about 5,300 times,

there were only 2 new posts,

The busiest day of the year was Apr 29th with 83 views.

Visitors are from 69 countries in all!

Most visitors came from India. The United States & The Srilanka.

DEFAULT Constraint – Adding Column Defaulting in Sql Server Table

The DEFAULT constraint is used to insert a default value into a column.

The default value will be added to all new records, if no other value is specified.

Rather than providing a value into a column manually during insert operation, by using default option we can auto-populate specific value and update in column.

in the below example, no need to provide CreatedDate and Freezed values during Insertion .

Example :

create table TestTable
(
Id int IDENTITY(1,1) NOT NULL,
UserId int,

—–

—–
CreatedDate datetime default (getdate()),
Freezed int default (0)
)

Comma separated / delimited string to a table in SQL Server

Recently, I came across a piece of TSQL code that would take a comma separated string as an input and parse it to return a single column table from it.
CREATE FUNCTION [dbo].[UDF_string_to_table]

(
@string VARCHAR(8000),
@delimiter CHAR(1)
)
RETURNS @output TABLE(CommaSeparatedString VARCHAR(256))

BEGIN

DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)

WHILE @start < LEN(@string) + 1 BEGIN
IF @end = 0
SET @end = LEN(@string) + 1

INSERT INTO @output (CommaSeparatedString) VALUES(SUBSTRING(@string, @start, @end – @start))

SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
END

RETURN
END

Output:

select * from UDF_string_to_table(‘1,2,3′,’,’)

2014 in Review

Wish You Happy New Year, Just received this years corporate diary, it has… ” Every mountain top is within reach if you just keep climbing “ Annual Report – 2014 for this blog Here’s an excerpt: In 2014 this blog was viewed about 5,300 times, there were only 4 new posts, growing the total archive of this blog to 90 posts. There were 2 pictures uploaded, The busiest day of the year was Dec 3rd with 53 views. Visitors are from 96 countries in all! Most visitors came from India. The United States & The Brazil.