Encryption MADE EASY with PProtectedDataClass

Posted: May 29, 2006 in Uncategorized
You might be aware of the ProtectedDAta section introduced in .NET 2.0.If not have a look into my earlier post on the same line  here http://spaces.msn.com/shreeman/blog/cns!E1AF7EB63FAA1FF!506.entry.
 
Now the latest Update into the same is if you are not aware of the fact there is a new class in .NET 2.0 called Protecteddat which help you Encrypt and decrypt  much easier.You need to add ref to  the System.Security.dll and you can now store the secured info per localuser or Localsystem.Without further delay let see a simpl,e Example:-
 
 

private static string EncryptString(string cleanstring,string entstr)

{

try

{

byte[] clearbytes = null;

byte[] entbyte = null;

byte[] encbyte = null;

string encstring = string.Empty;

clearbytes = Encoding.UTF8.GetBytes(cleanstring);

if (entstr != string.Empty)

{

entbyte = Encoding.UTF8.GetBytes(entstr);

}

encbyte = ProtectedData.Protect(clearbytes, entbyte, DataProtectionScope.CurrentUser);

encstring = Convert.ToBase64String(encbyte);

return encstring;

}

catch (Exception ex)

{

throw (ex);

}

}

private static string decryptstring(string encryptedstring,string entstr)

{

try

{

byte[] clearbyte = null;

string clearstring = string.Empty;

byte[] entbyte = null;

byte[] encbyte = null;

encbyte = Convert.FromBase64String(encryptedstring);

if (entstr != string.Empty)

{

entbyte = Encoding.UTF8.GetBytes(entstr);

}

clearbyte = ProtectedData.Unprotect(encbyte, entbyte, DataProtectionScope.CurrentUser);

clearstring = Encoding.UTF8.GetString(clearbyte);

return clearstring;

}

catch (Exception ex)

{

throw (ex);

}

}

private void button1_Click(object sender, EventArgs e)

{

string x = "shreeman";

string enctsring = System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString();

string encystr = EncryptString(x, enctsring);

MessageBox.Show("enc string: " +encystr);

string getback = decryptstring(encystr, enctsring);

MessageBox.Show("Afetr decryption : " + getback);

 

}

}

 

Finally for more look into www.msdn2.com 

http://msdn2.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s