예제 #1
0
        public static string aesDecryptBase64(string SourceStr, ulong Key)
        {
            string decrypt = "";

            try
            {
                var    aes    = new System.Security.Cryptography.AesCryptoServiceProvider();
                var    md5    = new System.Security.Cryptography.MD5CryptoServiceProvider();
                var    sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] key    = sha256.ComputeHash(BitConverter.GetBytes(Key));
                byte[] iv     = md5.ComputeHash(BitConverter.GetBytes(Key));
                aes.Key = key;
                aes.IV  = iv;

                byte[] dataByteArray = Convert.FromBase64String(SourceStr);
                using (var ms = new System.IO.MemoryStream())
                {
                    using (var cs = new System.Security.Cryptography.CryptoStream(ms, aes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(dataByteArray, 0, dataByteArray.Length);
                        cs.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
            }
            catch (Exception e)
            {
            }
            return(decrypt);
        }
 static public byte[] Decode(byte[] Data, System.Security.Cryptography.ICryptoTransform Decoder)
 {
     byte[] Outer = new byte[] { }; int rdlen = 0;
     if (Data.Length > 0)
     {
         using (System.IO.MemoryStream memStream = new System.IO.MemoryStream())
         {
             byte[] bin = new byte[128]; int len;
             System.IO.MemoryStream InputStr = new System.IO.MemoryStream();
             InputStr.Write(Data, 0, Data.Length);
             InputStr.Position = 0;
             System.Security.Cryptography.CryptoStream CryptStream = new System.Security.Cryptography.CryptoStream(memStream, Decoder, System.Security.Cryptography.CryptoStreamMode.Write);
             while (rdlen < Data.Length)
             {
                 len = InputStr.Read(bin, 0, 128);
                 CryptStream.Write(bin, 0, len);
                 rdlen = rdlen + len;
             }
             CryptStream.FlushFinalBlock();
             Outer = memStream.ToArray();
             CryptStream.Close();
         }
     }
     return(Outer);
 }
        /// <summary>
        /// Criptografa um array de bytes em outro array de bytes.
        /// </summary>
        /// <returns>Array de bytes criptografado.</returns>
        /// <param name="p_plaintextbytes">Array de bytes.</param>
        public byte[] EncryptToBytes(byte[] p_plaintextbytes)
        {
            byte[] v_ciphertextbytes;
            byte[] v_plaintextbyteswithsalt;
            System.IO.MemoryStream v_memory;
            System.Security.Cryptography.CryptoStream v_crypto;

            this.Initialize();

            v_plaintextbyteswithsalt = this.AddSalt(p_plaintextbytes);

            v_memory = new System.IO.MemoryStream();

            lock (this)
            {
                v_crypto = new System.Security.Cryptography.CryptoStream(v_memory, this.v_encryptor, System.Security.Cryptography.CryptoStreamMode.Write);
                v_crypto.Write(v_plaintextbyteswithsalt, 0, v_plaintextbyteswithsalt.Length);
                v_crypto.FlushFinalBlock();

                v_ciphertextbytes = v_memory.ToArray();

                v_memory.Close();
                v_crypto.Close();

                return(v_ciphertextbytes);
            }
        }
예제 #4
0
        public static byte[] GetEmbeddedBytes(String file)
        {
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(file))
            {
                if (stream != null)
                {
                    var assemblyData = new Byte[stream.Length];
                    stream.Read(assemblyData, 0, assemblyData.Length);

                    var    key       = System.Text.Encoding.ASCII.GetBytes("t7n6cVWf9Tbns0eI");
                    var    iv        = System.Text.Encoding.ASCII.GetBytes("9qh17ZUf");
                    var    provider  = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                    var    transform = provider.CreateDecryptor(key, iv);
                    byte[] bytes;
                    using (var cstream = new MemoryStream())
                    {
                        using (var cryptoStream = new System.Security.Cryptography.CryptoStream(cstream, transform, System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(assemblyData, 0, assemblyData.Length);
                            cryptoStream.FlushFinalBlock();
                            bytes = cstream.ToArray();

                            using (var compressedStream = new MemoryStream(bytes))
                                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                                    using (var resultStream = new MemoryStream())
                                    {
                                        zipStream.CopyTo(resultStream);
                                        return(resultStream.ToArray());
                                    }
                        }
                    }
                }
            }
            return(null);
        }
예제 #5
0
        public static string EncryptStatic(string encryptString)
        {
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            string result;

            try
            {
                byte[] bytes  = System.Text.Encoding.UTF8.GetBytes(SimpleSecurityHelper.KeyValue.Substring(0, 8));
                byte[] keys   = SimpleSecurityHelper.Keys;
                byte[] bytes2 = System.Text.Encoding.UTF8.GetBytes(encryptString);
                System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
                System.Security.Cryptography.CryptoStream             cryptoStream             = new System.Security.Cryptography.CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(bytes, keys), System.Security.Cryptography.CryptoStreamMode.Write);
                cryptoStream.Write(bytes2, 0, bytes2.Length);
                cryptoStream.FlushFinalBlock();
                System.Text.Encoding uTF = System.Text.Encoding.UTF8;
                result = System.Convert.ToBase64String(uTF.GetBytes(System.Convert.ToBase64String(memoryStream.ToArray())));
            }
            catch
            {
                result = "Encrypt Failed!";
            }
            finally
            {
                memoryStream.Close();
            }
            return(result);
        }
예제 #6
0
        /// <summary>
        /// Saves the dataset encrypted in specified file
        /// </summary>
        /// <param name="dataset">Dataset to save</param>
        /// <param name="username">Username for encryption</param>
        /// <param name="password">Password for encryption</param>
        /// <param name="fileName">File name where to save</param>
        /// <param name="compress">Should the file be compressed</param>
        internal static void EncryptDataSet(System.Data.DataSet dataset, string username, string password, string fileName, bool compress)
        {
            // Check the parameters
            if (dataset == null ||
                string.IsNullOrEmpty(username) ||
                string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(fileName))
            {
                throw new System.ArgumentNullException("All arguments must be supplied.");
            }

            // Save the dataset as encrypted
            using (System.Security.Cryptography.Aes aes = Cryptography.InitAes(username, password)) {
                using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None)) {
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(fileStream, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) {
                        if (compress)
                        {
                            // when compression is requested, use GZip
                            using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cryptoStream, System.IO.Compression.CompressionMode.Compress)) {
                                dataset.WriteXml(zipStream, System.Data.XmlWriteMode.WriteSchema);
                                zipStream.Flush();
                            }
                        }
                        else
                        {
                            dataset.WriteXml(cryptoStream, System.Data.XmlWriteMode.WriteSchema);
                            cryptoStream.FlushFinalBlock();
                        }
                    }
                }
            }
        }
예제 #7
0
        public string EncryptString(string value, string keyString)
        {
            try
            {
                byte[] resultBA = new byte[value.Length], valueBA = new byte[value.Length];
                byte[] iv       = new byte[] { 0x14, 0xD7, 0x5B, 0xA2, 0x47, 0x83, 0x0F, 0xC4 };
                System.Text.ASCIIEncoding ascEncoding = new System.Text.ASCIIEncoding();
                byte[] key = new byte[24];
                ascEncoding.GetBytes(keyString, 0, keyString.Length < 24?keyString.Length:24, key, 0);

                MemoryStream memStream = new MemoryStream();
                byte[]       tempBA    = new byte[value.Length];
                ascEncoding.GetBytes(value, 0, value.Length, tempBA, 0);
                System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream(memStream, System.Security.Cryptography.TripleDESCryptoServiceProvider.Create().CreateEncryptor(key, iv), System.Security.Cryptography.CryptoStreamMode.Write);
                cStream.Write(tempBA, 0, tempBA.Length);
                cStream.FlushFinalBlock();
                resultBA = memStream.ToArray();
                cStream.Close();


                return(InternalMethods.BytesToHexString(resultBA));
            }
            catch (Exception exc)
            {
                LogEvent(exc.Source, "EncryptString()", exc.ToString(), 4);
                return("");
            }
        }
예제 #8
0
        /// <summary>
        /// Encrypts a source stream and returns a Base64 result.
        /// </summary>
        /// <param name="Source">The source steam.</param>
        /// <param name="Key">A key to use for the encryption.</param>
        /// <returns>A Base64 string of the encrypted information.</returns>
        public string Encrypt(System.IO.Stream Source, string Key)
        {
            // read the stream into a byte array
            Source.Position = 0;
            byte[] bytIn = new byte[Source.Length];
            Source.Read(bytIn, 0, (int)Source.Length);

            // create a MemoryStream so that the process can be done without I/O files
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            byte[] bytKey = GetLegalKey(Key);

            // set the private key
            _cryptoservice.Key = bytKey;
            _cryptoservice.IV  = bytKey;

            // create an Encryptor from the Provider Service instance
            System.Security.Cryptography.ICryptoTransform encrypto = _cryptoservice.CreateEncryptor();

            // create Crypto Stream that transforms a stream using the encryption
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encrypto, System.Security.Cryptography.CryptoStreamMode.Write);

            // write out encrypted content into MemoryStream
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();

            byte[] bytOut = ms.GetBuffer();

            // convert into Base64 so that the result can be used in xml
            return(System.Convert.ToBase64String(bytOut, 0, (int)ms.Length));
        }
예제 #9
0
        public static string Encrypt(string plainText, string passPhrase)
        {
            byte[]    initVectorBytes = Encoding.ASCII.GetBytes("tu89geji340t89u2");
            const int keysize         = 256;

            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (System.Security.Cryptography.PasswordDeriveBytes password = new System.Security.Cryptography.PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged())
                {
                    symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
                    using (System.Security.Cryptography.ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                byte[] cipherTextBytes = memoryStream.ToArray();
                                return(Convert.ToBase64String(cipherTextBytes));
                            }
                        }
                    }
                }
            }
        }
예제 #10
0
        /// <summary>
        /// 字符串加密
        /// </summary>
        /// <param name="strText">字符串</param>
        /// <param name="strEncrKey">密钥8位数字或字母</param>
        /// <returns></returns>
        public string DesEncryptString(string strText, string strEncrKey)
        {
            byte[] rgbKey = null;
            string SIv    = "inputvec";

            try
            {
                rgbKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, strEncrKey.Length));
                System.Security.Cryptography.DESCryptoServiceProvider provider = new System.Security.Cryptography.DESCryptoServiceProvider();
                provider.Key  = rgbKey;
                provider.IV   = System.Text.Encoding.UTF8.GetBytes(SIv);
                provider.Mode = System.Security.Cryptography.CipherMode.ECB;

                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strText);
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream stream2 = new System.Security.Cryptography.CryptoStream(stream, provider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();
                return(Convert.ToBase64String(stream.ToArray()));
            }
            catch (Exception exception)
            {
                //return ("error:" + exception.Message + "\r");
                throw exception;
            }
        }
예제 #11
0
        public static string encryptRJ256(string target, string key, string iv)
        {
            var rijndael = new System.Security.Cryptography.RijndaelManaged()
            {
                Padding = System.Security.Cryptography.PaddingMode.Zeros,
                Mode = System.Security.Cryptography.CipherMode.CBC,
                KeySize = 256,
                BlockSize = 256
            };

            var bytesKey = Encoding.ASCII.GetBytes(key);
            var bytesIv = Encoding.ASCII.GetBytes(iv);

            var encryptor = rijndael.CreateEncryptor(bytesKey, bytesIv);

            var msEncrypt = new System.IO.MemoryStream();
            var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write);

            var toEncrypt = Encoding.ASCII.GetBytes(target);

            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            var encrypted = msEncrypt.ToArray();
            return Convert.ToBase64String(encrypted);
        }
예제 #12
0
        public void Encrypt(Stream inStream, Stream outStream)
        {
            ThrowIfObjectDisposed();

            AssertUtil.ArgumentNotNull(inStream, nameof(inStream));
            AssertUtil.ArgumentNotNull(outStream, nameof(outStream));

            if (!inStream.CanRead)
            {
                throw new ArgumentException($"Argument '{nameof(inStream)}' cannot be read.");
            }

            if (!outStream.CanWrite)
            {
                throw new ArgumentException($"Argument '{nameof(outStream)}' not supports writing.");
            }


            using (var encryptor = this.provider.CreateEncryptor())
                using (var writer = new System.Security.Cryptography.CryptoStream(outStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write, true))
                {
                    StreamUtil.StreamCopy(inStream, writer);
                    writer.FlushFinalBlock();
                }
        }
예제 #13
0
                //static Logger logger = SimpleLogger.setLogger("Common");
                #region 暗号化関係
                /// <summary>
                /// 文字列を暗号化する
                /// </summary>
                /// <param name="str">暗号化する文字列</param>
                /// <param name="key">パスワード</param>
                /// <returns>暗号化された文字列</returns>
                public static string EncryptString(string str, string key)
                {
                    //文字列をバイト型配列にする
                    byte[] bytesIn = System.Text.Encoding.UTF8.GetBytes(str);

                    //DESCryptoServiceProviderオブジェクトの作成
                    System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();

                    //共有キーと初期化ベクタを決定
                    //パスワードをバイト配列にする
                    byte[] bytesKey = System.Text.Encoding.UTF8.GetBytes(key);
                    //共有キーと初期化ベクタを設定
                    des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
                    des.IV  = ResizeBytesArray(bytesKey, des.IV.Length);

                    //暗号化されたデータを書き出すためのMemoryStream
                    MemoryStream msOut = new System.IO.MemoryStream();

                    //DES暗号化オブジェクトの作成
                    System.Security.Cryptography.ICryptoTransform desdecrypt = des.CreateEncryptor();
                    //書き込むためのCryptoStreamの作成
                    System.Security.Cryptography.CryptoStream cryptStreem = new System.Security.Cryptography.CryptoStream(msOut, desdecrypt, System.Security.Cryptography.CryptoStreamMode.Write);
                    //書き込む
                    cryptStreem.Write(bytesIn, 0, bytesIn.Length);
                    cryptStreem.FlushFinalBlock();
                    //暗号化されたデータを取得
                    byte[] bytesOut = msOut.ToArray();

                    //閉じる
                    cryptStreem.Close();
                    msOut.Close();

                    //Base64で文字列に変更して結果を返す
                    return(System.Convert.ToBase64String(bytesOut).Replace("=", ""));
                }
