예제 #1
0
        /// <summary>
        /// 以 DES 演算法加密 byte[]. baKey 應為 8 bytes, baIV 應為 8 bytes.
        /// </summary>
        /// <param name="baPlainText"></param>
        /// <param name="baKey"></param>
        /// <param name="baIV"></param>
        /// <returns></returns>
        public static byte[] EncryptDES(byte[] baPlainText, byte[] baKey, byte[] baIV)
        {
            try
            {
                byte[] baEncrypt = null;
                using (DESCryptoServiceProvider des1 = new DESCryptoServiceProvider())
                {
                    des1.Key = baKey;
                    des1.IV  = baIV;

                    baEncrypt = Encrypt(des1, baPlainText);
                    if (baEncrypt == null)
                    {
                        return(null);
                    }
                    des1.Clear();
                }
                return(baEncrypt);
            }
            catch (Exception e1)
            {
                msError = e1.Message;
                return(null);
            }
        }
예제 #2
0
파일: Form1.cs 프로젝트: r-kill/c-sharp
        } //compute hash from arguments and return hash value as string

        private static string GetDESHash(string text)
        {
            //create variables for computing hash and making it a string
            UnicodeEncoding UniCode = new UnicodeEncoding();

            byte[] HashResult;
            byte[] msg        = UniCode.GetBytes(text);
            DES    hashString = new DESCryptoServiceProvider();

            //generate a weak KEY and Initialization Vector for the hash algorithm
            hashString.GenerateKey();
            hashString.GenerateIV();
            ICryptoTransform encryptor = hashString.CreateEncryptor(hashString.Key, hashString.IV);
            string           Str       = "";

            //compute hash with DES module and format output as string
            //convert bytes in HashResult to string values
            HashResult = encryptor.TransformFinalBlock(msg, 0, msg.Length);
            foreach (byte x in HashResult)
            {
                Str += String.Format("{0:x2}", x);
            }

            //clear excess resource usage
            hashString.Clear();
            return(Str);
        } //compute hash from arguments and return hash value as string
        /// <summary>
        /// Event that fires when the des encrypt button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDESEncrypt_Click(object sender, RoutedEventArgs e)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            des.KeySize = ((ListItem)this.cboDESKeySize.SelectedItem).Value;
            des.Mode    = (CipherMode)((ListItem)this.cboDESMode.SelectedItem).Value;
            des.Padding = (PaddingMode)((ListItem)this.cboDESPadding.SelectedItem).Value;
            //des.BlockSize = ;

            des.GenerateIV();
            this.txtDESIV.Text = Convert.ToBase64String(des.IV);

            //generate the key and insert it into the text box
            des.GenerateKey();
            this.txtDESPassword.Text = Convert.ToBase64String(des.Key);

            byte[] byteInputText = encoding.GetBytes(this.txtDESInput.Text);

            byte[] cipherText;
            using (ICryptoTransform crypto = des.CreateEncryptor())
            {
                cipherText = crypto.TransformFinalBlock(byteInputText, 0, byteInputText.Length - 1);
                des.Clear();
            }

            this.txtDESOutput.Text = Convert.ToBase64String(cipherText);
        }
예제 #4
0
        /// <summary>
        /// Use DES encryption to encrypt the input Data bytes with the input Key bytes.
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Data"></param>
        /// <param name="Mode"></param>
        /// <returns></returns>
        public static byte[] EncryptDES(
            this byte[] Data, byte[] Key, CipherMode Mode = CipherMode.ECB, byte[] IV = null)
        {
            var tdes = new DESCryptoServiceProvider();

            tdes.Key = Key;

            // init vector.
            if (IV == null)
            {
                tdes.IV = Key;
            }
            else
            {
                tdes.IV = IV;
            }

            // mode of operation. there are 4 modes.
            tdes.Mode = Mode;

            // padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.None;

            ICryptoTransform cTransform = tdes.CreateEncryptor();

            // do the actual encrypt of the input data bytes.
            byte[] res = cTransform.TransformFinalBlock(Data, 0, Data.Length);

            // release resources
            tdes.Clear();

            return(res);
        }
예제 #5
0
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="encryptStr">密文字符串</param>
        /// <returns>明文</returns>
        public static string DESDecrypt(string key, string iv, string encryptStr)
        {
            byte[] bKey      = Encoding.UTF8.GetBytes(key);
            byte[] bIV       = Encoding.UTF8.GetBytes(iv);
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            string decrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();

            return(decrypt);
        }
예제 #6
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str">待解密的字符串</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string Decrypt(string str)
        {
            try
            {
                string decryptKey                 = _keyt;
                byte[] rgbKey                     = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV                      = _keys;
                byte[] inputByteArray             = Convert.FromBase64String(str);
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                MemoryStream             mStream  = new MemoryStream();
                CryptoStream             cStream  = new CryptoStream(mStream, provider.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                string result = Encoding.UTF8.GetString(mStream.ToArray());
                //
                provider.Clear();
                mStream.Close();
                mStream.Dispose();
                cStream.Close();
                cStream.Dispose();

                rgbKey         = null;
                rgbIV          = null;
                inputByteArray = null;

                return(result);
            }
            catch
            {
                return(str);
            }
        }
예제 #7
0
        //---------------------------------------------------------------------------------------------------------//
        //---------------------------------------------------------------------------------------------------------//

        public static string DesDecrypt(string encryptStr, string Key)  //Key format : @"Key_val" ... Key= 8 characters string= 64 bit
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV  = Encoding.UTF8.GetBytes(IVdes);
            encryptStr = encryptStr.Replace(" ", "+");
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            string decrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();

            return(decrypt);
        }
예제 #8
0
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Decrypt(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(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV  = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").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();
            cs.Dispose();
            des.Clear();
            return(Encoding.Default.GetString(ms.ToArray()));
        }
예제 #9
0
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="code">加密字符串</param>
        /// <param name="Key">密匙</param>
        /// <returns>被加密字符串</returns>
        public static byte[] DesDecryptByByte(byte[] code, string Key)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray        = code;

                if (CharSet.Trim() == "")
                {
                    des.Key = ASCIIEncoding.Default.GetBytes(Key);
                    des.IV  = ASCIIEncoding.Default.GetBytes(Key);
                }
                else
                {
                    des.Key = ASCIIEncoding.GetEncoding(CharSet).GetBytes(Key);
                    des.IV  = ASCIIEncoding.GetEncoding(CharSet).GetBytes(Key);
                }
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                byte[] res = ms.ToArray();
                cs.Close();
                des.Clear();
                ms.Close();
                return(res);
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
                return(null);
            }
        }
예제 #10
0
        /// <summary>
        /// Method uses AES to decrypt a ciphertext byte array using the given encryption key and initialization vector.
        /// </summary>
        /// <param name="cipherText">Ciphertext bytes to decrypt</param>
        /// <param name="key">Encryption key</param>
        /// <param name="iv">Initialization vector</param>
        /// <returns>Plaintext string</returns>
        public static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
        {
            byte[] output;

            //Create memory stream from the input bytes
            using (MemoryStream mStream = new MemoryStream())
            {
                var crypto = new DESCryptoServiceProvider
                {
                    //Set key and iv
                    Key = DEFAULT_KEY.GetBytesFromHexString(),
                    IV  = DEFAULT_IV.GetBytesFromHexString()
                };

                CryptoStream cStream = new CryptoStream(mStream
                                                        , crypto.CreateDecryptor(), CryptoStreamMode.Write);
                cStream.Write(cipherText, 0, cipherText.Length);
                cStream.FlushFinalBlock();
                cStream.Close();

                output = mStream.ToArray();

                //Close resources
                mStream.Close();
                crypto.Clear();
            }

            //Return encoded string
            return(Encoding.UTF8.GetString(output));
        }
예제 #11
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainStr">需要加密的字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>加密后的base64字符串</returns>
        public static string Encrypt(string plainStr, string key = null)
        {
            if (key == null)
            {
                key = _key;
            }
            byte[] bKey      = Encoding.UTF8.GetBytes(key);
            byte[] bIV       = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

            string encrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            des.Mode    = CipherMode.ECB;
            des.Padding = PaddingMode.Zeros;
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        encrypt = System.Convert.ToBase64String(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();

            return(encrypt);
        }
예제 #12
0
        //----------------------------------------------------------------------------------------------------------//
        //---------------------------------------------------------------------------------------------------------//

        public static string DesEncrypt(string plainStr, string Key)
        {
            byte[] bKey      = Encoding.UTF8.GetBytes(Key);
            byte[] bIV       = Encoding.UTF8.GetBytes(IVdes);
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

            string encrypt = null;
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        encrypt = Convert.ToBase64String(mStream.ToArray());
                    }
                }
            }
            catch { }
            des.Clear();

            return(encrypt);
        }
예제 #13
0
        /// <summary>
        /// DES 解密(数据加密标准,速度较快,适用于加密大量数据的场合)
        /// </summary>
        /// <param name="decryptString">待解密的密文</param>
        /// <param name="decryptKey">解密的密钥</param>
        /// <returns>returns</returns>
        public static string DesDecrypt(string decryptString, string decryptKey)
        {
            //if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }
            //if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
            //if (DecryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }

            decryptKey = CompletionKey(decryptKey);
            var mStrDecrypt  = "";
            var mDesProvider = new DESCryptoServiceProvider();

            try
            {
                var mBtDecryptString = Convert.FromBase64String(decryptString);
                var mStream          = new MemoryStream();
                var mCstream         = new CryptoStream(mStream, mDesProvider.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), DefaultIVKeys), CryptoStreamMode.Write);
                mCstream.Write(mBtDecryptString, 0, mBtDecryptString.Length);
                mCstream.FlushFinalBlock();
                mStrDecrypt = Encoding.Default.GetString(mStream.ToArray());
                mStream.Close();
                mStream.Dispose();
                mCstream.Close();
                mCstream.Dispose();
            }
            catch
            {
            }
            finally
            {
                mDesProvider.Clear();
            }
            return(mStrDecrypt);
        }
        /// <summary>
        /// Des解密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">des密钥,长度必须8位</param>
        /// <param name="iv">密钥向量</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>解密后的字符串</returns>
        public static string DecryptDes(string source, string key, string iv, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            byte[] rgbKeys = GetDesKey(key, encoding),
            rgbIvs         = GetDesKey(iv, encoding),
            inputByteArray = Convert.FromBase64String(source);
            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                                        desProvider.CreateDecryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                        cryptoStream.FlushFinalBlock();
                        cryptoStream.Close();
                        memoryStream.Flush();
                        memoryStream.Close();
                        desProvider.Clear();
                        byte[] result = memoryStream.ToArray();
                        return(encoding.GetString(result));
                    }
                }
            }
        }
예제 #15
0
        /// <summary>
        /// DES加密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string DESEncrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            //des.Key = Encoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            //des.IV = Encoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.Key = Encoding.UTF8.GetBytes(Md5Encryptor16(sKey).Substring(0, 8));
            des.IV  = Encoding.UTF8.GetBytes(Md5Encryptor16(sKey).Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream           cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();

            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            des.Clear();
            ms.Close();
            cs.Close();
            return(ret.ToString());
        }
예제 #16
0
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="plainStr">明文字符串</param>
        /// <param name="key">加密密钥长度64位(8字节)</param>
        /// <param name="iv">加密向量长度64位以上(8个字节以上)</param>
        /// <param name="isBase64Code">是否是Base64编码,否则是16进制编码</param>
        /// <param name="mode">加密模式</param>
        /// <param name="padding">填充模式</param>
        /// <returns>密文</returns>
        public static string DESEncrypt(string plainStr, string key = DefaultDESKey, string iv = DefaultDESIV, bool isBase64Code = true, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7)
        {
            byte[] bKey      = Encoding.UTF8.GetBytes(key);
            byte[] bIV       = Encoding.UTF8.GetBytes(iv);
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

            string encrypt = null;
            var    des     = new DESCryptoServiceProvider();

            try
            {
                des.Mode    = mode;
                des.Padding = padding;
                using (var mStream = new MemoryStream())
                {
                    using (var cStream = new CryptoStream(mStream, des.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        if (isBase64Code)
                        {
                            encrypt = Convert.ToBase64String(mStream.ToArray());
                        }
                        else
                        {
                            ConvertHelper.ToString(mStream.ToArray());
                        }
                    }
                }
            }
            catch { }
            des.Clear();

            return(encrypt);
        }
예제 #17
0
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="pToDecrypt">待解密字符串</param>
        /// <returns>解密后的字符串</returns>
        public string Decrypt(string pToDecrypt)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = desKey;
            des.IV  = desIV;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

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

            byte[] ret = ms.ToArray();

            ms.Close();
            cs.Close();
            des.Clear();

            return(Encoding.Default.GetString(ret));
        }
