c#DES加密 和解密

#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加密 和解密

上一篇:c#数据验证方法


下一篇:使用 GNU GCC 和 GDB 开发调试应用程序