예제 #14
0
파일: Function.cs 프로젝트: jujianfei/AC
        /// <summary>
        /// 字符串解密
        /// </summary>
        /// <param name="encryptPassword">加密过的字符串</param>
        /// <returns>解密后的字符串</returns>
        public static string PasswordDecrypt(string encryptPassword)
        {
            try
            {
                string strPasswordKey     = encryptPassword.Substring(encryptPassword.Length - 8, 8);
                string strEncryptPassword = encryptPassword.Substring(0, encryptPassword.Length - 8);

                System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
                int    intEncryptPasswordLength = strEncryptPassword.Length / 2;
                byte[] bytInput = new byte[intEncryptPasswordLength];

                for (int intIndex = 0; intIndex < intEncryptPasswordLength; intIndex++)
                {
                    bytInput[intIndex] = Convert.ToByte(strEncryptPassword.Substring(intIndex * 2, 2), 16);
                }

                des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(strPasswordKey);
                des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(strPasswordKey);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream((System.IO.Stream)ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cs.Write(bytInput, 0, bytInput.Length);
                cs.FlushFinalBlock();

                return(System.Text.Encoding.Default.GetString(ms.ToArray()));
            }
            catch
            {
                return("");
            }
        }
예제 #15
0
파일: Function.cs 프로젝트: jujianfei/AC
        /// <summary>
        /// 字符串加密
        /// </summary>
        /// <param name="password">欲加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string PasswordEncrypt(string password)
        {
            string strCharKey     = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string strPasswordKey = "";

            for (int intIndexKey = 1; intIndexKey <= 8; intIndexKey++)
            {
                strPasswordKey += strCharKey.Substring(GetRnd(0, strCharKey.Length - 1), 1);
            }

            System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] bytInput = System.Text.Encoding.Default.GetBytes(password);
            des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(strPasswordKey);
            des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(strPasswordKey);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream((System.IO.Stream)ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(bytInput, 0, bytInput.Length);
            cs.FlushFinalBlock();

            System.Text.StringBuilder sbRet = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                sbRet.AppendFormat("{0:X2}", b);
            }

            return(sbRet.ToString() + strPasswordKey);
        }
예제 #16
0
        public static string DecryptStatic(string decryptString, string decryptKey)
        {
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            string result;

            try
            {
                System.Text.Encoding uTF = System.Text.Encoding.UTF8;
                decryptString = uTF.GetString(System.Convert.FromBase64String(decryptString));
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(decryptKey);
                byte[] keys  = SimpleSecurityHelper.Keys;
                byte[] array = System.Convert.FromBase64String(decryptString);
                System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
                System.Security.Cryptography.CryptoStream             cryptoStream             = new System.Security.Cryptography.CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(bytes, keys), System.Security.Cryptography.CryptoStreamMode.Write);
                cryptoStream.Write(array, 0, array.Length);
                cryptoStream.FlushFinalBlock();
                result = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch
            {
                result = "Decrypt Failed!";
            }
            finally
            {
                memoryStream.Close();
            }
            return(result);
        }
예제 #17
0
파일: Des.cs 프로젝트: ZhuYi0128/socketTest
        public static string DesDecrypt(string inputString, string decryptKey)
        {
            #region
            byte[] byKey          = null;
            byte[] IV             = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = new Byte[inputString.Length];
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(inputString);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(byKey, IV), System.Security.Cryptography.CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = new System.Text.UTF8Encoding();
                inputString = encoding.GetString(ms.ToArray());
            }
            catch
            {
                throw;
            }
            return(inputString);

            #endregion
        }
예제 #18
0
 ///
 /// DES解密
 ///
 /// 要解密字符串
 /// 返回解密后字符串
 public static String Decrypt_DES(String str)
 {
     if (str.Trim() == "")
     {
         return("");
     }
     try
     {
         System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
         Int32  x;
         Byte[] inputByteArray = new Byte[str.Length / 2];
         for (x = 0; x < str.Length / 2; x++)
         {
             inputByteArray[x] = (Byte)(Convert.ToInt32(str.Substring(x * 2, 2), 16));
         }
         des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey);
         des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey);
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         System.Text.StringBuilder ret = new System.Text.StringBuilder();
         return(System.Text.Encoding.Default.GetString(ms.ToArray()));
     }
     catch (System.Exception ex)
     {
         return("");
     }
 }
예제 #19
0
        public static string Encrypt(string[] keyArray)
        {
            string key = "";

            foreach (string s in keyArray)
            {
                key = key + s + ";";
            }
            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes     = Encoding.ASCII.GetBytes(Salt);
            byte[] PlainTextBytes     = Encoding.UTF8.GetBytes(key);
            System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
            System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged();
            SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
            byte[] CipherTextBytes = null;
            using (System.Security.Cryptography.ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
            {
                using (System.IO.MemoryStream MemStream = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                        CryptoStream.FlushFinalBlock();
                        CipherTextBytes = MemStream.ToArray();
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return(Convert.ToBase64String(CipherTextBytes));
        }
예제 #20
0
        private static readonly String strDesKey = "gaoguanj";//加密所需8位密匙
        ///
        /// DES加密
        ///

        /// 要加密字符串
        /// 返回加密后字符串
        public static String Encrypt_DES(String str)
        {
            if (str.Trim() == "")
            {
                return("");
            }
            try
            {
                System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
                Byte[] inputByteArray = System.Text.Encoding.Default.GetBytes(str);
                des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey);
                des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (Byte b in ms.ToArray())
                {
                    sb.AppendFormat("{0:X2}", b);
                }
                return(sb.ToString());
            }
            catch (System.Exception ex)
            {
                return("");
            }
        }
예제 #21
0
        public static string DecryptPAN(string encryptedPAN)
        {
            //  Log log = new Log(LogPath);
            System.Security.Cryptography.SymmetricAlgorithm alg = System.Security.Cryptography.TripleDES.Create();
            alg.KeySize = 128;
            alg.Key     = Hex2Bin(PEncKey);
            alg.IV      = Hex2Bin(PEncIV);
            alg.Padding = System.Security.Cryptography.PaddingMode.None;
            alg.Mode    = System.Security.Cryptography.CipherMode.CBC;

            byte[] buf = new byte[16];
            Hex2Bin(encryptedPAN, buf);
            try
            {
                MemoryStream outs = new MemoryStream();
                System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(outs, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                encStream.Write(buf, 0, 16);
                encStream.FlushFinalBlock();
                Buffer.BlockCopy(outs.GetBuffer(), 0, buf, 0, 16);
                encStream.Close();
                return(Bin2Hex(buf).Trim('A'));
            }
            catch { }
            return(null);
        }
예제 #22
0
        public static string encryptRJ256(string target, string key, string iv)
        {
            var rijndael = new System.Security.Cryptography.RijndaelManaged()
            {
                Padding   = System.Security.Cryptography.PaddingMode.Zeros,
                Mode      = System.Security.Cryptography.CipherMode.CBC,
                KeySize   = 256,
                BlockSize = 256
            };

            var bytesKey = Encoding.ASCII.GetBytes(key);
            var bytesIv  = Encoding.ASCII.GetBytes(iv);

            var encryptor = rijndael.CreateEncryptor(bytesKey, bytesIv);

            var msEncrypt = new System.IO.MemoryStream();
            var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write);

            var toEncrypt = Encoding.ASCII.GetBytes(target);

            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            var encrypted = msEncrypt.ToArray();

            return(Convert.ToBase64String(encrypted));
        }
 public static byte[] DES_Enc(string str, string key, string vit)
 {
     //判断向量是否为空,进行默认赋值;
     if (string.IsNullOrEmpty(key)) { key = "KCCT"; }
     //判断向量是否为空,进行默认赋值;
     if (string.IsNullOrEmpty(vit)) { vit = "MNSN"; }
     try
     {
         //实例化加解密类的对象;
         using (var descsp = new System.Security.Cryptography.DESCryptoServiceProvider())
         {
             //定义字节数组,用来存储要加密的字符串;
             var data = System.Text.Encoding.UTF8.GetBytes(str);
             //实例化内存流对象;
             using (var mStream = new System.IO.MemoryStream())
             {
                 //使用内存流实例化加密流对象;
                 using (var cStream = new System.Security.Cryptography.CryptoStream(mStream, descsp.CreateEncryptor(System.Text.Encoding.Unicode.GetBytes(key), System.Text.Encoding.Unicode.GetBytes(vit)), System.Security.Cryptography.CryptoStreamMode.Write))
                 {
                     //向加密流中写入数据;
                     cStream.Write(data, 0, data.Length);
                     //释放加密流;
                     cStream.FlushFinalBlock();
                     //返回加密后的字符串;
                     return mStream.ToArray();
                 }
             }
         }
     }
     catch { return null; }
 }
예제 #24
0
        private byte[] Encrypt(byte[] PlainData)
        {
            byte[] Result = null;


            try
            {
                System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
                Enc.KeySize = 256;
                Enc.Key     = this.Encryption_Key();
                Enc.IV      = this.Encryption_IV();

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cryptoStream = null;
                cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cryptoStream.Write(PlainData, 0, PlainData.Length);
                cryptoStream.FlushFinalBlock();
                Result = memoryStream.ToArray();
                cryptoStream.Close();
                memoryStream.Close();
                cryptoStream.Dispose();
                memoryStream.Dispose();
            }
            catch (Exception)
            {
                Result = null;
            }

            return(Result);
        }
예제 #25
0
        public string Descifrar(string Cadena)
        {
            try
            {
                if (string.IsNullOrEmpty(Cadena))
                {
                    return(Cadena);
                }

                byte[] PlainText;
                PlainText = Convert.FromBase64String(Cadena);

                MemoryStream memdata = new MemoryStream();

                System.Security.Cryptography.DESCryptoServiceProvider DES          = new System.Security.Cryptography.DESCryptoServiceProvider();
                System.Security.Cryptography.CryptoStream             cryptostream = new System.Security.Cryptography.CryptoStream(memdata,
                                                                                                                                   DES.CreateDecryptor(Encoding.ASCII.GetBytes(Default8Key), Encoding.ASCII.GetBytes(Default8VI)),
                                                                                                                                   System.Security.Cryptography.CryptoStreamMode.Write);

                cryptostream.Write(PlainText, 0, PlainText.Length);
                cryptostream.FlushFinalBlock();
                cryptostream.Close();

                return(Encoding.ASCII.GetString(memdata.ToArray()));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
예제 #26
0
        private static string Encrypt(string hashKey, string strQueryStringParameter)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider hash_func = new System.Security.Cryptography.MD5CryptoServiceProvider();

            byte[] key = hash_func.ComputeHash(Encoding.ASCII.GetBytes(hashKey));
            byte[] IV  = new byte[hashKey.Length];

            System.Security.Cryptography.SHA1CryptoServiceProvider sha_func = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            byte[] temp = sha_func.ComputeHash(Encoding.ASCII.GetBytes(hashKey));

            for (int i = 0; i < hashKey.Length; i++)
            {
                IV[i] = temp[hashKey.Length];
            }

            byte[] toenc = System.Text.Encoding.UTF8.GetBytes(strQueryStringParameter);

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.KeySize = 128;
            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(
                ms,
                des.CreateEncryptor(key, IV),
                System.Security.Cryptography.CryptoStreamMode.Write
                );
            cs.Write(toenc, 0, toenc.Length);
            cs.FlushFinalBlock();

            return(Convert.ToBase64String(ms.ToArray()));
        }
예제 #27
0
        // ========================================
        // static field
        // ========================================
        public static string EncryptString(string str, string password)
        {
            var aes = new System.Security.Cryptography.AesCryptoServiceProvider();

            var data = System.Text.Encoding.UTF8.GetBytes(str);

            var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);

            aes.Key = ResizeBytesArray(passwordBytes, aes.Key.Length);
            aes.IV  = ResizeBytesArray(passwordBytes, aes.IV.Length);

            var stream      = new System.IO.MemoryStream();
            var encryptor   = aes.CreateEncryptor();
            var cryptStream = new System.Security.Cryptography.CryptoStream(
                stream,
                encryptor,
                System.Security.Cryptography.CryptoStreamMode.Write
                );

            try {
                cryptStream.Write(data, 0, data.Length);
                cryptStream.FlushFinalBlock();
                var encrypted = stream.ToArray();
                return(System.Convert.ToBase64String(encrypted));
            } finally {
                cryptStream.Close();
                stream.Close();
            }
        }
예제 #28
0
                //static Logger logger = SimpleLogger.setLogger("Common");

                #region �Í����֌W

                /// <summary>
                /// ��������������
                /// </summary>
                /// <param name="str">�Í������镶����</param>
                /// <param name="key">�p�X���[�h</param>
                /// <returns>�Í������ꂽ������</returns>
                public static string EncryptString(string str, string key)
                {
                    //�������o�C�g�^�z��ɂ���
                    byte[] bytesIn = System.Text.Encoding.UTF8.GetBytes(str);

                    //DESCryptoServiceProvider�I�u�W�F�N�g�̍쐬
                    System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();

                    //���L�L�[�Ə������x�N�^�����
                    //�p�X���[�h��o�C�g�z��ɂ���
                    byte[] bytesKey = System.Text.Encoding.UTF8.GetBytes(key);
                    //���L�L�[�Ə������x�N�^��ݒ�
                    des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
                    des.IV = ResizeBytesArray(bytesKey, des.IV.Length);

                    //�Í������ꂽ�f�[�^������o�����߂�MemoryStream
                    MemoryStream msOut = new System.IO.MemoryStream();
                    //DES�Í����I�u�W�F�N�g�̍쐬
                    System.Security.Cryptography.ICryptoTransform desdecrypt = des.CreateEncryptor();
                    //�������ނ��߂�CryptoStream�̍쐬
                    System.Security.Cryptography.CryptoStream cryptStreem = new System.Security.Cryptography.CryptoStream(msOut, desdecrypt, System.Security.Cryptography.CryptoStreamMode.Write);
                    //��������
                    cryptStreem.Write(bytesIn, 0, bytesIn.Length);
                    cryptStreem.FlushFinalBlock();
                    //�Í������ꂽ�f�[�^��擾
                    byte[] bytesOut = msOut.ToArray();

                    //�‚���
                    cryptStreem.Close();
                    msOut.Close();

                    //Base64�ŕ�����ɕύX���Č��ʂ�Ԃ�
                    return System.Convert.ToBase64String(bytesOut).Replace("=", "");
                }
예제 #29
0
        /// <summary>Szyfruje przekazany strumień danych.</summary>
        /// <param name="streamToEncrypt">Strumień danych do zaszyfrowania.</param>
        /// <param name="streamEncrypted">Zaszyfrowany strumień danych. Uwaga strumień zostanie zamknięty,
        /// ale w razie konieczności można będzie użyć metody 'ToArray()'.</param>
        /// <param name="key">Klucz szyfrujący. Maksymalnie 256 bitów, minimalnie 128 bitów, przeskok o 64 bity.</param>
        /// <param name="iv">Wektor inicjalizacji. Rozmiar 128 bitów.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="System.ArgumentException"></exception>
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException"></exception>
        public static void Encrypt(System.IO.Stream streamToEncrypt, System.IO.Stream streamEncrypted, byte[] key, byte[] iv)
        {
            if (streamToEncrypt == null)
            {
                throw new System.ArgumentNullException("streamToEncrypt");
            }
            if (streamToEncrypt.CanRead == false)
            {
                throw new System.ArgumentException("Argument 'streamToEncrypt' is not readable.");
            }

            if (streamEncrypted == null)
            {
                throw new System.ArgumentNullException("streamEncrypted");
            }
            if (streamEncrypted.CanWrite == false)
            {
                throw new System.ArgumentException("Argument 'streamEncrypted' is not writable.");
            }

            if (key == null)
            {
                throw new System.ArgumentNullException("key");
            }
            if (key.Length != 16 && key.Length != 22 && key.Length != 32)
            {
                throw new System.ArgumentException("Argument 'key' does not mach the block size for this algorithm.");
            }

            if (iv == null)
            {
                throw new System.ArgumentNullException("iv");
            }
            if (iv.Length != 16)
            {
                throw new System.ArgumentException("Argument 'iv' does not mach the block size for this algorithm.");
            }

            streamToEncrypt.Position = 0;
            streamEncrypted.Position = 0;

            using (System.Security.Cryptography.RijndaelManaged algoritmCrypt = new System.Security.Cryptography.RijndaelManaged())
            {
                using (System.Security.Cryptography.ICryptoTransform encryptor = algoritmCrypt.CreateEncryptor(key, iv))
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(
                               streamEncrypted, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        streamToEncrypt.CopyTo(cs);
                        cs.FlushFinalBlock();
                    }
                }
            }
        }
예제 #30
0
 /// <summary>
 /// Base64加密
 /// </summary>
 /// <param name="cryptString">原文</param>
 /// <returns>密文</returns>
 public static string EncryptToBase64(this string cryptString)
 {
     byte[] cryptKey = System.Convert.FromBase64String(CryptKey);
     byte[] cryptIV  = System.Convert.FromBase64String(CryptIV);
     byte[] bytes    = System.Text.Encoding.UTF8.GetBytes(cryptString);
     System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged();
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndaelManaged.CreateEncryptor(cryptKey, cryptIV), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(bytes, 0, bytes.Length);
     cryptoStream.FlushFinalBlock();
     return(System.Convert.ToBase64String(memoryStream.ToArray()));
 }
예제 #31
0
 private byte[] Crypt(byte[] inBytes, System.Security.Cryptography.ICryptoTransform xfrm)
 {
     System.IO.MemoryStream outStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream crypto = new System.Security.Cryptography.CryptoStream(outStream, xfrm, System.Security.Cryptography.CryptoStreamMode.Write);
     crypto.Write(inBytes, 0, inBytes.Length);
     crypto.FlushFinalBlock();
     for (int i = 0; i < inBytes.Length; ++i)
     {
         inBytes[i] = 0;
     }
     return(outStream.ToArray());
 }
예제 #32
0
 public string Decrypt()
 {
     System.Security.Cryptography.ICryptoTransform transform = this._mCSP.CreateDecryptor(this._mCSP.Key, this._mCSP.IV);
     byte[] array = System.Convert.FromBase64String(this._mstrEncryptedString);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, transform, System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(array, 0, array.Length);
     cryptoStream.FlushFinalBlock();
     cryptoStream.Close();
     this._mstrOriginalString = System.Text.Encoding.Unicode.GetString(memoryStream.ToArray());
     return(this._mstrOriginalString);
 }
예제 #33
0
        public static byte[] E1(byte[] data)
        {
            var stream = new MemoryStream();
            var des    = new System.Security.Cryptography.DESCryptoServiceProvider();

            des.Mode    = System.Security.Cryptography.CipherMode.CBC;
            des.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            var cs = new System.Security.Cryptography.CryptoStream(stream, des.CreateEncryptor(ES.Key, ES.IV), System.Security.Cryptography.CryptoStreamMode.Write);

            cs.Write(data, 0, (int)data.Length);
            cs.FlushFinalBlock();
            return(stream.ToArray());
        }
예제 #34
0
파일: DESEncrypt.cs 프로젝트: linyc/CTool
        /// <summary>   
        /// 解密数据   
        /// </summary>   
        /// <param name="Text"></param>   
        /// <param name="sKey"></param>   
        /// <returns></returns>   
        private static string Decrypt(string Text, string sKey)
        {
            try
            {
                System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.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();

                System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

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

                cs.FlushFinalBlock();

                return Encoding.Default.GetString(ms.ToArray());

            }
            catch
            {
                return Text;
            }
        }
예제 #35
0
        public static string Encrypt(string strPlainText)
        {
            //Dim roundtrip As String
            //Dim encASCII As New System.Text.ASCIIEncoding()
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged();
            //Dim fromEncrypt() As Byte
            byte[] baCipherTextBuffer = null;
            byte[] baPlainTextBuffer = null;
            byte[] baEncryptionKey = null;
            byte[] baInitializationVector = null;

            //Create a new key and initialization vector.
            //objRijndael.GenerateKey()
            //objRijndael.GenerateIV()
            objRijndael.Key = HexStringToByteArray(strKey);
            objRijndael.IV = HexStringToByteArray(strIV);

            //Get the key and initialization vector.
            baEncryptionKey = objRijndael.Key;
            baInitializationVector = objRijndael.IV;
            //strKey = ByteArrayToHexString(baEncryptionKey)
            //strIV = ByteArrayToHexString(baInitializationVector)

            //Get an encryptor.
            System.Security.Cryptography.ICryptoTransform ifaceAESencryptor = objRijndael.CreateEncryptor(baEncryptionKey, baInitializationVector);

            //Encrypt the data.
            System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, ifaceAESencryptor, System.Security.Cryptography.CryptoStreamMode.Write);

            //Convert the data to a byte array.
            baPlainTextBuffer = enc.GetBytes(strPlainText);

            //Write all data to the crypto stream and flush it.
            csEncrypt.Write(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
            csEncrypt.FlushFinalBlock();

            //Get encrypted array of bytes.
            baCipherTextBuffer = msEncrypt.ToArray();

            return ByteArrayToHexString(baCipherTextBuffer);
        }
예제 #36
0
파일: DESEncrypt.cs 프로젝트: linyc/CTool
        /// <summary>   
        /// 加密数据   
        /// </summary>   
        /// <param name="Text"></param>   
        /// <param name="sKey"></param>   
        /// <returns></returns>   
        private static string Encrypt(string Text, string sKey)
        {
            System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();

            byte[] inputByteArray;

            inputByteArray = Encoding.Default.GetBytes(Text);

            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();

            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.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);

            }
            return ret.ToString();
        }
예제 #37
0
 public static string Encrypt_Des(this object value, string desKey, string desIV)
 {
     string originalString = value as string;
         byte[] Key = GetBytes(desKey);
         byte[] IV = GetBytes(desIV);
         if (String.IsNullOrEmpty(originalString))
             throw new ArgumentNullException("plainText");
         if (Key == null || Key.Length <= 0)
             throw new ArgumentNullException("Key");
         if (IV == null || IV.Length <= 0)
             throw new ArgumentNullException("IV");
         System.Security.Cryptography.DESCryptoServiceProvider cryptoProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
         MemoryStream memoryStream = new MemoryStream();
         System.Security.Cryptography.CryptoStream cryptoStream
             = new System.Security.Cryptography.CryptoStream(memoryStream,
                                                             cryptoProvider.CreateEncryptor(Key, IV),
                                                             System.Security.Cryptography.CryptoStreamMode.Write);
         StreamWriter writer = new StreamWriter(cryptoStream);
         writer.Write(originalString);
         writer.Flush();
         cryptoStream.FlushFinalBlock();
         writer.Flush();
         return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
 }
예제 #38
0
        /// <summary>
        /// 根据密钥进行字符串加密.
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>机密后的字符串</returns>
        public static string EncryptString(string str, string key)
        {
            try
            {
                //根据UTF8编码规则取得二进制流..
                byte[] bytesIn = System.Text.Encoding.UTF8.GetBytes(str);

                //访问数据加密标准 (DES) 算法的加密服务提供程序.
                System.Security.Cryptography.DESCryptoServiceProvider des =
                    new System.Security.Cryptography.DESCryptoServiceProvider();

                //对密钥进行编码.
                byte[] bytesKey = System.Text.Encoding.UTF8.GetBytes(key);

                //初始化机密适配器..
                des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
                des.IV = ResizeBytesArray(bytesKey, des.IV.Length);

                System.IO.MemoryStream msOut = new System.IO.MemoryStream();

                //基本的加密转换运算.
                System.Security.Cryptography.ICryptoTransform desdecrypt =
                    des.CreateEncryptor();

                //定义将数据流链接到加密转换的流.
                System.Security.Cryptography.CryptoStream cryptStreem =
                    new System.Security.Cryptography.CryptoStream(msOut,
                    desdecrypt,
                    System.Security.Cryptography.CryptoStreamMode.Write);

                //二进制流输出.
                cryptStreem.Write(bytesIn, 0, bytesIn.Length);
                cryptStreem.FlushFinalBlock();

                //取得加密后的二进制流取得.
                byte[] bytesOut = msOut.ToArray();

                //关闭流.
                cryptStreem.Close();
                msOut.Close();

                //生成由以 64 为基的二进制数组.
                return System.Convert.ToBase64String(bytesOut);
            }
            catch (Exception e)
            {
                throw (e);
                //				return "";
            }
        }
예제 #39
0
        /// <summary>
        /// 文字列を暗号化する
        /// </summary>
        /// <param name="str">暗号化する文字列</param>
        /// <param name="key">パスワード</param>
        /// <returns>暗号化された文字列</returns>
        public static string EncryptString(string str, string key)
        {
            // 文字列をバイト型配列にする
            var bytesIn = System.Text.Encoding.UTF8.GetBytes(str);

            // DESCryptoServiceProviderオブジェクトの作成
            var des = new System.Security.Cryptography.DESCryptoServiceProvider();

            // 共有キーと初期化ベクタを決定

            // パスワードをバイト配列にする
            var bytesKey = System.Text.Encoding.UTF8.GetBytes(key);

            // 共有キーと初期化ベクタを設定
            des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
            des.IV = ResizeBytesArray(bytesKey, des.IV.Length);

            // 暗号化されたデータを書き出すためのMemoryStream
            var msOut = new System.IO.MemoryStream();

            // DES暗号化オブジェクトの作成
            var desdecrypt = des.CreateEncryptor();

            // 書き込むためのCryptoStreamの作成
            var cryptStreem = new System.Security.Cryptography.CryptoStream(msOut, desdecrypt, System.Security.Cryptography.CryptoStreamMode.Write);

            // 書き込む
            cryptStreem.Write(bytesIn, 0, bytesIn.Length);
            cryptStreem.FlushFinalBlock();

            // 暗号化されたデータを取得
            byte[] bytesOut = msOut.ToArray();

            // 閉じる
            cryptStreem.Close();
            msOut.Close();

            // Base64で文字列に変更して結果を返す
            return System.Convert.ToBase64String(bytesOut);
        }
예제 #40
0
        protected static void ProduceResponse(HttpContext context, ITypeAccepter accepter, string title, Render.RenderContext ctx, Size tileSize,
            int rot = 0, float translateX = 0, float translateY = 0,
            bool transparent = false, IDictionary<string, Object> queryDefaults = null)
        {
            // New-style Options
            // TODO: move to ParseOptions (maybe - requires options to be parsed after stylesheet creation?)
            if (HandlerBase.GetBoolOption(context.Request, "sscoords", queryDefaults: queryDefaults, defaultValue: false))
                ctx.styles.hexCoordinateStyle = Stylesheet.HexCoordinateStyle.Subsector;

            if (HandlerBase.GetBoolOption(context.Request, "allhexes", queryDefaults: queryDefaults, defaultValue: false))
                ctx.styles.numberAllHexes = true;

            if (!HandlerBase.GetBoolOption(context.Request, "routes", queryDefaults: queryDefaults, defaultValue: true))
            {
                ctx.styles.macroRoutes.visible = false;
                ctx.styles.microRoutes.visible = false;
            }

            ctx.styles.dimUnofficialSectors = HandlerBase.GetBoolOption(context.Request, "dimunofficial", queryDefaults: queryDefaults, defaultValue: false);

            double devicePixelRatio = HandlerBase.GetDoubleOption(context.Request, "dpr", defaultValue: 1, queryDefaults: queryDefaults);
            if (devicePixelRatio <= 0)
                devicePixelRatio = 1;

            if (accepter.Accepts(context, MediaTypeNames.Application.Pdf))
            {
                using (var document = new PdfDocument())
                {
                    document.Version = 14; // 1.4 for opacity
                    document.Info.Title = title;
                    document.Info.Author = "Joshua Bell";
                    document.Info.Creator = "TravellerMap.com";
                    document.Info.Subject = DateTime.Now.ToString("F", CultureInfo.InvariantCulture);
                    document.Info.Keywords = "The Traveller game in all forms is owned by Far Future Enterprises. Copyright (C) 1977 - 2015 Far Future Enterprises. Traveller is a registered trademark of Far Future Enterprises.";

                    // TODO: Credits/Copyright
                    // This is close, but doesn't define the namespace correctly:
                    // document.Info.Elements.Add( new KeyValuePair<string, PdfItem>( "/photoshop/Copyright", new PdfString( "HelloWorld" ) ) );

                    PdfPage page = document.AddPage();

                    // NOTE: only PageUnit currently supported in XGraphics is Points
                    page.Width = XUnit.FromPoint(tileSize.Width);
                    page.Height = XUnit.FromPoint(tileSize.Height);

                    PdfSharp.Drawing.XGraphics gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page);

                    RenderToGraphics(ctx, rot, translateX, translateY, gfx);

                    using (var stream = new MemoryStream())
                    {
                        document.Save(stream, closeStream: false);

                        context.Response.ContentType = MediaTypeNames.Application.Pdf;
                        context.Response.AddHeader("content-length", stream.Length.ToString());
                        context.Response.AddHeader("content-disposition", "inline;filename=\"map.pdf\"");
                        context.Response.BinaryWrite(stream.ToArray());
                        context.Response.Flush();
                        context.Response.Close();
                    }

                    return;
                }
            }

            using (var bitmap = new Bitmap((int)Math.Floor(tileSize.Width * devicePixelRatio), (int)Math.Floor(tileSize.Height * devicePixelRatio), PixelFormat.Format32bppArgb))
            {
                if (transparent)
                    bitmap.MakeTransparent();

                using (var g = Graphics.FromImage(bitmap))
                {
                    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

                    using (var graphics = XGraphics.FromGraphics(g, new XSize(tileSize.Width * devicePixelRatio, tileSize.Height * devicePixelRatio)))
                    {
                        graphics.ScaleTransform(devicePixelRatio);

                        RenderToGraphics(ctx, rot, translateX, translateY, graphics);
                    }
                }

                bool dataURI = HandlerBase.GetBoolOption(context.Request, "datauri", queryDefaults: queryDefaults, defaultValue: false );
                MemoryStream ms = null;
                if (dataURI)
                    ms = new MemoryStream();

                BitmapResponse(context.Response, dataURI ? ms : context.Response.OutputStream, ctx.styles, bitmap, transparent ? Util.MediaTypeName_Image_Png : null);

                if (dataURI)
                {
                    string contentType = context.Response.ContentType;
                    context.Response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain;
                    ms.Seek(0, SeekOrigin.Begin);

                    context.Response.Output.Write("data:");
                    context.Response.Output.Write(contentType);
                    context.Response.Output.Write(";base64,");
                    context.Response.Output.Flush();

                    byte[] buffer = new byte[4096];
                    System.Security.Cryptography.ICryptoTransform transform = new System.Security.Cryptography.ToBase64Transform();
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(context.Response.OutputStream, transform, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        int bytesRead;
                        while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) > 0)
                            cs.Write(buffer, 0, bytesRead);
                        cs.FlushFinalBlock();
                    }
                    context.Response.OutputStream.Flush();
                }
            }
        }
예제 #41
0
        /// <summary>
        /// Criptografa um array de bytes em outro array de bytes.
        /// </summary>
        /// <returns>Array de bytes criptografado.</returns>
        /// <param name="p_plaintextbytes">Array de bytes.</param>
        public byte[] EncryptToBytes(byte[] p_plaintextbytes)
        {
            byte[] v_ciphertextbytes;
            byte[] v_plaintextbyteswithsalt;
            System.IO.MemoryStream v_memory;
            System.Security.Cryptography.CryptoStream v_crypto;

            this.Initialize();

            v_plaintextbyteswithsalt = this.AddSalt(p_plaintextbytes);

            v_memory = new System.IO.MemoryStream();

            lock (this)
            {
                v_crypto = new System.Security.Cryptography.CryptoStream(v_memory, this.v_encryptor, System.Security.Cryptography.CryptoStreamMode.Write);
                v_crypto.Write(v_plaintextbyteswithsalt, 0, v_plaintextbyteswithsalt.Length);
                v_crypto.FlushFinalBlock();

                v_ciphertextbytes = v_memory.ToArray();

                v_memory.Close();
                v_crypto.Close();

                return v_ciphertextbytes;
            }
        }
예제 #42
0
    public static string Encrypt(string toEncrypt, string key)
    {
        var des = new System.Security.Cryptography.DESCryptoServiceProvider();
        var ms = new System.IO.MemoryStream();

        VerifyKey(ref key);

        des.Key = HashKey(key, des.KeySize / 8);
        des.IV = HashKey(key, des.KeySize / 8);
        byte[] inputBytes = Encoding.UTF8.GetBytes(toEncrypt);

        var cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
        cs.Write(inputBytes, 0, inputBytes.Length);
        cs.FlushFinalBlock();

        return HttpServerUtility.UrlTokenEncode(ms.ToArray());
    }
예제 #43
0
파일: My.cs 프로젝트: yanyuzhy/LolAutoPlay
 /// <summary>
 /// DES解密算法
 /// </summary>
 /// <param name="Source">要解密的字符串</param>
 /// <param name="SecretKey">解密密钥(8的整数倍字节数的字符串)</param>
 /// <returns>解密后的结果字符串</returns>
 public static string DES_Decode(byte[] Source, string SecretKey)
 {
     System.Security.Cryptography.DESCryptoServiceProvider provider = new System.Security.Cryptography.DESCryptoServiceProvider();
     provider.Key = System.Text.Encoding.UTF8.GetBytes(SecretKey);
     provider.IV = System.Text.Encoding.UTF8.GetBytes(SecretKey);
     System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream stream = new System.Security.Cryptography.CryptoStream(stream2, provider.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     stream.Write(Source, 0, Source.Length);
     try
     {
         stream.FlushFinalBlock();
     }
     catch (System.Security.Cryptography.CryptographicException)
     {
         return "";
     }
     return System.Text.Encoding.UTF8.GetString(stream2.ToArray());
 }
예제 #44
0
        private byte[] AESEncrypt(byte[] data, byte[] key)
        {
            byte[] cipherTextBytes = null;

            //  Create uninitialized Rijndael encryption object.
            System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged();

            // It is required that the encryption mode is Electronic Codebook (ECB)
            // see MS-OFFCRYPTO v1.0 2.3.4.7 pp 39.
            symmetricKey.Mode = System.Security.Cryptography.CipherMode.ECB;
            symmetricKey.Padding = System.Security.Cryptography.PaddingMode.None; // System.Security.Cryptography.PaddingMode.None;
            symmetricKey.KeySize = this.keySize;
            // symmetricKey.Key = key;
            // symmetricKey.IV = new byte[16];

            // Generate encryptor from the existing key bytes and initialization vector.
            // Key size will be defined based on the number of the key bytes.
            System.Security.Cryptography.ICryptoTransform encryptor = symmetricKey.CreateEncryptor(key, null);

            //  Define memory stream which will be used to hold encrypted data.
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                //  Define cryptographic stream (always use Write mode for encryption).
                using (System.Security.Cryptography.CryptoStream cryptoStream
                        = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    //  Start encrypting.
                    cryptoStream.Write(data, 0, data.Length);

                    //  Finish encrypting.
                    cryptoStream.FlushFinalBlock();
                }

                //  Convert our encrypted data from a memory stream into a byte array.
                cipherTextBytes = memoryStream.ToArray();
                return cipherTextBytes;
            }
        }
예제 #45
0
 private byte[] Crypt(byte[] inBytes, System.Security.Cryptography.ICryptoTransform xfrm)
 {
     System.IO.MemoryStream outStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream crypto = new System.Security.Cryptography.CryptoStream(outStream, xfrm, System.Security.Cryptography.CryptoStreamMode.Write);
     crypto.Write(inBytes, 0, inBytes.Length);
     crypto.FlushFinalBlock();
     for (int i = 0; i < inBytes.Length; ++i)
         inBytes[i] = 0;
     return outStream.ToArray();
 }
예제 #46
0
파일: My.cs 프로젝트: yanyuzhy/LolAutoPlay
 /// <summary>
 /// DES加密算法
 /// </summary>
 /// <param name="Source">要加密的字符串</param>
 /// <param name="SecretKey">加密密钥(8的整数倍字节数的字符串)</param>
 /// <returns>加密后的结果字符串</returns>
 public static byte[] DES_Encode(string Source, string SecretKey)
 {
     System.Security.Cryptography.DESCryptoServiceProvider provider = new System.Security.Cryptography.DESCryptoServiceProvider();
     try
     {
         provider.Key = System.Text.Encoding.UTF8.GetBytes(SecretKey);
     }
     catch (System.ArgumentException)
     {
         byte[] buffer = new byte[0];
         return buffer;
     }
     provider.IV = System.Text.Encoding.UTF8.GetBytes(SecretKey);
     System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream stream = new System.Security.Cryptography.CryptoStream(stream2, provider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     stream.Write(System.Text.Encoding.UTF8.GetBytes(Source), 0, System.Text.Encoding.UTF8.GetBytes(Source).Length);
     stream.FlushFinalBlock();
     return stream2.ToArray();
 }
예제 #47
0
        /// <summary>
        /// Encrypts a source stream and returns a Base64 result.
        /// </summary>
        /// <param name="Source">The source steam.</param>
        /// <param name="Key">A key to use for the encryption.</param>
        /// <returns>A Base64 string of the encrypted information.</returns>
        public string Encrypt(System.IO.Stream Source, string Key)
        {
            // read the stream into a byte array
            Source.Position = 0;
            byte[] bytIn = new byte[Source.Length];
            Source.Read(bytIn,0,(int)Source.Length);

            // create a MemoryStream so that the process can be done without I/O files
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            byte[] bytKey = GetLegalKey(Key);

            // set the private key
            _cryptoservice.Key = bytKey;
            _cryptoservice.IV = bytKey;

            // create an Encryptor from the Provider Service instance
            System.Security.Cryptography.ICryptoTransform encrypto = _cryptoservice.CreateEncryptor();

            // create Crypto Stream that transforms a stream using the encryption
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encrypto, System.Security.Cryptography.CryptoStreamMode.Write);

            // write out encrypted content into MemoryStream
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();

            byte[] bytOut = ms.GetBuffer();

            // convert into Base64 so that the result can be used in xml
            return System.Convert.ToBase64String(bytOut, 0, (int)ms.Length);
        }
예제 #48
0
 /// <summary>
 /// Returns a stream for hashing that can be part of a stream stack together
 /// with a callback to retrieve the hash when done.
 /// </summary>
 public static System.Security.Cryptography.CryptoStream GetFileHasherStream(System.IO.Stream stream, System.Security.Cryptography.CryptoStreamMode mode, out Func<string> getHash)
 {
     var hasher = System.Security.Cryptography.HashAlgorithm.Create(VOLUME_HASH);
     System.Security.Cryptography.CryptoStream retHasherStream =
         new System.Security.Cryptography.CryptoStream(stream, hasher, mode);
     getHash = () =>
     {
         if (mode == System.Security.Cryptography.CryptoStreamMode.Write
             && !retHasherStream.HasFlushedFinalBlock)
             retHasherStream.FlushFinalBlock();
         string retHash = Convert.ToBase64String(hasher.Hash);
         hasher.Dispose();
         return retHash;
     };
     return retHasherStream;
 }
예제 #49
0
        private byte[] Encrypt(byte[] PlainData)
        {
            byte[] Result = null;

            try
            {
                System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
                Enc.KeySize = 256;
                Enc.Key = this.Encryption_Key();
                Enc.IV = this.Encryption_IV();

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cryptoStream = null;
                cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cryptoStream.Write(PlainData, 0, PlainData.Length);
                cryptoStream.FlushFinalBlock();
                Result = memoryStream.ToArray();
                cryptoStream.Close();
                memoryStream.Close();
                cryptoStream.Dispose();
                memoryStream.Dispose();

            }
            catch (Exception)
            {
                Result = null;
            }

            return Result;
        }