예제 #18
0
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="pToEncrypt">待加密字符串</param>
        /// <returns>加密后的字符串</returns>
        public string Encrypt(string pToEncrypt)
        {
            if (pToEncrypt == null || pToEncrypt.ToString() == "")
            {
                return("");
            }
            else
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
                des.Key = desKey;
                des.IV  = desIV;
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);//格式化为十六进制
                }
                ms.Close();
                cs.Close();
                des.Clear();
                return(ret.ToString());
            }
        }
예제 #19
0
        /// <summary>
        /// DES 加密(数据加密标准,速度较快,适用于加密大量数据的场合)
        /// </summary>
        /// <param name="EncryptString">待加密的明文</param>
        /// <param name="EncryptKey">加密的密钥</param>
        /// <returns>加密后的密文</returns>
        public static string DESEncrypt(string EncryptString, string EncryptKey)
        {
            if (string.IsNullOrEmpty(EncryptString))
            {
                throw (new Exception("明文不得为空!"));
            }
            if (string.IsNullOrEmpty(EncryptKey))
            {
                throw (new Exception("密钥不得为空!"));
            }
            if (EncryptKey.Length != 8)
            {
                EncryptKey = MD5Encrypt16(EncryptKey).Substring(0, 8);
            }
            byte[] m_btIV       = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            string m_strEncrypt = "";
            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();

            try
            {
                byte[]       m_btEncryptString = Encoding.Default.GetBytes(EncryptString);
                MemoryStream m_stream          = new MemoryStream();
                CryptoStream m_cstream         = new CryptoStream(m_stream, m_DESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
                m_cstream.FlushFinalBlock();
                //m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
                byte[] bt1 = m_stream.ToArray();
                foreach (byte bt in m_stream.ToArray())
                {
                    m_strEncrypt += bt.ToString("X2");
                }
                m_stream.Close();
                m_stream.Dispose();
                m_cstream.Close();
                m_cstream.Dispose();
            }
            catch (IOException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                m_DESProvider.Clear();
            }

            return(m_strEncrypt);
        }
예제 #20
0
        /// <summary>
        /// DES 解密(数据加密标准,速度较快,适用于加密大量数据的场合)
        /// </summary>
        /// <param name="DecryptString">待解密的密文</param>
        /// <returns>returns</returns>
        public static string DESDecrypt(string DecryptString)
        {
            if (DecryptString == "")
            {
                return("");
            }
            string DecryptKey = key;

            if (string.IsNullOrEmpty(DecryptString))
            {
                throw (new Exception("密文不得为空"));
            }

            if (string.IsNullOrEmpty(DecryptKey))
            {
                throw (new Exception("密钥不得为空"));
            }

            if (DecryptKey.Length != 8)
            {
                throw (new Exception("密钥必须为8位"));
            }

            byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

            string m_strDecrypt = "";

            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();

            try
            {
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);

                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);

                m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);

                m_cstream.FlushFinalBlock();

                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());

                m_stream.Close(); m_stream.Dispose();

                m_cstream.Close(); m_cstream.Dispose();
            }
            //catch (IOException ex) { throw ex; }
            //catch (CryptographicException ex) { throw ex; }
            //catch (ArgumentException ex) { throw ex; }
            //catch (Exception ex) { throw ex; }
            catch (Exception ex) {
                Log4Net.Error(typeof(Security), "解密错误:" + DecryptString, ex);
                return("");
            }
            finally { m_DESProvider.Clear(); }

            return(m_strDecrypt);
        }
