• C#实现简单的字符串加密


    最近用到一些字符串加密,而.net中提供的加密算法中用起来比较复杂,便简单的封装了一下,方便日后使用。

        public class Encrypt
        {
            static Encoding encoding = Encoding.UTF8;

            public static string EncryptDES(string encryptString, string key)
            {
                var input = encoding.GetBytes(encryptString);
                var ouptputData = ProcessDES(input, key, true);
                var outputStr = Convert.ToBase64String(ouptputData);

                //base64
    编码中有不能作为文件名的
    '/'符号,这里把它替换一下,增强适用范围
                return outputStr.Replace('/', '@');
            }

            public static string DecryptDES(string decryptString, string key)
            {
                decryptString = decryptString.Replace('@', '/');

                var input = Convert.FromBase64String(decryptString);
                var data = ProcessDES(input, key, false);
                return encoding.GetString(data);
            }


            private static byte[] ProcessDES(byte[] data, string key, bool isEncrypt)
            {
                using (var dCSP = new DESCryptoServiceProvider())
                {
                    var keyData = Md5(key);
                    var rgbKey = new ArraySegment<byte>(keyData, 0, 8).ToArray();
                    var rgbIV = new ArraySegment<byte>(keyData, 8, 8).ToArray();
                    var dCSPKey = isEncrypt ? dCSP.CreateEncryptor(rgbKey, rgbIV) : dCSP.CreateDecryptor(rgbKey, rgbIV);

                    using (var memory = new MemoryStream())
                    using (var cStream = new CryptoStream(memory, dCSPKey, CryptoStreamMode.Write))
                    {
                        cStream.Write(data, 0, data.Length);
                        cStream.FlushFinalBlock();
                        return memory.ToArray();
                    }
                }
            }

            public static byte[] Md5(string str)
            {
                using (var md5 = MD5.Create())
                {
                    return md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                }
            }
        }

    这个封装支持MD5和DES加密(有空再把RSA给补上),用于字符串加密,主要考虑的是方便使用,并没有追求最优效率。为方便使用做了如下两点优化:

    1. 密钥为字符串形式,没有长度限制
    2. 加密后输出的字符串为Base64的改造形式,可以用于文件名
  • 相关阅读:
    BigPipe_高性能流水线页面技术
    高并发大流量网站 10 个解决方法
    崇高不是比惨
    utf-8无bom格式编码
    go.php
    微信+QQ跳转
    java 设计模式-单例
    HTML连载88-今天把努比亚界面仿真写完了(完结连载)
    Android连载10-动态添加页面、创建一个新闻app
    JavaScript连载9-三目运算符、综合复习
  • 原文地址:https://www.cnblogs.com/TianFang/p/3301941.html
Copyright © 2020-2023  润新知