public override byte[] Encrypt(byte[] message, byte[] key, byte[] IV)
        {
            des.KeySize = key.Length * 8;
            des.Key     = key;
            SetCipherMode();


            if (des.Mode != System.Security.Cryptography.CipherMode.ECB)
            {
                des.IV = IV;
            }

            var encryptor = des.CreateEncryptor(des.Key, des.IV);

            byte[] encrypted;

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    cs.Write(message);
                }

                encrypted = ms.ToArray();
            }

            des.Dispose();

            return(encrypted);
        }
示例#2
0
        /// <summary>
        /// DES对称解密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string DES(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;

            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int    x, i;

            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(Encrypt.MD5(sKey).Substring(0, 8));
            des.IV  = ASCIIEncoding.ASCII.GetBytes(Encrypt.MD5(sKey).Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream           cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            string msg = Encoding.Default.GetString(ms.ToArray());

            cs.Close();
            ms.Close();
            des.Dispose();
            return(msg);
        }
        /// <summary>
        /// DES对称解密
        /// </summary>
        /// <param name="encryptBytes">要解密的二进制数据,如果是一个对象,该对象必须实现了<see cref="SerializableAttribute"/></param>
        /// <param name="privateKey">加密的私钥</param>
        /// <returns></returns>
        public static object DeEncryptDES(byte[] encryptBytes, string privateKey)
        {
            object result = null;

            if (StringUtil.IsNullOrEmpty(encryptBytes))
            {
                return(result);
            }
            DESCryptoServiceProvider provider = (DESCryptoServiceProvider)GetEncryptFactory <DESCryptoServiceProvider>(privateKey, 8);

            try
            {
                byte[] deencryptResult = Encrypt(provider.CreateDecryptor(), encryptBytes);
                result = SerializeUtil.FromBinary <object>(deencryptResult);
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
            catch (SerializationException ex)
            {
                throw new SerializationException("解密时序列化失败,无法反序列化对象", ex);
            }
            finally
            {
                provider.Dispose();
            }
            return(result);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_transform1 != null)
                    {
                        _transform1.Dispose();
                        _transform1 = null;
                    }
                    if (_transform2 != null)
                    {
                        _transform2.Dispose();
                        _transform2 = null;
                    }
                    if (_transform3 != null)
                    {
                        _transform3.Dispose();
                        _transform3 = null;
                    }

                    if (_desService != null)
                    {
                        _desService.Dispose();
                        _desService = null;
                    }
                }

                _disposed = true;
            }
        }
        /// <summary>
        /// <Decription>decrypt text for matching with input</Decription>
        /// </summary>
        /// <param name="text">Text To decrypt</param>
        public static string Decrypt(string text)
        {
            DESCryptoServiceProvider des          = new DESCryptoServiceProvider();
            MemoryStream             memoryStream = new MemoryStream();

            try
            {
                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));


                Byte[] byteArray = Convert.FromBase64String(text);


                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                             des.CreateDecryptor(key, IV), CryptoStreamMode.Write);

                cryptoStream.Write(byteArray, 0, byteArray.Length);
                cryptoStream.FlushFinalBlock();

                return(Encoding.UTF8.GetString(memoryStream.ToArray()));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                des.Dispose();
                memoryStream.Dispose();
            }
        }
示例#6
0
    public static string FromDESString(this string s, string key)
    {
        if (key.Length < 8)
        {
            throw new ArgumentException("参数[key]长度必须大于8", "key");
        }

        var dKey   = Encoding.Default.GetBytes(key.Substring(0, 8));
        var dIV    = Encoding.Default.GetBytes("10100100");
        var data   = Convert.FromBase64String(s);
        var des    = new DESCryptoServiceProvider();
        var stream = new MemoryStream(data);
        var r      = "";

        using (var cs = new CryptoStream(stream, des.CreateDecryptor(dKey, dIV), CryptoStreamMode.Read))
        {
            using (var sr = new StreamReader(cs))
            {
                r = sr.ReadToEnd();
            }
        }
        des.Dispose();
        stream.Close();
        return(r);
    }
        public static string CompressString(this string str, Encoding encoding = null)
        {
            string s = "";

            encoding = encoding ?? new UTF8Encoding(false);
            s        = Convert.ToBase64String(encoding.GetBytes(str).Compress());
            try
            {
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                byte[]       bytes   = Encoding.Unicode.GetBytes(encryptKey);
                byte[]       rgbIV   = Encoding.Unicode.GetBytes(encryptIv);
                byte[]       buffer  = Encoding.Unicode.GetBytes(s);
                MemoryStream stream  = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(bytes, rgbIV), CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
                s = Convert.ToBase64String(stream.ToArray());
                stream.Close();
                stream.Dispose();
                stream2.Close();
                stream2.Dispose();
                provider.Dispose();
            }
            catch (Exception)
            {
                s = "";
            }
            return(s);
        }
示例#8
0
        /// <summary>
        /// 通过DES加密数据
        /// </summary>
        /// <param name="targetValue">需要加密的目标数据</param>
        /// <param name="key">公共秘钥</param>
        /// <returns>返回加密好的数据</returns>
        static string Encrypt(string targetValue, string key)
        {
            if (string.IsNullOrEmpty(targetValue))
            {
                return(string.Empty);
            }
            var des = new DESCryptoServiceProvider();//实例化加解密对象

            byte[] inputByteArray = Encoding.Default.GetBytes(targetValue);
            //设置DES初始化向量
            des.IV = Encoding.Default.GetBytes(key.Substring(0, 8));
            //设置DES秘钥
            des.Key = Encoding.Default.GetBytes(key.Substring(0, 8));
            //创建内存流
            var ms = new MemoryStream();
            //使用内存流创建加密流
            CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            encStream.Write(inputByteArray, 0, inputByteArray.Length);
            encStream.FlushFinalBlock();

            var resultString = new StringBuilder();

            foreach (var item in ms.ToArray())
            {
                resultString.AppendFormat("{0:X2}", item);
            }

            encStream.Close();
            ms.Close();
            des.Dispose();
            return(resultString.ToString());
        }
示例#9
0
    public static string ToDESString(this string s, string key)
    {
        if (key.Length < 8)
        {
            throw new ArgumentException("参数[key]长度必须大于8", "key");
        }

        var dKey   = Encoding.Default.GetBytes(key.Substring(0, 8));
        var dIV    = Encoding.Default.GetBytes("10100100");
        var des    = new DESCryptoServiceProvider();
        var stream = new MemoryStream();

        using (var cs = new CryptoStream(stream, des.CreateEncryptor(dKey, dIV), CryptoStreamMode.Write))
        {
            using (var sw = new StreamWriter(cs))
            {
                sw.Write(s);
            }
        }
        var data = stream.ToArray();

        des.Dispose();
        stream.Close();
        return(Convert.ToBase64String(data));
    }
示例#10
0
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="data">解密数据</param>
        /// <param name="key">8位字符的密钥字符串(需要和加密时相同)</param>
        /// <param name="iv">8位字符的初始化向量字符串(需要和加密时相同)</param>
        /// <returns></returns>
        public static string DESDecrypt(string data, string key, string iv)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
            byte[] byIV  = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return(null);
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream             ms             = new MemoryStream(byEnc);
            CryptoStream             cst            = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader             sr             = new StreamReader(cst);

            cryptoProvider.Dispose();
            ms.Dispose();
            cst.Dispose();
            sr.Dispose();
            return(sr.ReadToEnd());
        }
示例#11
0
        private static string sKey = "L6Xe8dXVGISZ17LJy7GzZaeYGpeGfe";//默认密钥
        #region DESEnCode DES加密
        /// <summary>
        /// 加密(返回16进制字符串)
        /// </summary>
        /// <param name="pToEncrypt"></param>
        /// <returns></returns>
        public static string DESEnCode(this string pToEncrypt)
        {
            if (String.IsNullOrEmpty(pToEncrypt))
            {
                return(String.Empty);
            }
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);
            //建立加密对象的密钥和偏移量
            //原文使用ASCIIEncoding.ASCII方法的GetBytes方法
            //使得输入密码必须输入英文文本
            des.Key  = Encoding.ASCII.GetBytes(sKey.Substring(0, 8));
            des.IV   = Encoding.ASCII.GetBytes(sKey.Substring(sKey.Length - 8, 8));
            des.Mode = CipherMode.CBC;//官方建议:ECB 存在多个安全隐患,易被破解 https://msdn.microsoft.com/library/system.security.cryptography.ciphermode(v=vs.100).aspx
            StringBuilder ret;

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                }
                ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:x2}", b);//输出为16进制
                }
            }
            des.Dispose();

            return(ret.ToString());
        }
示例#12
0
        public byte [] DESEncode(byte [] msg, byte [] key)
        {
            byte[] crymsg = null;
            DESCryptoServiceProvider des    = null;
            CryptoStream             stream = null;
            MemoryStream             ms     = null;
            BinaryWriter             wr     = null;

            try
            {
                des = new DESCryptoServiceProvider();
                ms  = new MemoryStream();
                Array.Copy(key, des.Key, des.Key.Length);
                byte[] a = new byte[des.Key.Length];
                for (int i = 0; i < des.Key.Length; i++)
                {
                    a[i] = key[i];
                }
                des.Key = a;
                for (int i = 0; i < des.IV.Length; i++)
                {
                    des.IV[i] = key[des.Key.Length + i];
                }
                for (int i = 0; i < des.IV.Length; i++)
                {
                    a[i] = key[des.Key.Length + i];
                }
                des.IV = a;
                stream = new CryptoStream(ms, des.CreateEncryptor(des.Key, des.IV), CryptoStreamMode.Write);
                wr     = new BinaryWriter(stream);
                wr.Write(msg, 0, (int)msg.Length);
                wr.Close();
                stream.Close();
                crymsg = ms.ToArray();
            }
            catch
            {
                crymsg = null;
            }
            finally
            {
                if (wr != null)
                {
                    wr.Dispose();
                }
                if (ms != null)
                {
                    ms.Dispose();
                }
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (des != null)
                {
                    des.Dispose();
                }
            }
            return(crymsg);
        }
示例#13
0
        public static string DecryptDes(this string decryptString, string decryptKey)
        {
            DESCryptoServiceProvider dcsp    = new DESCryptoServiceProvider();
            MemoryStream             mStream = new MemoryStream();

            try
            {
                byte[] rgbKey         = Encoding.Default.GetBytes(decryptKey.Substring(0, 8));
                byte[] rgbIv          = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);

                using (var cStream = new CryptoStream(mStream, dcsp.CreateDecryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
                {
                    cStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cStream.FlushFinalBlock();
                    cStream.Close();
                }

                return(Encoding.Default.GetString(mStream.ToArray()));
            }
            catch
            {
                return(decryptString);
            }
            finally
            {
                mStream.Close();
                dcsp.Dispose();
            }
        }
示例#14
0
        public static string EncryptDes(this string encryptString, string encryptKey)
        {
            var dCsp    = new DESCryptoServiceProvider();
            var mStream = new MemoryStream();

            try
            {
                var rgbKey         = Encoding.Default.GetBytes(encryptKey.Substring(0, 8));
                var rgbIv          = Keys;
                var inputByteArray = Encoding.Default.GetBytes(encryptString);

                using (var cStream = new CryptoStream(mStream, dCsp.CreateEncryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
                {
                    cStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cStream.FlushFinalBlock();
                    cStream.Close();
                }

                return(Convert.ToBase64String(mStream.ToArray()));
            }
            catch
            {
                return(encryptString);
            }
            finally
            {
                mStream.Close();
                dCsp.Dispose();
            }
        }
示例#15
0
 public void Dispose()
 {
     CanDescramble = false;
     _Decryptor.Dispose();
     _Des.Dispose();
     _Decryptor = null;
     _Des       = null;
 }
示例#16
0
        /// <summary>
        /// DES解密
        /// <para>将一段DES密文通过CBC的方式根据privateKey和publicKey进行解密</para>
        /// <para>公钥和私钥只能是可以通过Encoding.GetBytes转换的字符串,否则密钥验证会失效</para>
        /// </summary>
        /// <typeparam name="T">要将密文解析成的类型</typeparam>
        /// <param name="content">密文</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="publicKey">公钥</param>
        /// <returns></returns>
        public static T DeEncryptDES <T>(string content, string privateKey, string publicKey)
        {
            T result = default(T);

            //如果要解密的对象是空,就无法解密,直接返回空
            if (StringUtil.IsEmpty(content))
            {
                return(result);
            }
            //如果私钥是空,则使用加密器支持的随机私钥
            if (StringUtil.IsEmpty(privateKey))
            {
                privateKey = string.Empty;
            }
            //如果公钥是空,则使用加密器支持的随机公钥
            if (StringUtil.IsEmpty(publicKey))
            {
                publicKey = string.Empty;
            }
            //定义一个DES加密、解密器
            DESCryptoServiceProvider manager = new DESCryptoServiceProvider();

            manager.Mode = CipherMode.CBC;
            //计算私钥
            byte[] privateKeyBytes = Encoding.Default.GetBytes(privateKey);
            //因为DES只支持8位密钥,所以这里公钥私钥长度都限制为8
            manager.Key = GeneralKeyBytes(privateKeyBytes, 8);
            //计算公钥
            byte[] publicKeyBytes = Encoding.Default.GetBytes(publicKey);
            //因为DES只支持8位密钥,所以这里公钥私钥长度都限制为8
            manager.IV = GeneralKeyBytes(publicKeyBytes, 8);
            byte[] contentBytes = Convert.FromBase64String(content);
            try
            {
                //定义一个临时变量存放解密后的明文的二进制数组
                //进行解密
                byte[] resultBytes = DoTransform(manager.CreateDecryptor(), contentBytes);
                //将解密后的明文数组反序列化为目标对象
                result = resultBytes.ToObject <T>();
            }
            catch (CryptographicException ce)
            {
                //如果发生解密异常则认为是密钥错误
                LogUtil.WriteException(ce.ToString());
            }
            catch (System.Runtime.Serialization.SerializationException se)
            {
                //如果发生序列化异常则认为是密文错误
                LogUtil.WriteException(se.ToString());
            }
            finally
            {
                manager.Dispose();
            }
            return(result);
        }
示例#17
0
        private static string EncryptDES(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider provider;

            byte[]       buffer;
            MemoryStream stream;
            string       str;
            CryptoStream stream2;
            string       str2;

            provider = new DESCryptoServiceProvider();
Label_0007:
            try
            {
                buffer       = Encoding.UTF8.GetBytes(pToEncrypt);
                provider.Key = Encoding.ASCII.GetBytes(sKey);
                provider.IV  = Encoding.ASCII.GetBytes(sKey);
                stream       = new MemoryStream();
                stream2      = new CryptoStream(stream, provider.CreateEncryptor(), 1);
Label_004D:
                try
                {
                    stream2.Write(buffer, 0, (int)buffer.Length);
                    stream2.FlushFinalBlock();
                    stream2.Close();
                    goto Label_007B;
                }
                finally
                {
Label_006E:
                    if (stream2 == null)
                    {
                        goto Label_007A;
                    }
                    stream2.Dispose();
                    Label_007A :;
                }
                Label_007B :
                str = Convert.ToBase64String(stream.ToArray());
                stream.Close();
                str2 = str;
                goto Label_009E;
            }
            finally
            {
Label_0093:
                if (provider == null)
                {
                    goto Label_009D;
                }
                provider.Dispose();
                Label_009D :;
            }
            Label_009E :
            return(str2);
        }
示例#18
0
        /// <summary>
        /// Takes an encrypted key in the form of a string as input
        /// and applies the DES encryption algorithm to produce an
        /// unencrypted byte array
        /// </summary>
        /// <param name="strEncryptedKey">Encrypted security key</param>
        /// <returns></returns>
        //  Revision History
        //  MM/DD/YY Who Version Issue# Description
        //  -------- --- ------- ------ -------------------------------------------
        //  06/21/13 RCG 2.70.77        Copied from CENTRON_AMI

        private byte[] DecryptHANKey(string strEncryptedKey)
        {
            int Discarded;

            SecureDataStorage        DataStorage     = null;
            DESCryptoServiceProvider Crypto          = null;
            MemoryStream             EncryptedStream = null;
            MemoryStream             DecryptedStream = null;
            string       strDecryptedKey             = null;
            StreamReader sr = null;

            try
            {
                DataStorage = new SecureDataStorage(SecureDataStorage.DEFAULT_LOCATION);
                Crypto      = new DESCryptoServiceProvider();
                Crypto.Key  = DataStorage.RetrieveSecureData(SecureDataStorage.ZIGBEE_KEY_ID);
                Crypto.IV   = DataStorage.RetrieveSecureData(SecureDataStorage.ZIGBEE_IV_ID);


                byte[] EncryptedKey = HexEncoding.GetBytes(strEncryptedKey, out Discarded);

                //Create a memory stream to the passed buffer.
                EncryptedStream = new MemoryStream(EncryptedKey);
                DecryptedStream = new MemoryStream();

                Encryption.DecryptData(Crypto, EncryptedStream, DecryptedStream);

                //We must rewind the stream
                DecryptedStream.Position = 0;

                // Create a StreamReader for reading the stream.
                sr = new StreamReader(DecryptedStream);

                // Read the stream as a string.
                strDecryptedKey = sr.ReadLine();
            }
            finally
            {
                // Close the streams.
                //Closing sr also closes DecryptedStream
                if (null != sr)
                {
                    sr.Close();
                }
                else
                {
                    DecryptedStream.Close();
                }
                EncryptedStream.Close();
                Crypto.Dispose();
            }
            //Transform the string into a byte array
            return(HexEncoding.GetBytes(strDecryptedKey, out Discarded));
        }
示例#19
0
        /// <summary>
        /// DES对称加密
        /// </summary>
        /// <param name="content">要加密的内容,如果是一个对象必须要实现<see cref="SerializableAttribute"/></param>
        /// <param name="privateKey">加密的密钥</param>
        /// <returns></returns>
        public static byte[] EncryptDES(object content, string privateKey)
        {
            byte[] result = new byte[0];
            if (StringUtil.IsNullOrEmpty(content))
            {
                return(result);
            }
            DESCryptoServiceProvider provider = (DESCryptoServiceProvider)GetEncryptFactory <DESCryptoServiceProvider>(privateKey, 8);

            result = Encrypt(provider.CreateEncryptor(), SerializeUtil.ToBinary(content));
            provider.Dispose();
            return(result);
        }
示例#20
0
 public void Dispose()
 {
     try
     {
         if (m_des != null)
         {
             m_des.Dispose();
         }
     }
     finally
     {
         m_des = null;
     }
 }
示例#21
0
        /// <summary>
        /// 内容加密
        /// </summary>
        private void EThreadContent()
        {
            byte[]       btRKey     = Encoding.UTF8.GetBytes(KeySecret);
            byte[]       btRIV      = Encoding.UTF8.GetBytes(IVSecret);
            MemoryStream _ms        = new MemoryStream(Encoding.UTF8.GetBytes(strContent));
            FileStream   NewFStream = new FileStream(strFilePath, FileMode.OpenOrCreate, FileAccess.Write);

            NewFStream.SetLength((long)0);
            byte[] buffer = new byte[0x400];
            int    MinNum = 0;
            long   length = _ms.Length;
            int    MaxNum = (int)(length / ((long)0x400));

            if (PBar != null)
            {
                PBar.Maximum = MaxNum;
            }

            DES myDES = new DESCryptoServiceProvider
            {
                Key = btRKey,
                IV  = btRIV
            };
            CryptoStream CStream = new CryptoStream(NewFStream, myDES.CreateEncryptor(), CryptoStreamMode.Write);

            while (MinNum < length)
            {
                int count = _ms.Read(buffer, 0, 0x400);
                CStream.Write(buffer, 0, count);
                MinNum += count;
                try
                {
                    if (PBar != null && PBar.Value < PBar.Maximum)
                    {
                        PBar.Value++;
                    }
                }
                catch
                {
                }
            }
            CStream.FlushFinalBlock();
            CStream.Close();
            NewFStream.Close();
            _ms.Close();
            myDES.Dispose();
            MessageBox.Show("写入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
示例#22
0
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    des.Dispose();
                }

                // Note disposing has been done.
                disposed = true;
            }
        }
示例#23
0
 /// <summary>
 ///  Generic DES Decryption Function
 /// </summary>
 /// <param name="data"></param>
 /// <param name="key"></param>
 /// <param name="iv"></param>
 /// <param name="padding"></param>
 /// <param name="mode"></param>
 /// <returns></returns>
 internal static byte[] Decrypt(byte[] data, byte[] key, byte[] iv, PaddingMode padding, CipherMode mode)
 {
     try
     {
         var algorithm = new DESCryptoServiceProvider {
             Padding = padding, Mode = mode
         };
         ICryptoTransform decryptor = algorithm.CreateDecryptor(key, iv);
         var retVal = Crypter(data, key, iv, decryptor);
         decryptor.Dispose();
         algorithm.Dispose();
         return(retVal);
     }
     catch (CryptographicException ex)
     {
         throw new ApplicationException("Error during des decryption of license code.", ex);
     }
 }
示例#24
0
 public static string DESDecrypt(string val, string key = "?!@$%?&?", string vi = "?!@$??&?")
 {
     if (!string.IsNullOrWhiteSpace(val))
     {
         if (key.Length < 8)
         {
             key = string.Format("{0}?!@$%?&?", key);
         }
         else
         {
             if (key.Length > 8)
             {
                 key = key.Substring(0, 8);
             }
         }
         if (vi.Length < 8)
         {
             vi = string.Format("{0}?!@$%?&?", vi);
         }
         else
         {
             if (vi.Length > 8)
             {
                 vi = vi.Substring(0, 8);
             }
         }
         SymmetricAlgorithm sa = new DESCryptoServiceProvider();
         sa.Key = Encoding.UTF8.GetBytes(key);
         sa.IV  = Encoding.UTF8.GetBytes(vi);
         ICryptoTransform ct  = sa.CreateDecryptor();
         byte[]           byt = Convert.FromBase64String(val);
         MemoryStream     ms  = new MemoryStream();
         CryptoStream     cs  = new CryptoStream(ms, ct, CryptoStreamMode.Write);
         cs.Write(byt, 0, byt.Length);
         cs.FlushFinalBlock();
         ms.Dispose();
         cs.Dispose();
         sa.Dispose();
         ct.Dispose();
         return(Encoding.UTF8.GetString(ms.ToArray()));
     }
     return(string.Empty);
 }
示例#25
0
        /// <summary>
        /// 解密。
        /// </summary>
        /// <param name="m_Need_Encode_String"></param>
        /// <returns></returns>
        public static string Decode(string m_Need_Encode_String)
        {
            if (m_Need_Encode_String == null)
            {
                throw new ArgumentNullException(nameof(m_Need_Encode_String));
            }
            DESCryptoServiceProvider objDES = new DESCryptoServiceProvider();

            byte[]       arrInput        = Convert.FromBase64String(m_Need_Encode_String);
            MemoryStream objMemoryStream = new MemoryStream(arrInput);
            CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateDecryptor(arrDESKey, arrDESIV), CryptoStreamMode.Read);
            StreamReader objStreamReader = new StreamReader(objCryptoStream);

            objDES.Dispose();
            objMemoryStream.Dispose();
            objCryptoStream.Dispose();
            objStreamReader.Dispose();
            return(objStreamReader.ReadToEnd());
        }
示例#26
0
        public static string DesHelper(string str, string key, string iv, Mode mode)
        {
            if (key.Length != 8)
            {
                throw new ArgumentOutOfRangeException("Key length should be 8!");
            }

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = Convert.FromBase64String(str);
            des.Key = Encoding.UTF8.GetBytes(key);
            des.IV  = Encoding.UTF8.GetBytes(iv);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs;

            if (mode == Mode.Encrypt)
            {
                cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            }
            else if (mode == Mode.Decrypt)
            {
                cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            }
            else
            {
                throw new ArgumentOutOfRangeException("Mode is not valid");
            }
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            cs.Dispose();
            ms.Dispose();
            des.Dispose();

            if (mode == Mode.Encrypt)
            {
                return(Convert.ToBase64String(ms.ToArray()));
            }
            else
            {
                return(Encoding.Default.GetString(ms.ToArray()));
            }
        }
示例#27
0
        public JObject DESEncrypt(string str, string key = "", string iv = "")
        {
            JObject obj = new JObject();
            int     a   = 1;
            int     b   = a / (a - 1);

            try
            {
                if (key == "")
                {
                    key = System.Configuration.ConfigurationManager.AppSettings["byKey"];
                }
                if (iv == "")
                {
                    iv = System.Configuration.ConfigurationManager.AppSettings["byIV"];
                }

                byte[] byKey = Encoding.Default.GetBytes(key);
                byte[] byIV  = Encoding.Default.GetBytes(iv);

                DESCryptoServiceProvider dESCrypto    = new DESCryptoServiceProvider();
                MemoryStream             memory       = new MemoryStream();                                                                       //先创建 一个内存流
                CryptoStream             cryptoStream = new CryptoStream(memory, dESCrypto.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write); //将内存流连接到加密转换流
                StreamWriter             sw           = new StreamWriter(cryptoStream);
                sw.Write(str);                                                                                                                    //将要加密的字符串写入加密转换流
                sw.Close();
                cryptoStream.Close();
                memory.Close();
                dESCrypto.Dispose();
                byte[] buffer = memory.ToArray();               //将加密后的流转换为字节数组

                string result = Convert.ToBase64String(buffer); //将加密后的字节数组转换为字符串
                obj.Add("success", true);
                obj.Add("result", result);
            }
            catch (Exception ex)
            {
                obj.Add("success", false);
                obj.Add("result", ex.Message);
            }
            return(obj);
        }
示例#28
0
        /// <summary>
        /// ¼ÓÃÜ
        /// </summary>
        /// <param name="pToEncrypt"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string EncryptDES(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider provider;

            byte[]       buffer;
            MemoryStream stream = null;
            string       str;
            CryptoStream cryptoStream = null;

            provider = new DESCryptoServiceProvider();
            try
            {
                buffer       = Encoding.UTF8.GetBytes(pToEncrypt);
                provider.Key = Encoding.ASCII.GetBytes(sKey);
                provider.IV  = Encoding.ASCII.GetBytes(sKey);
                stream       = new MemoryStream();
                cryptoStream = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
                cryptoStream.Write(buffer, 0, (int)buffer.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                str = Convert.ToBase64String(stream.ToArray());
                stream.Close();
            }
            finally
            {
                if (cryptoStream != null)
                {
                    cryptoStream.Dispose();
                }
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (provider != null)
                {
                    provider.Dispose();
                }
            }

            return(str);
        }
示例#29
0
        /// <summary>
        /// 内容解密
        /// </summary>
        private void DThreadCotent()
        {
            if (File.Exists(strFilePath))
            {
                FileStream FStream = new FileStream(strFilePath, FileMode.Open, FileAccess.Read);
                byte[]     bytes   = new byte[FStream.Length];
                FStream.Read(bytes, 0, bytes.Length);
                FStream.Seek(0, SeekOrigin.Begin);

                DES          myDES      = new DESCryptoServiceProvider();
                MemoryStream _DeContent = new MemoryStream();

                try
                {
                    byte[] btRKey = Encoding.UTF8.GetBytes(KeySecret);
                    byte[] btRIV  = Encoding.UTF8.GetBytes(IVSecret);

                    if (bytes.Length > 0)
                    {
                        CryptoStream CStream = new CryptoStream(_DeContent, myDES.CreateDecryptor(btRKey, btRIV), CryptoStreamMode.Write);
                        CStream.Write(bytes, 0, bytes.Length);
                        CStream.FlushFinalBlock();
                        DeContent = Encoding.UTF8.GetString(_DeContent.ToArray());
                        CStream.Close();
                        CStream.Dispose();
                    }
                }
                catch
                {
                    MessageBox.Show("配置读取失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    _DeContent.Close();
                    _DeContent.Dispose();
                    FStream.Close();
                    FStream.Close();
                    myDES.Dispose();
                }
            }
        }
示例#30
0
        /// <summary>
        /// 加密。
        /// </summary>
        /// <param name="m_Need_Encode_String"></param>
        /// <returns></returns>
        public static string Encode(string m_Need_Encode_String)
        {
            if (m_Need_Encode_String == null)
            {
                throw new ArgumentNullException(nameof(m_Need_Encode_String));
            }
            DESCryptoServiceProvider objDES          = new DESCryptoServiceProvider();
            MemoryStream             objMemoryStream = new MemoryStream();
            CryptoStream             objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateEncryptor(arrDESKey, arrDESIV), CryptoStreamMode.Write);
            StreamWriter             objStreamWriter = new StreamWriter(objCryptoStream);

            objStreamWriter.Write(m_Need_Encode_String);
            objStreamWriter.Flush();
            objCryptoStream.FlushFinalBlock();
            objMemoryStream.Flush();
            objDES.Dispose();
            objMemoryStream.Dispose();
            objCryptoStream.Dispose();
            objStreamWriter.Dispose();
            return(Convert.ToBase64String(objMemoryStream.GetBuffer(), 0, (int)objMemoryStream.Length));
        }