Sunday, July 5, 2009

Encrypt and Decrypt a String in C# using Cryptography

I am going to explain how to encrypt and decrypt a string in C# using Cryptography and by generating an MD5 hash from the password.

First of all we need to add System.Security.Cryptography; namespace in our code, I am going to create a class with two Methods

1) Encrypter
2) Decrypter

Encrypter used to encrypt a string and Decrypter used to descrypt the string encrypted by Encrypter.

Here is this beautiful class. Its a competetely implemented Class, what all you need to do is just Copy and Paste.

public class EncryptDecrypt
{
public EncryptDecrypt()
{
//
// TODO: Add constructor logic here
//
}

public string Encrypter(string strStringToEncrypt)
{
string strOriginal, strEncryptedString, password;
TripleDESCryptoServiceProvider des;
MD5CryptoServiceProvider hashmd5;
byte[] pwdhash, buff;

//create a secret password. the password is used to encrypt and decrypt
//strings. Without the password, the encrypted string cannot be
//decrypted and is just garbage. You must use the same password to
//decrypt an encrypted string as the string was originally encrypted with.

password = "manojjoshi";

//create a string to encrypt
//original = "String to encrypt";

strOriginal = strStringToEncrypt;

//generate an MD5 hash from the password.a hash is a one way
//encryption meaning once you generate the hash, you cant derive the
//password back from it.

hashmd5 = new MD5CryptoServiceProvider();
pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
hashmd5 = null;

//implement DES3 encryption
des = new TripleDESCryptoServiceProvider();

//the key is the secret password hash.
des.Key = pwdhash;

//the mode is the block cipher mode which is basically the details of how
//the encryption will work. There are several kinds of ciphers available in
//DES3 and they all have benefits and drawbacks. Here the Electronic
//Codebook cipher is used which means that it encrypt each
//block individually and a given bit of text is always encrypted exactly the
// same when the same password is used.

des.Mode = CipherMode.ECB; //CBC, CFB


//----- encrypt an un-encrypted string ------------
//the original string, which needs encrypted, must be in byte array
//form to work with the des3 class. everything will because most encryption
//works at the byte level so you'll find that the class takes in byte
//arrays and returns byte arrays and you'll be converting
//those arrays to strings.

buff = ASCIIEncoding.ASCII.GetBytes(strOriginal);

//encrypt the byte buffer representation of the original string and base64
//encode the encrypted string. The reason the encrypted bytes are being
//base64 encoded as string is the encryption will have created some weird
//characters in there. Base64 encoding provides a platform independent view
//of the encrypted string and can be sent as a plain text string to wherever.

strEncryptedString = Convert.ToBase64String(
des.CreateEncryptor().TransformFinalBlock(buff, 0, buff.Length)
);

return strEncryptedString;
}

public string Decrypter(string StrEncryptedString)
{
string decrypted, password;
TripleDESCryptoServiceProvider des;
MD5CryptoServiceProvider hashmd5;
byte[] pwdhash, buff;

//create a secret password. the password is used to encrypt
//and decrypt strings. Without the password, the encrypted
//string cannot be decrypted and is just garbage. You must
//use the same password to decrypt an encrypted string as the
//string was originally encrypted with.
password = "manojjoshi

//generate an MD5 hash from the password.
//a hash is a one way encryption meaning once you generate
//the hash, you cant derive the password back from it.
hashmd5 = new MD5CryptoServiceProvider();
pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
hashmd5 = null;

//implement DES3 encryption
des = new TripleDESCryptoServiceProvider();

//the key is the secret password hash.
des.Key = pwdhash;

//the mode is the block cipher mode which is basically the
//details of how the encryption will work. There are several
//kinds of ciphers available in DES3 and they all have benefits
//and drawbacks. Here the Electronic Codebook cipher is used
//which means that a given bit of text is always encrypted
//exactly the same when the same password is used.
des.Mode = CipherMode.ECB; //CBC, CFB


//----- decrypt an encrypted string ------------
//whenever you decrypt a string, you must do everything you
//did to encrypt the string, but in reverse order. To encrypt,
//first a normal string was des3 encrypted into a byte array
//and then base64 encoded for reliable transmission. So, to
//decrypt this string, first the base64 encoded string must be
//decoded so that just the encrypted byte array remains.
buff = Convert.FromBase64String(StrEncryptedString);

//decrypt DES 3 encrypted byte buffer and return ASCII string
decrypted = ASCIIEncoding.ASCII.GetString(
des.CreateDecryptor().TransformFinalBlock(buff, 0, buff.Length)
);

return decrypted;
}


}

