private static byte[] Decrypt(byte[] cipherKey, byte[] ciphertext)
        {
            var cipher = new System.Security.Cryptography.AesManaged();
            cipher.Key = cipherKey;
            cipher.Mode = System.Security.Cryptography.CipherMode.CBC;
            cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

            var ivSize = cipher.IV.Length;
            var iv = new byte[ivSize];
            Array.Copy(ciphertext, iv, ivSize);
            cipher.IV = iv;

            var data = new byte[ciphertext.Length - ivSize];
            Array.Copy(ciphertext, ivSize, data, 0, data.Length);

            using (var ms = new System.IO.MemoryStream())
            {
                using (var cs = new System.Security.Cryptography.CryptoStream(
                    ms, cipher.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                }

                var plaintext = ms.ToArray();
                return plaintext;
            }
        }
Example #2
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);
        }
Example #3
0
File: Des.cs Project: Fun33/code
        /// <summary>
        /// 加密文件
        /// </summary>
        public void EncryptFile(string Value, string OuputFileName)
        {
            try
            {
                // Must be 64 bits, 8 bytes.
                // Distribute this key to the user who will decrypt this file.
                //Get the Key for the file to Encrypt.
                string sKey = GenerateKey();

                byte[] b = ASCIIEncoding.ASCII.GetBytes(Value);

                System.IO.FileStream fsEncrypted = new System.IO.FileStream(OuputFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);

                System.Security.Cryptography.DESCryptoServiceProvider DES = new System.Security.Cryptography.DESCryptoServiceProvider();
                DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                DES.IV  = ASCIIEncoding.ASCII.GetBytes(sKey);

                System.Security.Cryptography.ICryptoTransform desencrypt = DES.CreateEncryptor();
                System.Security.Cryptography.CryptoStream     cs         = new System.Security.Cryptography.CryptoStream(fsEncrypted, desencrypt, System.Security.Cryptography.CryptoStreamMode.Write);

                cs.Write(b, 0, b.Length);
                cs.Close();

                fsEncrypted.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #4
0
        public static string Encrypt(string plainText, string encryptionKey)
        {
            //string EncryptionKey = "tahaahat";

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

            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(plainText);

            using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
            {
                System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV  = pdb.GetBytes(16);

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    plainText = HttpServerUtility.UrlTokenEncode(ms.ToArray());
                }
            }
            return(plainText);
        }
                //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("=", "");
                }
Example #6
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);
        }
 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; }
 }
Example #8
0
        public static string Encrypt(string encryptValue)
        {
            string key       = "12345678912345678912345678912345";
            string Indicator = "mdhyadhsddmyghjq";

            byte[] password           = Encoding.ASCII.GetBytes(encryptValue);
            byte[] Key                = Encoding.ASCII.GetBytes(key);
            byte[] IV                 = Encoding.ASCII.GetBytes(Indicator);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
            alg.Key = Key;
            alg.IV  = IV;
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms,
                                                                                                         alg.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(password, 0, password.Length);
            cs.Close();
            byte[] encryptedData = ms.ToArray();
            string str           = null;

            //convert byte into comma seprate string
            for (int i = 0; i < encryptedData.Length; i++)
            {
                str = str + encryptedData[i] + '.';
            }
            //trim , at the end
            str = str.TrimEnd('.');
            return(str);
        }
Example #9
0
        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
        }
Example #10
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("=", ""));
                }
Example #11
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("");
     }
 }
Example #12
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));
        }
Example #13
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);
            }
        }
 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);
 }
Example #15
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()));
        }
        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);
        }
Example #17
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;
            }
        }