예제 #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //身份校验
            if (!InterfaceTool.IdentityVerify(Request))
            {
                Json = JsonConvert.SerializeObject(new DicPackage(false, null, "身份认证错误!").DicInfo());
                return;
            }

            string strKey        = Request.Params["Key"];
            string strCipherText = HttpUtility.UrlDecode(Request.Params["Value"]);
            string password2     = DES_IV.IV;
            string cipher        = string.Empty;

            try
            {
                if (strKey == null || strCipherText == null)
                {
                    Json = JsonConvert.SerializeObject(new DicPackage(false, null, "参数错误,DES解密失败!").DicInfo());
                    return;
                }

                char[] key = new char[8];
                if (strKey.Length > 8)
                {
                    strKey = strKey.Remove(8);
                }
                strKey.CopyTo(0, key, 0, strKey.Length);

                char[] iv = new char[8];
                if (password2.Length > 8)
                {
                    password2 = password2.Remove(8);
                }
                password2.CopyTo(0, iv, 0, password2.Length);

                strCipherText = strCipherText.Replace(" ", "+");
                SymmetricAlgorithm serviceProvider = new DESCryptoServiceProvider();
                serviceProvider.Key = Encoding.ASCII.GetBytes(key);
                serviceProvider.IV  = Encoding.ASCII.GetBytes(iv);

                byte[]       contentArray = Convert.FromBase64String(strCipherText);
                MemoryStream memoryStream = new MemoryStream(contentArray);
                CryptoStream cryptoStream = new CryptoStream(memoryStream, serviceProvider.CreateDecryptor(), CryptoStreamMode.Read);
                StreamReader streamReader = new StreamReader(cryptoStream);

                Json = JsonConvert.SerializeObject(new DicPackage(true, streamReader.ReadToEnd(), null).DicInfo());

                streamReader.Dispose();
                cryptoStream.Dispose();
                memoryStream.Dispose();
                serviceProvider.Clear();
            }
            catch (Exception ex)
            {
                Json = JsonConvert.SerializeObject(new DicPackage(false, null, string.Format("{0}:DES解密数据发生异常。{1}", ex.Source, ex.Message)).DicInfo());
            }
        }
예제 #22
0
        /// <summary>Encrypt ScopedPdu using DES encryption protocol</summary>
        /// <param name="unencryptedData">Unencrypted ScopedPdu byte array</param>
        /// <param name="offset">Offset to start encryption</param>
        /// <param name="length">Length of data to encrypt</param>
        /// <param name="key">Encryption key. Key has to be at least 32 bytes is length</param>
        /// <param name="engineBoots">Authoritative engine boots value</param>
        /// <param name="engineTime">Authoritative engine time value. Not used for DES</param>
        /// <param name="privacyParameters">Privacy parameters out buffer. This field will be filled in with information
        /// required to decrypt the information. Output length of this field is 8 bytes and space has to be reserved
        /// in the USM header to store this information</param>
        /// <param name="authDigest">Authentication digest class reference. Not used by DES and can be null.</param>
        /// <returns>Encrypted byte array</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key is null or length of the encryption key is too short.</exception>
        public byte[] Encrypt(byte[] unencryptedData, int offset, int length, byte[] key, int engineBoots, int engineTime, out byte[] privacyParameters, IAuthenticationDigest authDigest)
        {
            if (key == null || key.Length < MinimumKeyLength)
            {
                throw new ArgumentOutOfRangeException(nameof(key), "Encryption key length has to 32 bytes or more.");
            }

            privacyParameters = GetSalt(engineBoots);
            byte[] iv = GetIV(key, privacyParameters);

            // DES uses 8 byte keys but we need 16 to encrypt ScopedPdu. Get first 8 bytes and use them as encryption key
            byte[] outKey = GetKey(key);

            int div = (int)Math.Floor(length / 8.0);

            if ((length % 8) != 0)
            {
                div += 1;
            }

            int newLength = div * 8;

            byte[] result = new byte[newLength];
            byte[] buffer = new byte[newLength];

            byte[] inbuffer   = new byte[8];
            byte[] cipherText = iv;
            int    posIn      = 0;
            int    posResult  = 0;

            Buffer.BlockCopy(unencryptedData, offset, buffer, 0, length);

            DES des = new DESCryptoServiceProvider
            {
                Mode    = CipherMode.ECB,
                Padding = PaddingMode.None,
            };

            ICryptoTransform transform = des.CreateEncryptor(outKey, null);

            for (int b = 0; b < div; b++)
            {
                for (int i = 0; i < 8; i++)
                {
                    inbuffer[i] = (byte)(buffer[posIn] ^ cipherText[i]);
                    posIn++;
                }

                transform.TransformBlock(inbuffer, 0, inbuffer.Length, cipherText, 0);
                Buffer.BlockCopy(cipherText, 0, result, posResult, cipherText.Length);

                posResult += cipherText.Length;
            }

            des.Clear();

            return(result);
        }
예제 #23
0
        protected override void DisposeHostedRes()
        {
            _des.Clear();

            if (_des as IDisposable != null)
            {
                ((IDisposable)_des).Dispose();
            }
        }
