C # code encapsulation for common string encryption and decryption Methods
This article mainly introduces C # code encapsulation for commonly used string encryption and decryption methods. If you need it, refer to it.
The Code is as follows:
// Method 1
// Add a reference to System. Web
// Using System. Web. Security;
/// <Summary>
/// SHA1 encrypted string
/// </Summary>
/// <Param name = "source"> source string </param>
/// <Returns> encrypted string </returns>
Public string SHA1 (string source)
{
Return FormsAuthentication. HashPasswordForStoringInConfigFile (source, "SHA1 ");
}
/// <Summary>
/// MD5 encrypted string
/// </Summary>
/// <Param name = "source"> source string </param>
/// <Returns> encrypted string </returns>
Public string MD5 (string source)
{
Return FormsAuthentication. HashPasswordForStoringInConfigFile (source, "MD5 ");;
}
// Method 2 (reversible encryption and decryption ):
// Using System. Security. Cryptography;
Public string Encode (string data)
{
Byte [] byKey = System. Text. ASCIIEncoding. ASCII. GetBytes (KEY_64 );
Byte [] byIV = System. Text. ASCIIEncoding. ASCII. GetBytes (IV_64 );
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider ();
Int I = cryptoProvider. KeySize;
MemoryStream MS = new MemoryStream ();
CryptoStream cst = new CryptoStream (MS, cryptoProvider. CreateEncryptor (byKey, byIV), CryptoStreamMode. Write );
StreamWriter sw = new StreamWriter (cst );
Sw. Write (data );
Sw. Flush ();
Cst. FlushFinalBlock ();
Sw. Flush ();
Return Convert. ToBase64String (ms. GetBuffer (), 0, (int) ms. Length );
}
Public string Decode (string data)
{
Byte [] byKey = System. Text. ASCIIEncoding. ASCII. GetBytes (KEY_64 );
Byte [] byIV = System. Text. ASCIIEncoding. ASCII. GetBytes (IV_64 );
Byte [] byEnc;
Try
{
ByEnc = Convert. FromBase64String (data );
}
Catch
{
Return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider ();
MemoryStream MS = new MemoryStream (byEnc );
CryptoStream cst = new CryptoStream (MS, cryptoProvider. CreateDecryptor (byKey, byIV), CryptoStreamMode. Read );
StreamReader sr = new StreamReader (cst );
// Method 3 (MD5 irreversible ):
// Using System. Security. Cryptography;
// MD5 irreversible encryption
// 32-bit encryption
Public string GetMD5_32 (string s, string _ input_charset)
{
MD5 md5 = new MD5CryptoServiceProvider ();
Byte [] t = md5.ComputeHash (Encoding. GetEncoding (_ input_charset). GetBytes (s ));
StringBuilder sb = new StringBuilder (32 );
For (int I = 0; I <t. Length; I ++)
{
Sb. Append (t [I]. ToString ("x"). PadLeft (2, '0 '));
}
Return sb. ToString ();
}
// 16-bit encryption
Public static string GetMd5_16 (string ConvertString)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider ();
String t2 = BitConverter. ToString (md5.ComputeHash (UTF8Encoding. Default. GetBytes (ConvertString), 4, 8 );
T2 = t2.Replace ("-","");
Return t2;
}
// Method 4 (symmetric encryption ):
// Using System. IO;
// Using System. Security. Cryptography;
Private encryption ricalgorithm mobjCryptoService;
Private string Key;
/// <Summary>
/// Constructor of symmetric encryption
/// </Summary>
Public parameter ricmethod ()
{
MobjCryptoService = new RijndaelManaged ();
Key = "Guz (% & hj7x89H $ yuBI0456FtmaT5 & fvHUFCy76 * h % (HilJ $ lhj! Y6 & (* jkP87jH7 ";
}
/// <Summary>
/// Obtain the key
/// </Summary>
/// <Returns> key </returns>
Private byte [] GetLegalKey ()
{
String sTemp = Key;
MobjCryptoService. GenerateKey ();
Byte [] bytTemp = mobjCryptoService. Key;
Int KeyLength = bytTemp. Length;
If (sTemp. Length> KeyLength)
STemp = sTemp. Substring (0, KeyLength );
Else if (sTemp. Length <KeyLength)
STemp = sTemp. PadRight (KeyLength ,'');
Return ASCIIEncoding. ASCII. GetBytes (sTemp );
}
/// <Summary>
/// Obtain the initial vector IV
/// </Summary>
/// <Returns> initial test vector IV </returns>
Private byte [] GetLegalIV ()
{
String sTemp = "E4ghj * Ghg7! RNIfb & 95GUY86GfghUb # er57HBh (u % g6HJ ($ jhWk7 &! Hg4ui % $ hjk ";
MobjCryptoService. GenerateIV ();
Byte [] bytTemp = mobjCryptoService. IV;
Int IVLength = bytTemp. Length;
If (sTemp. Length> IVLength)
STemp = sTemp. Substring (0, IVLength );
Else if (sTemp. Length <IVLength)
STemp = sTemp. PadRight (IVLength ,'');
Return ASCIIEncoding. ASCII. GetBytes (sTemp );
}
/// <Summary>
/// Encryption Method
/// </Summary>
/// <Param name = "Source"> string to be encrypted </param>
/// <Returns> encrypted string </returns>
Public string Encrypto (string Source)
{
Byte [] bytIn = UTF8Encoding. UTF8.GetBytes (Source );
MemoryStream MS = new MemoryStream ();
MobjCryptoService. Key = GetLegalKey ();
MobjCryptoService. IV = GetLegalIV ();
ICryptoTransform encrypto = mobjCryptoService. CreateEncryptor ();
CryptoStream cs = new CryptoStream (MS, encrypto, CryptoStreamMode. Write );
Cs. Write (bytIn, 0, bytIn. Length );
Cs. FlushFinalBlock ();
Ms. Close ();
Byte [] bytOut = ms. ToArray ();
Return Convert. ToBase64String (bytOut );
}
/// <Summary>
/// Decryption Method
/// </Summary>
/// <Param name = "Source"> string to be decrypted </param>
/// <Returns> decrypted string </returns>
Public string Decrypto (string Source)
{
Byte [] bytIn = Convert. FromBase64String (Source );
MemoryStream MS = new MemoryStream (bytIn, 0, bytIn. Length );
MobjCryptoService. Key = GetLegalKey ();
MobjCryptoService. IV = GetLegalIV ();
ICryptoTransform encrypto = mobjCryptoService. CreateDecryptor ();
CryptoStream cs = new CryptoStream (MS, encrypto, CryptoStreamMode. Read );
StreamReader sr = new StreamReader (cs );
Return sr. ReadToEnd ();
}
// Method 5:
// Using System. IO;
// Using System. Security. Cryptography;
// Using System. Text;
// Default key vector
Private static byte [] Keys = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/** // <Summary>
/// DES encrypted string keleyi.com
/// </Summary>
/// <Param name = "encryptString"> string to be encrypted </param>
/// <Param name = "encryptKey"> encryption key, which must be 8-bit </param>
/// <Returns> the encrypted string is returned successfully. If the source string fails to be returned, </returns>
Public static string EncryptDES (string encryptString, string encryptKey)
{
Try
{
Byte [] rgbKey = Encoding. UTF8.GetBytes (encryptKey. Substring (0, 8 ));
Byte [] rgbIV = Keys;
Byte [] inputByteArray = Encoding. UTF8.GetBytes (encryptString );
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider ();
MemoryStream mStream = new MemoryStream ();
CryptoStream cStream = new CryptoStream (mStream, dCSP. CreateEncryptor (rgbKey, rgbIV), CryptoStreamMode. Write );
CStream. Write (inputByteArray, 0, inputByteArray. Length );
CStream. FlushFinalBlock ();
Return Convert. ToBase64String (mStream. ToArray ());
}
Catch
{
Return encryptString;
}
}
/** // <Summary>
/// DES decryption string keleyi.com
/// </Summary>
/// <Param name = "decryptString"> string to be decrypted </param>
/// <Param name = "decryptKey"> the decryption key must be 8 bits, which is the same as the encryption key </param>
/// <Returns> the decrypted string is returned successfully, and the source string fails to be returned. </returns>
Public static string DecryptDES (string decryptString, string decryptKey)
{
Try
{
Byte [] rgbKey = Encoding. UTF8.GetBytes (decryptKey );
Byte [] rgbIV = Keys;
Byte [] inputByteArray = Convert. FromBase64String (decryptString );
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider ();
MemoryStream mStream = new MemoryStream ();
CryptoStream cStream = new CryptoStream (mStream, DCSP. CreateDecryptor (rgbKey, rgbIV), CryptoStreamMode. Write );
CStream. Write (inputByteArray, 0, inputByteArray. Length );
CStream. FlushFinalBlock ();
Return Encoding. UTF8.GetString (mStream. ToArray ());
}
Catch
{
Return decryptString;
}
}
// Method 6 (file encryption ):
// Using System. IO;
// Using System. Security. Cryptography;
// Using System. Text;
// Encrypt the file
Private static void EncryptData (String inName, String outName, byte [] cipher ey, byte [] desIV)
{
// Create the file streams to handle the input and output files.
FileStream fin = new FileStream (inName, FileMode. Open, FileAccess. Read );
FileStream fout = new FileStream (outName, FileMode. OpenOrCreate, FileAccess. Write );
Fout. SetLength (0 );
// Create variables to help with read and write.
Byte [] bin = new byte [100]; // This is intermediate storage for the encryption.
Long rdlen = 0; // This is the total number of bytes written.
Long totlen = fin. Length; // This is the total length of the input file.
Int len; // This is the number of bytes to be written at a time.
DES des = new DESCryptoServiceProvider ();
CryptoStream encStream = new CryptoStream (fout, des. CreateEncryptor (Cipher ey, desIV), CryptoStreamMode. Write );
// Read from the input file, then encrypt and write to the output file.
While (rdlen <totlen)
{
Len = fin. Read (bin, 0,100 );
EncStream. Write (bin, 0, len );
Rdlen = rdlen + len;
}
EncStream. Close ();
Fout. Close ();
Fin. Close ();
}
// Decrypt the file
Private static void DecryptData (String inName, String outName, byte [] cipher ey, byte [] desIV)
{
// Create the file streams to handle the input and output files.
FileStream fin = new FileStream (inName, FileMode. Open, FileAccess. Read );
FileStream fout = new FileStream (outName, FileMode. OpenOrCreate, FileAccess. Write );
Fout. SetLength (0 );
// Create variables to help with read and write.
Byte [] bin = new byte [100]; // This is intermediate storage for the encryption.
Long rdlen = 0; // This is the total number of bytes written.
Long totlen = fin. Length; // This is the total length of the input file.
Int len; // This is the number of bytes to be written at a time.
DES des = new DESCryptoServiceProvider ();
CryptoStream encStream = new CryptoStream (fout, des. CreateDecryptor (Cipher ey, desIV), CryptoStreamMode. Write );
// Read from the input file, then encrypt and write to the output file.
While (rdlen <totlen)
{
Len = fin. Read (bin, 0,100 );
EncStream. Write (bin, 0, len );
Rdlen = rdlen + len;
}
EncStream. Close ();
Fout. Close ();
Fin. Close ();
Return sr. ReadToEnd ();
}
Detailed source reference: http://www.jb51.net/article/44133.htm