.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Encryption & Decryption >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Encryption and Decryption in C#

Posted By:Abhisek Panda       Posted Date: October 26, 2009    Points: 10    Category: Encryption & Decryption    URL: http://www.dotnetspark.com  
 

Encryption and Decription



The following program demonstrates how to encrypt or decrypt data using C#. It follows 64 bit encryption technology. You can use this code in your program to Encrypt your passwords or some important data.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace EncryptDecrypt

{

public class EncryptDecrypt

{

const char fillchar = '=';

static string cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

//Method to encrypt data

static public string Encode(string data)

{

int i;

int c;

int len = data.Length;

string ret = "";

for (i = 0; i < len; ++i)

{

c = (data >> 2) & 0x3f;

ret += cvt[c];

c = (data << 4) & 0x3f;

if (++i < len)

c |= (data >> 4) & 0x0f;

ret += cvt[c];

if (i < len)

{

c = (data << 2) & 0x3f;

if (++i < len)

c |= (data >> 6) & 0x03;

ret += cvt[c];

}

else

{

++i;

ret += fillchar;

}

if (i < len)

{

c = data & 0x3f;

ret += cvt[c];

}

else

{

ret += fillchar;

}

}

return (ret);

}



//Method to decrypt the data

static public string Decode(string data)

{

string ret = "";

int i;

char c;

char c1;

int len = data.Length;

for (i = 0; i < len; ++i)

{

c = (char)cvt.IndexOf(data);

++i;

c1 = (char)cvt.IndexOf(data);

c = ((char)((c << 2) | ((c1 >> 4) & 0x3)));

ret += c;

if (++i < len)

{

c = data;

if (fillchar == c)

break;

c = (char)cvt.IndexOf(c);

c1 = (char)(((c1 << 4) & 0xf0) | ((c >> 2) & 0xf));

ret += c1;

}

if (++i < len)

{

c1 = data;

if (fillchar == c1)

break;

c1 = (char)cvt.IndexOf(c1);

c = (char)(((c << 6) & 0xc0) | c1);

ret += c;

}

}

return (ret);

}

}

}



In the above code there are two methods, Encode() which encrypts the string passed to it and Decode() which decrypt the encrypted string passed to it.


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend