zoukankan      html  css  js  c++  java
  • 通用DES加密解密方法

    /// <summary>
    /// DES加密方法
    /// </summary>
    /// <param name="strPlain">明文</param>
    /// <param name="strDESKey">密钥</param>
    /// <param name="strDESIV">向量</param>
    /// <returns>密文</returns>
    public string Encrypt(string source,string _DESKey)
    {
    StringBuilder sb = new StringBuilder();
    using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
    {
    byte[] key = ASCIIEncoding.ASCII.GetBytes(_DESKey);
    byte[] iv = ASCIIEncoding.ASCII.GetBytes(_DESKey);
    byte[] dataByteArray = Encoding.UTF8.GetBytes(source);
    des.Mode = System.Security.Cryptography.CipherMode.CBC;
    des.Key = key;
    des.IV = iv;
    string encrypt = "";
    using (MemoryStream ms = new MemoryStream())
    using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
    {
    cs.Write(dataByteArray, 0, dataByteArray.Length);
    cs.FlushFinalBlock();
    //輸出資料
    foreach (byte b in ms.ToArray())
    {
    sb.AppendFormat("{0:X2}", b);
    }
    encrypt = sb.ToString();
    }
    return encrypt;
    }

    }

    /// <summary>
    /// 进行DES解密。
    /// </summary>
    /// <param name="pToDecrypt">要解密的串</param>
    /// <param name="sKey">密钥,且必须为8位。</param>
    /// <returns>已解密的字符串。</returns>
    public string Decrypt(string source, string sKey)
    {
    byte[] inputByteArray = Encoding.UTF8.GetBytes(source);
    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;
    }

  • 相关阅读:
    [MacOS]Sublime text3 安装(一)
    [RHEL8]开启BBR
    PAT Advanced 1136 A Delayed Palindrome (20分)
    PAT Advanced 1144 The Missing Number (20分)
    PAT Advanced 1041 Be Unique (20分)
    PAT Advanced 1025 PAT Ranking (25分)
    PAT Advanced 1022 Digital Library (30分)
    PAT Advanced 1019 General Palindromic Number (20分)
    PAT Advanced 1011 World Cup Betting (20分)
    PAT Advanced 1102 Invert a Binary Tree (25分)
  • 原文地址:https://www.cnblogs.com/lxny/p/6760728.html
Copyright © 2011-2022 走看看