Using System;
Using System.Text;
Using System.IO;
Using System.Security.Cryptography;
Namespace Stringsecurity
{
<summary>
String encryption decryption class.
</summary>
public sealed class Stringsecurity
{
Private stringsecurity () {}
#region SHA1 Encryption
<summary>
Use SHA1 to encrypt strings.
</summary>
<param name= "inputstring" > Input string. </param>
<returns> the encrypted string. (40 characters) </returns>
public static string Stringtosha1hash (String inputstring)
{
SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider ();
byte[] encryptedbytes = Sha1.computehash (Encoding.ASCII.GetBytes (inputstring));
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < encryptedbytes.length; i++)
{
Sb. AppendFormat ("{0:x2}", Encryptedbytes[i]);
}
Return SB. ToString ();
}
#endregion
#region DES Encryption/decryption
private static byte[] key = ASCIIEncoding.ASCII.GetBytes ("Caikelun");
private static byte[] IV = ASCIIEncoding.ASCII.GetBytes ("12345678");
<summary>
DES encryption.
</summary>
<param name= "inputstring" > Input string. </param>
<returns> the encrypted string. </returns>
public static string Desencrypt (String inputstring)
{
MemoryStream ms = NULL;
CryptoStream cs = null;
StreamWriter sw = null;
DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
Try
{
ms = new MemoryStream ();
CS = new CryptoStream (MS, Des. CreateEncryptor (Key, iv), CryptoStreamMode.Write);
SW = new StreamWriter (CS);
Sw. Write (inputstring);
Sw. Flush ();
Cs. FlushFinalBlock ();
Return convert.tobase64string (Ms. GetBuffer (), 0, (int) Ms. Length);
}
Finally
{
if (SW!= null) SW. Close ();
if (CS!= null) CS. Close ();
if (MS!= null) Ms. Close ();
}
}
<summary>
Des decryption.
</summary>
<param name= "inputstring" > Input string. </param>
<returns> the decrypted string. </returns>
public static string Desdecrypt (String inputstring)
{
MemoryStream ms = NULL;
CryptoStream cs = null;
StreamReader sr = null;
DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
Try
{
ms = new MemoryStream (convert.frombase64string (inputstring));
CS = new CryptoStream (MS, Des. CreateDecryptor (Key, iv), CryptoStreamMode.Read);
sr = new StreamReader (CS);
return Sr. ReadToEnd ();
}
Finally
{
if (SR!= null) Sr. Close ();
if (CS!= null) CS. Close ();
if (MS!= null) Ms. Close ();
}
}
#endregion
}
}