Example #18
0
            /// <summary>
            /// 解密指定的字节数据
            /// </summary>
            /// <param name="originalData">加密的字节数据</param>
            /// <param name="keyData">解密密钥</param>
            /// <param name="ivData"></param>
            /// <returns>原始文本</returns>
            private static byte[] Decrypt(byte[] encryptedData, byte[] keyData, byte[] ivData)
            {
                MemoryStream memoryStream = new MemoryStream();

                //创建Rijndael加密算法
                System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
                rijndael.Key = keyData;
                rijndael.IV  = ivData;

                System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(
                    memoryStream, rijndael.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                try
                {
                    cryptoStream.Write(encryptedData, 0, encryptedData.Length);
                    cryptoStream.Close();
                    cryptoStream.Dispose();
                    return(memoryStream.ToArray());
                }
                catch (Exception ex)
                {
                    LogManager.Instance.WriteLog("GlobalMethods.Decrypt", ex);
                    return(null);
                }
                finally
                {
                    memoryStream.Close();
                    memoryStream.Dispose();
                }
            }
        public static string Encrypt(string input, string pwdValue)
        {
            try
            {
                byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
                byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);
                // AesManaged - 高级加密标准(AES) 对称算法的管理类
                System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();
                // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数)             // 通过 密码 和 salt 派生密钥
                System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
                aes.Key       = rfc.GetBytes(aes.KeySize / 8);
                aes.IV        = rfc.GetBytes(aes.BlockSize / 8);
                // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象
                System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor();
                // 加密后的输出流
                System.IO.MemoryStream encryptStream = new System.IO.MemoryStream();
                // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接
                System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream(encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);
                // 将一个字节序列写入当前 CryptoStream (完成加密的过程)
                encryptor.Write(data, 0, data.Length);
                encryptor.Close();
                // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串
                string encryptedString = Convert.ToBase64String(encryptStream.ToArray());

                return(encryptedString);
            }
            catch
            {
            }
            return(input);
        }
Example #20
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);
        }
Example #21
0
        public string Encrypt(string inVal)
        {
            try
            {
                //System.Text.Encoder encoding;
                //System.Text.Encoder encoding = System.Text.Encoding.ASCII

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

                //Create variables to help with read and write.
                byte[] bin; //This is intermediate storage for the encryption.
                System.Security.Cryptography.SymmetricAlgorithm encAlg    = System.Security.Cryptography.SymmetricAlgorithm.Create("RC2");
                System.Security.Cryptography.CryptoStream       encStream = new System.Security.Cryptography.CryptoStream(MSout, encAlg.CreateEncryptor(bKey, bIV), System.Security.Cryptography.CryptoStreamMode.Write);

                bin = ConvertStringToByteArray(inVal);
                encStream.Write(bin, 0, inVal.Length);
                encStream.Close();
                bin = MSout.ToArray();
                MSout.Close();

                return(formatHexString(bin));
            }
            catch (System.Exception ex)
            {
                // Log Error
                throw ex;
            }
        }
Example #22
0
        private string Decrypt(string cipher, string type)
        {
            string EncryptionKey;

            byte[] cipherBytes;

            EncryptionKey = string.Format(this.Core.GetAttribute("DecryptKey"), type);

            cipherBytes = Convert.FromBase64String(cipher);

            using (System.Security.Cryptography.Rijndael encryptor = System.Security.Cryptography.Rijndael.Create())
            {
                System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKey, Convert.FromBase64String(this.Core.GetAttribute("DecryptSalt")));

                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV  = pdb.GetBytes(16);

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }

                    cipher = System.Text.Encoding.Unicode.GetString(ms.ToArray());
                }
            }

            return(cipher);
        }
Example #23
0
        public string Decrypt(string inVal)
        {
            try
            {
                System.IO.MemoryStream MSout = new System.IO.MemoryStream();
                byte[] bin;
                byte[] retArr;

                //Create variables to help with read and write.
                System.Security.Cryptography.SymmetricAlgorithm encAlg    = System.Security.Cryptography.SymmetricAlgorithm.Create("RC2");
                System.Security.Cryptography.CryptoStream       DecStream = new System.Security.Cryptography.CryptoStream(MSout, encAlg.CreateDecryptor(bKey, bIV), System.Security.Cryptography.CryptoStreamMode.Write);
                bin = DeformatHexString(inVal);

                DecStream.Write(bin, 0, bin.Length);
                DecStream.Close();
                retArr = MSout.ToArray();

                MSout.Close();
                System.Text.ASCIIEncoding getStr = new ASCIIEncoding();

                return(getStr.GetString(retArr));
            }
            catch (System.Exception ex)
            {
                // Log Error
                throw ex;
            }
        }
Example #24
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("");
            }
        }
Example #25
0
        public UniversalHashFunction(byte[] keyOf16Or24Or32Bytes, int randomKeyVectorLengthInBytes = 256)
        {
            int numberOfRandomBytesToGenerate = SetVectorLengthAndGetNumberOfRandomBytesNeeded(randomKeyVectorLengthInBytes);

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Key  = keyOf16Or24Or32Bytes;
                aes.IV   = new byte[16];
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;

                byte[] pseudoRandomBytes;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ciphertext, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        if (numberOfRandomBytesToGenerate % 16 != 0)
                        {
                            numberOfRandomBytesToGenerate += 16 - (numberOfRandomBytesToGenerate % 16);
                        }
                        cs.Write(new byte[numberOfRandomBytesToGenerate], 0, numberOfRandomBytesToGenerate);
                    }
                    pseudoRandomBytes = ciphertext.ToArray();
                }

                _randomKeyVector = new ulong[randomKeyVectorLengthInBytes / 8];
                for (int i = 0; i < _randomKeyVector.Length; i++)
                {
                    _randomKeyVector[i] = BitConverter.ToUInt64(pseudoRandomBytes, i * 8);
                }
                _initialRandomKey = BitConverter.ToUInt64(pseudoRandomBytes, randomKeyVectorLengthInBytes);
            }
        }
        /// <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);
            }
        }
Example #27
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));
        }
        /// <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));
        }
Example #29
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);
        }
Example #30
0
        public string EncryptPassword(string clearText)
        {
            string encryptedText = "";


            string EncryptionKey = "Xavier";

            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
            {
                System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV  = pdb.GetBytes(16);
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    encryptedText = Convert.ToBase64String(ms.ToArray());
                }
            }


            return(encryptedText);
        }
Example #31
0
        public static string Decrypt(string decryptValue)
        {
            string[]      csbytes = decryptValue.Split('.');
            byte[]        temp    = new byte[csbytes.Length];
            StringBuilder sUC     = new StringBuilder();

            for (int ictr = 0; ictr < csbytes.Length; ictr++)
            {
                temp[ictr] = Convert.ToByte(csbytes[ictr].ToString());
            }
            string key       = "12345678912345678912345678912345";
            string Indicator = "mdhyadhsddmyghjq";

            byte[] Key = Encoding.ASCII.GetBytes(key);
            byte[] IV  = Encoding.ASCII.GetBytes(Indicator);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
            alg.Key = Key;
            alg.IV  = IV;
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(temp, 0, temp.Length);
            cs.Close();
            byte[] decryptedData = ms.ToArray();
            string org;

            org = (Encoding.UTF8.GetString(decryptedData));
            return(org);
        }
Example #32
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();
            }
        }
Example #33
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));
                            }
                        }
                    }
                }
            }
        }
Example #34
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("");
            }
        }
