zoukankan      html  css  js  c++  java
  • 对称可逆加密Des

    加密后能解密回原文,但是需要一个key

    加密key与解密key是一样的(对称)

    但是key的安全性问题一定要得到保证

    code:

            //key可以写在配置文件中
            //加密key 
            static string key = "A1B2C3D4E5";
            private static byte[] _rgbKey = ASCIIEncoding.ASCII.GetBytes(key.Substring(0, 8));
            //解密key
            private static byte[] _rgbIV = ASCIIEncoding.ASCII.GetBytes(key.Insert(0, "w").Substring(0, 8));
    
            /// <summary>
            /// DES加密
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public async Task<string> Encrypt(string str)
            {
                var dsp = new DESCryptoServiceProvider();
                //创建一个流对象
                using (MemoryStream stream = new MemoryStream())
                {
                    //将数据写入流中
                    CryptoStream cryptoStream = new CryptoStream(stream, dsp.CreateEncryptor(_rgbKey, _rgbIV),
                        CryptoStreamMode.Write);
                    StreamWriter streamWriter = new StreamWriter(cryptoStream);
                    streamWriter.Write(str);
                    streamWriter.Flush();
                    cryptoStream.FlushFinalBlock();
                    stream.Flush();
                    return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length);
                }
            }
    
            /// <summary>
            /// DES解密
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public async Task<string> Decrypt(string str)
            {
                var dsp = new DESCryptoServiceProvider();
                byte[] buffer = Convert.FromBase64String(str);
                using (MemoryStream stream = new MemoryStream())
                {
                    CryptoStream cryptoStream = new CryptoStream(stream, dsp.CreateEncryptor(_rgbKey, _rgbIV), CryptoStreamMode.Write);
                    cryptoStream.Write(buffer, 0, buffer.Length);
                    cryptoStream.FlushFinalBlock();
                    return Encoding.UTF8.GetString(stream.ToArray());
                }
            }
  • 相关阅读:
    windows下配置mysql环境变量
    360Top奢侈品演示站
    CSS3性能体验
    使用jquery获取radio的值
    获取select 的 val 和 text [转引]
    PHP时间比较和时间差如何计算
    InnoDB和MyISAM的区别与选择
    大型网站技术架构学习摘要
    大型网站系统架构分析--转
    一步步构建大型网站架构-转
  • 原文地址:https://www.cnblogs.com/zhangnever/p/12427521.html
Copyright © 2011-2022 走看看