Friday, February 19, 2010

Simple Encrypt and Decrypt Password Silverlight

Hello Guys,


I have sample code here on how to create a simple encryption and decryption on Silverlight.
First, I created a PASSWORD from SL Controls. A Three Button for encryption, decryption, clear. A one textblock and one textbox.

Second, I created a simple function for Encryption and Decryption and variables.

byte[] _encryted;
byte[] _decryted;
string s;

private string EncrytedString(string str)
{
_encryted = System.Text.Encoding.Unicode.GetBytes(str);
s = Convert.ToBase64String(_encryted);
return s;
}

private string DecrytedString(string str)
{
_decryted = Convert.FromBase64String(str);
s = System.Text.Encoding.Unicode.GetString(_decryted, 0, _decryted.ToArray().Length);
return s;
}



Now the snippets.

//For the Encryption Button
private void btnEncrypt_Click(object sender, RoutedEventArgs e)
{
if (passwordBox1.Password == string.Empty)
{
MessageBox.Show("Please Enter your Password");
passwordBox1.Focus();
}
else
{
btnDecrypt.IsEnabled = true;
string s = EncrytedString(passwordBox1.Password);
txtEncrypted.Text = s;
}
}

//For the Decryption Button
private void btnDecrypt_Click(object sender, RoutedEventArgs e)
{
string s;
s = DecrytedString(txtEncrypted.Text);
MessageBox.Show(s);
}

//For the Clear Button
private void btnClear_Click(object sender, RoutedEventArgs e)
{
txtEncrypted.Text = string.Empty;
passwordBox1.Password = string.Empty;
passwordBox1.Focus();
btnDecrypt.IsEnabled = false;
}






No comments:

Post a Comment