Example #35
0
File: Utility.cs Project: JuRogn/OA
        /// <summary>
        /// 根据给定的字符串对其进行加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string input)
        {
            // 盐值
            string saltValue = "saltValue";
            // 密码值
            string pwdValue = "pwdValue";

            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
            byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);

            // AesManaged - 高级加密标准(AES) 对称算法的管理类
            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();

            // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数)
            // 通过 密码 和 salt 派生密钥
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);

            /**/
            /*
         * AesManaged.BlockSize - 加密操作的块大小(单位:bit)
         * AesManaged.LegalBlockSizes - 对称算法支持的块大小(单位:bit)
         * AesManaged.KeySize - 对称算法的密钥大小(单位:bit)
         * AesManaged.LegalKeySizes - 对称算法支持的密钥大小(单位:bit)
         * AesManaged.Key - 对称算法的密钥
         * AesManaged.IV - 对称算法的密钥大小
         * Rfc2898DeriveBytes.GetBytes(int 需要生成的伪随机密钥字节数) - 生成密钥
         */

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象
            System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor();

            // 加密后的输出流
            System.IO.MemoryStream encryptStream = new System.IO.MemoryStream();

            // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接
            System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream
                (encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);

            // 将一个字节序列写入当前 CryptoStream (完成加密的过程)
            encryptor.Write(data, 0, data.Length);
            encryptor.Close();

            // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串
            string encryptedString = Convert.ToBase64String(encryptStream.ToArray());

            return encryptedString;
        }
            /// <summary>
            /// Encripcion Byte Key IV
            /// </summary>
            /// <param name="clearData">Datos en limpio</param>
            /// <param name="Key">Llave</param>
            /// <param name="IV">IV</param>
            /// <returns>Arreglo de byte's.</returns>
            private static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.Security.Cryptography.Rijndael alg;
                alg = System.Security.Cryptography.Rijndael.Create();
                alg.Key = Key;
                alg.IV = IV;

                System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, alg.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cs.Write(clearData, 0, clearData.Length);
                cs.Close();

                byte[] encryptedData = ms.ToArray();
                return encryptedData;
            }
Example #37
0
        public static MemoryStream EncryptStream(string key, byte[] content)
        {
            System.Security.Cryptography.SymmetricAlgorithm rijn = System.Security.Cryptography.SymmetricAlgorithm.Create();

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] rgbIV = Encoding.ASCII.GetBytes("polychorepolycho");
                byte[] rgbKey = Encoding.ASCII.GetBytes(key);
                System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, rijn.CreateEncryptor(rgbKey, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write);

                cs.Write(content, 0, content.Length);
                cs.Close();

                return ms;
            }
        }
Example #38
0
        /// <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;
            }
        }
Example #39
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Decrypt(string input)
        {
            byte[] encryptBytes = Convert.FromBase64String(input);
            byte[] salt = Encoding.UTF8.GetBytes(saltValue);

            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV = rfc.GetBytes(aes.BlockSize / 8);

            System.Security.Cryptography.ICryptoTransform transform = aes.CreateDecryptor();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream
            (stream, transform, System.Security.Cryptography.CryptoStreamMode.Write);
            decryptor.Write(encryptBytes, 0, encryptBytes.Length);
            decryptor.Close();
            byte[] decryptBytes = stream.ToArray();
            return UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
        }
Example #40
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Encrypt(string input)
        {
            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
            byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);

            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV = rfc.GetBytes(aes.BlockSize / 8);

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

            encryptor.Write(data, 0, data.Length);
            encryptor.Close();
            return Convert.ToBase64String(stream.ToArray());
        }
        private static byte[] Encrypt(byte[] cipherKey, byte[] plaintext)
        {
            var cipher = new System.Security.Cryptography.AesManaged();
            cipher.Key = cipherKey;
            cipher.Mode = System.Security.Cryptography.CipherMode.CBC;
            cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

            using (var ms = new System.IO.MemoryStream())
            {
                using (var cs = new System.Security.Cryptography.CryptoStream(
                    ms, cipher.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(plaintext, 0, plaintext.Length);
                }

                var ciphertext = ms.ToArray();

                var message = new byte[cipher.IV.Length + ciphertext.Length];
                cipher.IV.CopyTo(message, 0);
                ciphertext.CopyTo(message, cipher.IV.Length);
                return message;
            }
        }
Example #42
0
        /// <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();
        }
