Encryption and Decryption in C#
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.