美文网首页
c# 基于DES的字符串加密解密

c# 基于DES的字符串加密解密

作者: zhangqian976431 | 来源:发表于2016-08-02 09:50 被阅读0次

    注:由于加密、解密字符串时,需要用到加密类和内存流,所以首先需要在命名空间区域添加System.Security.Cryptography和System.IO命名空间。

    //自定义的加密字符串 

    static string encryptKey = "1234"; 

    //字符串加密
            static string Encrypt(string str)
            {
                DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
                byte[] key = Encoding.Unicode.GetBytes(encryptKey);
                byte[] data = Encoding.Unicode.GetBytes(str);
                MemoryStream MStream = new MemoryStream();
                CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
                CStream.Write(data, 0, data.Length);
                CStream.FlushFinalBlock();
                return Convert.ToBase64String(MStream.ToArray());
            }

     //字符串解密
            static string Decrypt(string str)
            {
                DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
                byte[] key = Encoding.Unicode.GetBytes(encryptKey);
                byte[] data = Convert.FromBase64String(str);
                MemoryStream MStream = new MemoryStream();
                CryptoStream CStram = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
                CStram.Write(data, 0, data.Length);
                CStram.FlushFinalBlock();
                return Encoding.Unicode.GetString(MStream.ToArray());
            }

    //调用方法

    static void Main(string[] args)
            {

               Console.Write("请输入要加密的字符串:");
                Console.WriteLine();
                string strOld = Console.ReadLine();
                string strNew = Encrypt(strOld);
                Console.WriteLine("加密后的字符串:" + strNew);
                Console.WriteLine("解密后的字符串:" + Decrypt(strNew));
                Console.ReadLine();

           }

    相关文章

      网友评论

          本文标题:c# 基于DES的字符串加密解密

          本文链接:https://www.haomeiwen.com/subject/jdefsttx.html