String encryption and decryption functions (C #)
Using System;
Using System. Text;
Using System. Security. Cryptography;
Using System. IO;
// Default key vector
Private static byte [] Keys = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/// <Summary>
/// DES encrypted string
/// </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
/// </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;
}
}
0 0
0
(Please comment on the article)