Tuesday, August 25, 2009

Encryption and Decryption without .net APIs

This code is for encrypting and then decrypting any string. here we use teo strings NORMAL and ENCRYPT. in this method we pick characters from input and and get its index from NORMAL string and character at the same index in ENCRYPT string is replaces by original character. reverse process is used for decryption.

string NORMAL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string ENCRYPT = "YO17KPLVSU50C8WE64GAI3MB2DFNZQ9JXTRH";
string strInput = "NikhilGaur";
string strEncrypted = string.Empty;
string strDecrypted = string.Empty;
string strNewChar;
string strLtr;
int iIdx;
protected EncryptionDecryptionDemo()
{
Response.Write("Original String : " + strInput);
Response.Write("
");
for (int i = 0; i < strInput.Length; i++)
{
strLtr = strInput.Substring(i, 1).ToUpper();
iIdx = NORMAL.IndexOf(strLtr);
strNewChar = ENCRYPT.Substring(iIdx, 1).ToUpper();
strEncrypted += strNewChar;
}
Response.Write("Encrypted string : " + strEncrypted);
Response.Write("
");

for (int i = 0; i < strInput.Length; i++)
{
strLtr = strEncrypted.Substring(i, 1).ToUpper();
iIdx = ENCRYPT.IndexOf(strLtr);
strNewChar = NORMAL.Substring(iIdx, 1).ToUpper();
strDecrypted += strNewChar;
}
Response.Write("Decrypted string(Original again :" + strDecrypted);
}

If you want to use any special characters you can add in variable "NORMAL" and equivalent encrypted value in variable "ENCRYPT".
"ENCRYPT" variable has the reordered letters of "NORMAL" variable.

No comments: