MD5和DES加密方法

    /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="EncryptString"></param>
        /// <returns></returns>
        public string MD5Encrypt(string EncryptString)
        {
            if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception(" 密文不得为空 ")); }
            System.Security.Cryptography.MD5 md5 = new MD5CryptoServiceProvider();
            string m_strEncrypt = "";
            try
            {
                m_strEncrypt = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(EncryptString))).Replace("-", "");
            }
            catch (ArgumentException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { md5.Clear(); }
            return m_strEncrypt;

}

DES加密解密

/// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string DecryptCookie(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            MemoryStream stream = new MemoryStream(Convert.FromBase64String(str));
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(KEY_64, IV_64), CryptoStreamMode.Read);
            StreamReader reader = new StreamReader(stream2);
            return reader.ReadToEnd();
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string EncryptCookie(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }
            byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(KEY_64, IV_64), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());
        }
        /// <summary>
        /// 8字节=64位
        /// </summary>
        private static byte[] IV_64
        {
            get
            {
                return new byte[] { 0x18, 0x56, 0x7e, 0x2e, 0x4c, 0x2c, 0x83, 0x13 };
            }
        }
        private static byte[] KEY_64
        {
            get
            {
                return new byte[] { 0x52, 0xcb, 0x38, 0x38, 0x12, 0x18, 0x63, 0x45 };
            }

}

上一篇:JVM 必备指南


下一篇:了不起的分支和循环01 - 零基础入门学习Python007