예제 #24
0
        /// <summary>
        /// DES 加密(数据加密标准,速度较快,适用于加密大量数据的场合)
        /// </summary>
        /// <param name="EncryptString">待加密的密文</param>
        /// <param name="EncryptKey">加密的密钥</param>
        /// <returns>returns</returns>
        public static string DESEncrypt(string EncryptString, string EncryptKey, Encoding EncodingUsing = null)
        {
            if (string.IsNullOrEmpty(EncryptString))
            {
                throw (new Exception("密文不得为空"));
            }

            if (string.IsNullOrEmpty(EncryptKey))
            {
                throw (new Exception("密钥不得为空"));
            }

            if (EncryptKey.Length != 8)
            {
                throw (new Exception("密钥必须为8位"));
            }

            if (EncodingUsing == null)
            {
                EncodingUsing = new UTF8Encoding();
            }

            byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

            string m_strEncrypt = "";

            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();

            try
            {
                byte[] m_btEncryptString = EncodingUsing.GetBytes(EncryptString);

                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateEncryptor(EncodingUsing.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);

                m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);

                m_cstream.FlushFinalBlock();

                m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());

                m_stream.Close();
                m_stream.Dispose();

                m_cstream.Close();
                m_cstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_DESProvider.Clear(); }

            return(m_strEncrypt);
        }
        /// <summary>
        /// decrypt value
        /// </summary>
        /// <param name="strKey"></param>
        /// <param name="strData"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        private string Decrypt(string strKey, string strData)
        {
            string strValue = "";

            if (!(strData == ""))
            {
                if (strKey.Length < 16)
                {
                    strKey = strKey.PadRight(16 - strKey.Length, 'X').Substring(0, 16);
                }
                else
                {
                    if (strKey.Length > 16)
                    {
                        strKey = strKey.Substring(0, 16);
                    }
                }
                byte[] byteKey    = Encoding.UTF8.GetBytes(strKey.Substring(0, 8));
                byte[] byteVector = Encoding.UTF8.GetBytes(strKey.Substring(8));
                byte[] byteData   = new byte[strData.Length + 1];
                try
                {
                    byteData = Convert.FromBase64String(strData);
                }
                catch
                {
                    strValue = strData;
                }
                if (strValue == "")
                {
                    try
                    {
                        DESCryptoServiceProvider objDES          = new DESCryptoServiceProvider();
                        System.IO.MemoryStream   objMemoryStream = new System.IO.MemoryStream();
                        CryptoStream             objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write);
                        objCryptoStream.Write(byteData, 0, byteData.Length);
                        objCryptoStream.FlushFinalBlock();
                        System.Text.Encoding objEncoding = System.Text.Encoding.UTF8;
                        strValue = objEncoding.GetString(objMemoryStream.ToArray());
                        objDES.Clear();
                        objCryptoStream.Clear();
                        objCryptoStream.Close();
                    }
                    catch
                    {
                        strValue = "";
                    }
                }
            }
            else
            {
                strValue = strData;
            }
            return(strValue);
        }
예제 #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string password2 = DES_IV.IV;
                string password  = Request["Key"];
                string cleartext = Request["Value"];
                //password = "******";
                //cleartext = "AAA8N3ABfAAAxqAAAD";


                char[] key = new char[8];
                if (password.Length > 8)
                {
                    password = password.Remove(8);
                }
                password.CopyTo(0, key, 0, password.Length);

                char[] iv = new char[8];
                if (password2.Length > 8)
                {
                    password2 = password2.Remove(8);
                }
                password2.CopyTo(0, iv, 0, password2.Length);

                if (cleartext == null)
                {
                    Json = string.Empty;
                    return;
                }

                SymmetricAlgorithm serviceProvider = new DESCryptoServiceProvider();
                serviceProvider.Key = Encoding.ASCII.GetBytes(key);
                serviceProvider.IV  = Encoding.ASCII.GetBytes(iv);

                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, serviceProvider.CreateEncryptor(), CryptoStreamMode.Write);
                StreamWriter streamWriter = new StreamWriter(cryptoStream);

                streamWriter.Write(cleartext);
                streamWriter.Dispose();
                cryptoStream.Dispose();

                byte[] signData = memoryStream.ToArray();
                memoryStream.Dispose();
                serviceProvider.Clear();
                Json = Convert.ToBase64String(signData);
                //Json = HttpUtility.UrlEncode(Json);
            }
            catch (Exception ex)
            {
                Json = ex.Message;
            }
        }
