The following is the C # implementation code of the symmetric encryption algorithm. You can change different algorithms as needed. The Rijndael algorithm is used as an example: using System;
Using System. IO;
Using System. Security. Cryptography;
Using System. Text;
Namespace DataCrypto
{
/// <Summary>
/// Symmetric encryption algorithm
/// </Summary>
Public class extends ricmethod
{
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 ();
}
}
}