And we are done with this. Now play with encryption and decryption Cheers..

Read more...

How to Send mail through C# using SMTP

If you need to send mails through your code here is the simple Example in
C#

1) Add the System.Net.Mail; namespace to your code.

2) Wirte this code or modify it according to your need.

SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
string sHostName = "mail.test.com";
string strEmailFrom = "Manoj@mailtest.com";
string sFromName = "Manoj";
string strToEmail = "manojjoshi@gmail.com";
string strSubject = "Test Mail From Manoj";
string strBody = "< table >< tr >< td >This is just a test mail< /td >
< /tr >< /table >"; // Format your massage body here

MailAddress fromAddress = new MailAddress(strEmailFrom, sFromName);

// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost in this case it is mail.test.com
smtpClient.Host = sHostName;
//Default port will be 25
smtpClient.Port = 25;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add(strToEmail);
message.Subject = strSubject;
string ccMailIDs = "MyCC1@gmail.com";

///this line of code is for adding more Recipients in cc of your mail

message.CC.Add(new MailAddress(ccMailIDs));
ccMailIDs = "MyCC2@gmail.com";
message.CC.Add(new MailAddress(ccMailIDs));
ccMailIDs = "MyCC3@gmail.com";
message.CC.Add(new MailAddress(ccMailIDs));
//Body can be Html or text format
//Specify true if it is html message
message.IsBodyHtml = true;
// Message body content
message.Body = strBody;

// Send SMTP mail
smtpClient.Send(message);

}
catch (Exception ex)
{
string s = ex.Message;
}


And you are done. Cheers

Read more...

Wednesday, July 1, 2009

View State Versus Control State

View State Versus Control State

ViewState is a mechanism through which Asp.Net preserve state of the controls during postback and preserve data in hidden fields. Whenever any request goes to the server the whole value that is in hidden fields decrypt using BASE64 encoding and further incrypt after server response. We can set enable viewstate property to false if we dont want viewstate.

And Control State work in the same manner as ViewState but with a big difference, we can't disable controlstate.Control state is used for storing a control's essential data that is needed on postback to enable the control to function even when view state has been disabled.

Mostly Use the Control State property when you are going to implement Custom Control by overriding the SaveControlState method to save the data in Control State

Cheers

Read more...

Thursday, June 4, 2009

Rounding a Number in Javascript

function roundToWhatever()

{

var numberToRound = document.getElementById("idOfTheInputProvider").value

var numberToRound = new Number(numberToRound );

var result =numberToRound.toFixed(10);

document.getElementById("idOfTheInputProvider").value = result ;

}

Read more...

Monday, April 20, 2009

Boxing and Unboxing

Whenever we convert an Value type to a Reference type this process is called Boxing and opposite of that is UnBoxing

for ex :

class BoxingUnBoxing
{
static void Main()
{
int i = 1;
object o = i; // boxing
int j = (int) o; // unboxing
}
}

In this example we are assigning a value type to a reference type (eg. object o = i) , Object o is of reference type and i is of value type. and after that we assign an reference type to a value type (eg. int j = (int) o)

Read more...

About This Blog

This blog is all about Asp.Net , C# , Ajax, Sql Server and other technologies. Please feel free to contact me if you are looking for some solution's or want to share your knowldge with this programming world.

Cheers

  © Blogger template Coozie by Ourblogtemplates.com 2008

Back to TOP