예제 #27
0
 public bool EncryptData(string DataString, ref string EnString)
 {
     try
     {
         byte[] inputBuffers = System.Text.Encoding.UTF8.GetBytes(DataString);
         byte[] resultBytes  = null;
         using (ICryptoTransform cryptoTransform = desProvider.CreateEncryptor(this.rgbKey, this.rgbIV))
         {
             resultBytes = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
             desProvider.Clear();
         }
         EnString = Convert.ToBase64String(resultBytes);
         return(true);
     }
     catch (Exception EXMessage)
     {
         this.ErrorMsg = "企业号密钥En异常:" + EXMessage.Message;
         return(false);
     }
 }
예제 #28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string password2  = DES_IV.IV;
            string password   = Request["Key"];
            string ciphertext = HttpUtility.UrlDecode(Request["Value"]);
            //ciphertext = "C1hstQ2Erq3P2w4hJzr71%2fVqu%2biOq5WF";
            string cipher = string.Empty;

            //password = "******";

            try
            {
                char[] key = new char[8];
                if (password.Length > 8)
                {
                    password = password.Remove(8);
                }
                password.CopyTo(0, key, 0, password.Length);

                char[] iv = new char[8];
                if (password2.Length > 8)
                {
                    password2 = password2.Remove(8);
                }
                password2.CopyTo(0, iv, 0, password2.Length);

                if (ciphertext == null)
                {
                    Json = "null";
                    return;
                }
                ciphertext = ciphertext.Replace(" ", "+");
                SymmetricAlgorithm serviceProvider = new DESCryptoServiceProvider();
                serviceProvider.Key = Encoding.ASCII.GetBytes(key);
                serviceProvider.IV  = Encoding.ASCII.GetBytes(iv);

                byte[]       contentArray = Convert.FromBase64String(ciphertext);
                MemoryStream memoryStream = new MemoryStream(contentArray);
                CryptoStream cryptoStream = new CryptoStream(memoryStream, serviceProvider.CreateDecryptor(), CryptoStreamMode.Read);
                StreamReader streamReader = new StreamReader(cryptoStream);

                Json = streamReader.ReadToEnd();

                streamReader.Dispose();
                cryptoStream.Dispose();
                memoryStream.Dispose();
                serviceProvider.Clear();
            }
            catch (Exception ex)
            {
                Json = ex.Message;
            }
        }
예제 #29
0
        /// <summary>
        /// DES 加密
        /// </summary>
        /// <param name="data">需要加密的数据</param>
        /// <param name="key">密钥(必须 8 位)</param>
        /// <param name="vector">向量(必须 8 位)</param>
        /// <returns></returns>
        public static string DESEncrypt(string data, string key, string vector = null)
        {
            DESCryptoServiceProvider desCryptoService = null;
            MemoryStream             memoryStream     = null;
            CryptoStream             cryptoStream     = null;

            try
            {
                string result = null;

                using (desCryptoService = new DESCryptoServiceProvider())
                {
                    byte[] byteDataList = Encoding.UTF8.GetBytes(data);
                    desCryptoService.Key = ASCIIEncoding.ASCII.GetBytes(key);

                    if (string.IsNullOrEmpty(vector))
                    {
                        vector = key;
                    }
                    desCryptoService.IV = ASCIIEncoding.ASCII.GetBytes(vector);

                    using (memoryStream = new MemoryStream())
                    {
                        using (cryptoStream = new CryptoStream(memoryStream, desCryptoService.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(byteDataList, 0, byteDataList.Length);
                            cryptoStream.FlushFinalBlock();
                        }
                        result = Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
                return(result);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (cryptoStream != null)
                {
                    cryptoStream.Close();
                }
                if (memoryStream != null)
                {
                    memoryStream.Close();
                }
                if (desCryptoService != null)
                {
                    desCryptoService.Clear();
                }
            }
        }
예제 #30
0
        /// <summary> 创建类的实例,并随机创建一对密匙和向量 </summary>
        public DESCrypto()
        {
            // 每次创建加密示例,创建一个密码和向量。
            DES des = new DESCryptoServiceProvider();

            des.GenerateKey();
            des.GenerateIV();
            deskey = des.Key;
            desiv  = des.IV;
            des.Clear();
            des = null;
        }