C#MD5加密解密

来源:互联网 发布:淘宝网运动服女装 编辑:程序博客网 时间:2024/04/27 19:34

using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// MD5Class 的摘要说明
/// </summary>
public class MD5Class
{
    //使用下边的加密规则字符串
    //??b???W
    static string key = "??b???W";
    public MD5Class()
    {

    }
 
    // 创建KEY
 
    public static string GenerateKey()
    {
        System.Security.Cryptography.DESCryptoServiceProvider desCrypto = (System.Security.Cryptography.DESCryptoServiceProvider)System.Security.Cryptography.DESCryptoServiceProvider.Create();
        return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
    }
  
    // MD5加密
    //pToEncrypt为要加密的字符串
    public static string MD5Encrypt(string pToEncrypt)
    {
        string sKey = key;
        System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
        byte[] inputByteArray = System.Text.Encoding.Default.GetBytes(pToEncrypt);
        des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(sKey);
        des.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(sKey);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        System.Text.StringBuilder ret = new System.Text.StringBuilder();
        foreach (byte b in ms.ToArray())
        {
            ret.AppendFormat("{0:X2}", b);
        }
        ret.ToString();
        return ret.ToString();
    }
   
    // MD5解密
    //pToDecrypt为要解密的字符串
    public static string MD5Decrypt(string pToDecrypt)
    {
        string sKey = key;
        System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
        byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
        for (int x = 0; x < pToDecrypt.Length / 2; x++)
        {
            int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
            inputByteArray[x] = (byte)i;
        }
        des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(sKey);
        des.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(sKey);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        System.Text.StringBuilder ret = new System.Text.StringBuilder();
        return System.Text.Encoding.Default.GetString(ms.ToArray());
    }
}