zoukankan      html  css  js  c++  java
  • C#,ASP.NET简单的MD5加密,解密

    简单的MD5加密

    首先要有一个加解密的规则  就是key

    代码如下 

    // 创建Key
    public string GenerateKey()
    {
    DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
    return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
    }

    然后就是加密

    传入的参数分别为你要加密的字符串,然后就是加密规则;

    ///MD5加密
    public string MD5Encrypt(string pToEncrypt, string sKey)
    {
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
    des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();
    StringBuilder ret = new StringBuilder();

    //按照规则写你的加密后的内容
    foreach (byte b in ms.ToArray())
    {
    ret.AppendFormat("{0:X2}", b);
    }
    ret.ToString();
    return ret.ToString();
    }

    加密后要相对应的解密:

    传入的参数分别为:用上面的规则加密来的字符串,然后就是规则


    ///MD5解密
    public string MD5Decrypt(string pToDecrypt, string sKey)
    {
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    byte[] inputByteArray = new byte[pToDecrypt.Length / 2];

    //根据规则解读byte
    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 = ASCIIEncoding.ASCII.GetBytes(sKey);
    des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();

    StringBuilder ret = new StringBuilder();

    return System.Text.Encoding.Default.GetString(ms.ToArray());
    }

    简单的MD5加密,解密

    可以写成一个公共类在任意的地方调用  

    再见!!!!

  • 相关阅读:
    JS的编码、解码及C#中对应的解码、编码 itprobie
    word、excel、ppt转换成html itprobie
    js 导出到word,excel itprobie
    word、excel、ppt转换成pdf itprobie
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
    Copy Table From Another Table
    系统表相关SQL语句
    sp_executesql Demo
    SQLServer2000删除重复数据
    SQL Tran Save Point
  • 原文地址:https://www.cnblogs.com/SpadeA/p/6294059.html
Copyright © 2011-2022 走看看