• 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加密,解密

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

    再见!!!!

  • 相关阅读:
    Shell流程控制语句if
    Linux命令之read
    Docker容器(六)——创建docker私有化仓库
    Docker容器(五)——Docker静态化IP
    Docker容器(四)——常用命令
    python笔记
    iOS应用性能调优建议
    QQ音乐项目(OC版)
    iOS : 静态库制作
    iOS : 静态库(.framework)合并
  • 原文地址:https://www.cnblogs.com/SpadeA/p/6294059.html
Copyright © 2020-2023  润新知