Example #43
0
 /// <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();
 }
        /// <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);
        }
Example #45
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 "";
            }
        }
Example #46
0
            /// <summary>
            /// ����ָ�����ֽ�����
            /// </summary>
            /// <param name="originalData">ԭʼ�ֽ�����</param>
            /// <param name="keyData">������Կ</param>
            /// <param name="ivData"></param>
            /// <returns>���ܺ������</returns>
            private static byte[] Encrypt(byte[] originalData, byte[] keyData, byte[] ivData)
            {
                MemoryStream memoryStream = new MemoryStream();
                //����Rijndael�����㷨
                System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
                rijndael.Key = keyData;
                rijndael.IV = ivData;

                System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(
                    memoryStream, rijndael.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                try
                {
                    cryptoStream.Write(originalData, 0, originalData.Length);
                    cryptoStream.Close();
                    cryptoStream.Dispose();
                    return memoryStream.ToArray();
                }
                catch (Exception ex)
                {
                    LogManager.Instance.WriteLog("GlobalMethods.Encrypt", ex);
                    return null;
                }
                finally
                {
                    memoryStream.Close();
                    memoryStream.Dispose();
                }
            }
Example #47
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();
                }
            }
        }
        /// <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;
            }
        }
        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);
        }
Example #50
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());
    }
Example #51
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);
        }
        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;
        }
 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();
 }
Example #54
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;
            }
        }
Example #55
0
        /// <summary>
        /// Construct a keyed universal hash function.
        /// 
        /// An instance of a universal hash function needs to store on the order of RandomKeyVectorLengthInBytes values upon construction,
        /// so it is best not to initialize this function for large strings (e.g., those over 32k).
        /// 
        /// </summary>
        /// <param name="keyOf16Or24Or32Bytes">A key that should not be known to those who might try to create collisions, provided as an array of 16, 24, or 32 bytes.</param>
        /// <param name="randomKeyVectorLengthInBytes">The length of the random key vector used for hashing.  Should be twice the length of the longest value you expect to hash,
        /// unless you hash values bigger than you would want to keep in memory.  If hashing a value longer than this, the universal hash properties may not hold.</param>
        public UniversalHashFunction(byte[] keyOf16Or24Or32Bytes, int randomKeyVectorLengthInBytes = 256)
        {
            int numberOfRandomBytesToGenerate = SetVectorLengthAndGetNumberOfRandomBytesNeeded(randomKeyVectorLengthInBytes);

            // Generate enough random bytes to fill the RandomKeyVector and 4 extra for the InitialRandomKey
            using (System.Security.Cryptography.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                aes.Key = keyOf16Or24Or32Bytes;
                aes.IV = new byte[16];
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;

                // Encrypt a null message with the key using CBC and InitializationVector=0
                byte[] pseudoRandomBytes;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ciphertext, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        if (numberOfRandomBytesToGenerate % 16 != 0)
                        {
                            // Round to next 128-bit boundary since we're using AES 128-bit blocks to generate randomness
                            numberOfRandomBytesToGenerate += 16 - (numberOfRandomBytesToGenerate % 16);
                        }
                        cs.Write(new byte[numberOfRandomBytesToGenerate], 0, numberOfRandomBytesToGenerate);
                        // Ensure all bytes are flushed.
                    }
                    pseudoRandomBytes = ciphertext.ToArray();
                }

                // Create the random key vector and fill it with random bytes
                _randomKeyVector = new ulong[randomKeyVectorLengthInBytes / 8];
                for (int i = 0; i < _randomKeyVector.Length; i++)
                    _randomKeyVector[i] = BitConverter.ToUInt64(pseudoRandomBytes, i * 8);
                // Fill the initial random key with the last remaining 8 bytes
                _initialRandomKey = BitConverter.ToUInt64(pseudoRandomBytes, randomKeyVectorLengthInBytes);
            }
        }
Example #56
0
 /// <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());
 }