This document describes how to encrypt and decrypt MD5 and des of ASP. NET. Algorithm
# Region MD5 Algorithm
Public String MD5 (string STR, int code)
{
If (code = 16) // 16-bit MD5 encryption (take 32-bit encryption 9 ~ 25 characters)
{
Return System. Web. Security. formsauthentication. hashpasswordforstoringinconfigfile (STR, "MD5"). tolower (). substring (8, 16 );
}
If (code = 32) // 32-bit encryption
{
Return System. Web. Security. formsauthentication. hashpasswordforstoringinconfigfile (STR, "MD5"). tolower ();
}
Return "00000000000000000000000000000000 ";
}
# Endregion
# Region desencrypt DES encryption
// <Summary>
/// Perform DES encryption.
/// </Summary>
/// <Param name = "ptoencrypt"> string to be encrypted. </Param>
/// <Param name = "skey"> The key must be 8 bits. </Param>
/// <Returns> the encrypted string returned in base64 format. </Returns>
Public String desencrypt (string ptoencrypt, string skey)
{
Using (descryptoserviceprovider des = new descryptoserviceprovider ())
{
Byte [] inputbytearray = encoding. utf8.getbytes (ptoencrypt );
Des. Key = asciiencoding. ASCII. getbytes (skey );
Des. IV = asciiencoding. ASCII. getbytes (skey );
System. Io. memorystream MS = new system. Io. memorystream ();
Using (cryptostream cs = new cryptostream (MS, Des. createencryptor (), cryptostreammode. Write ))
{
CS. Write (inputbytearray, 0, inputbytearray. Length );
CS. flushfinalblock ();
CS. Close ();
}
String STR = convert. tobase64string (Ms. toarray ());
Ms. Close ();
Return STR;
}
}
# Endregion
# Region desdecrypt des decryption
/// <Summary>
/// Perform des decryption.
/// </Summary>
/// <Param name = "ptodecrypt"> the base64 file to be decrypted </param>
/// <Param name = "skey"> The key must be 8 bits. </Param>
/// <Returns> decrypted string. </Returns>
Public String desdecrypt (string ptodecrypt, string skey)
{
Byte [] inputbytearray = convert. frombase64string (ptodecrypt );
Using (descryptoserviceprovider des = new descryptoserviceprovider ())
{
Des. Key = asciiencoding. ASCII. getbytes (skey );
Des. IV = asciiencoding. ASCII. getbytes (skey );
System. Io. memorystream MS = new system. Io. memorystream ();
Using (cryptostream cs = new cryptostream (MS, Des. createdecryptor (), cryptostreammode. Write ))
{
CS. Write (inputbytearray, 0, inputbytearray. Length );
CS. flushfinalblock ();
CS. Close ();
}
String STR = encoding. utf8.getstring (Ms. toarray ());
Ms. Close ();
Return STR;
}
}
# Endregion