Public class encryptdesstring
{
// 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); // convert to byte
Byte [] rgbiv = keys;
Byte [] inputbytearray = encoding. utf8.getbytes (encryptstring );
Descryptoserviceprovider dcsp = new descryptoserviceprovider (); // instantiate the Data Encryption Standard
Memorystream mstream = new memorystream (); // instantiate the memory stream
// Link the data stream to the encrypted conversion stream
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;
}
}
}
Implementation of DES encryption and decryption