首页 > Windows开发 > 详细

c#DES加密 和解密

时间:2020-03-01 17:34:11      阅读:46      评论:0      收藏:0      [点我收藏+]
#region DES加密
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="datastr">需要加密的字符串</param>
        /// <returns>返回加密后的字符串</returns>
        public static string Encrypt(string datastr)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes("", null);
            DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
            byte[] key = pdb.CryptDeriveKey("DES", "SHA1", 0, new byte[8]);
            byte[] data = System.Text.Encoding.Unicode.GetBytes(datastr);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, desc.CreateEncryptor(key, key), CryptoStreamMode.Write);

            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();
            return System.Text.Encoding.Unicode.GetString(ms.ToArray());
        }
        #endregion

        #region 解密字符串
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="datastr">需要解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string datastr)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes("", null);
            DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
            byte[] key = pdb.CryptDeriveKey("DES", "SHA1", 0, new byte[8]);
            byte[] data = System.Text.Encoding.Unicode.GetBytes(datastr);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, desc.CreateDecryptor(key, key), CryptoStreamMode.Write);
            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();
            return System.Text.Encoding.Unicode.GetString(ms.ToArray());
        }
        #endregion

 

c#DES加密 和解密

原文:https://www.cnblogs.com/zengxh/p/12390707.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!