• 对称可逆加密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());
                }
            }
  • 相关阅读:
    source命令
    bash中单引号与双引号的总结
    鸟哥的linux私房菜学习笔记3
    鸟哥的linux私房菜学习笔记2
    /usr/sbin/atd 和 /etc/init.d/atd有什么区别
    Linux中/etc/fstab /etc/mtab /proc/mounts这三个文件的分析与比较
    服务器本机不能登陆的解决
    有用的博客
    推荐几个好用的PHP集成开发环境
    ANDROID开发笔记(二)
  • 原文地址:https://www.cnblogs.com/zhangnever/p/12427521.html
Copyright © 2020-2023  润新知