Inheritance: Stream, IDisposable
Ejemplo n.º 1
1
        public static string Decrypt(string sourceData)
        {
            // set key and initialization vector values
              byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
              byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
              try
              {
            // convert data to byte array
            byte[] encryptedDataBytes =
               Convert.FromBase64String(sourceData);

            // get source memory stream and fill it
            MemoryStream tempStream =
               new MemoryStream(encryptedDataBytes, 0,
              encryptedDataBytes.Length);

            // get decryptor and decryption stream
            DESCryptoServiceProvider decryptor =
               new DESCryptoServiceProvider();
            CryptoStream decryptionStream =
               new CryptoStream(tempStream,
              decryptor.CreateDecryptor(key, iv),
              CryptoStreamMode.Read);

            // decrypt data
            StreamReader allDataReader =
               new StreamReader(decryptionStream);
            return allDataReader.ReadToEnd();
              }
              catch
              {
            throw new StringEncryptorException(
               "Unable to decrypt data.");
              }
        }
Ejemplo n.º 2
1
        public static string Encode(string str, string key)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            byte[] bytes = Encoding.UTF8.GetBytes(str);

            MemoryStream stream = new MemoryStream();

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            stream2.Write(bytes, 0, bytes.Length);

            stream2.FlushFinalBlock();

            StringBuilder builder = new StringBuilder();

            foreach (byte num in stream.ToArray())
            {

                builder.AppendFormat("{0:X2}", num);

            }

            stream.Close();

            return builder.ToString();
        }
Ejemplo n.º 3
1
        public static string DecryptString(String cipherText, string Key)
        {
            byte[] tmpCipherText = Convert.FromBase64String(cipherText);
            byte[] tmpKey = GenerateAlgotihmInputs(Key);

            using (RijndaelManaged alg = new RijndaelManaged())
            {
                alg.Key = tmpKey;
                alg.IV = tmpKey;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(tmpCipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        // Place les données déchiffrées dans un tableau d'octet
                        byte[] plainTextData = new byte[tmpCipherText.Length];

                        int decryptedByteCount = csDecrypt.Read(plainTextData, 0, plainTextData.Length);
                        return Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount);
                    }

                }

            }
        }
Ejemplo n.º 4
1
        // Decrypt a byte array into a byte array using a key and an IV
        public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV, CipherMode cipherMode, PaddingMode paddingMode)
        {
            // Create a MemoryStream that is going to accept the
            // decrypted bytes
            MemoryStream ms = new MemoryStream();

            // Create a symmetric algorithm.
            // We are going to use Rijndael because it is strong and
            // available on all platforms.
            // You can use other algorithms, to do so substitute the next
            // line with something like
            //     TripleDES alg = TripleDES.Create();

            Rijndael alg = Rijndael.Create();

            // Now set the key and the IV.
            // We need the IV (Initialization Vector) because the algorithm
            // is operating in its default
            // mode called CBC (Cipher Block Chaining). The IV is XORed with
            // the first block (8 byte)
            // of the data after it is decrypted, and then each decrypted
            // block is XORed with the previous
            // cipher block. This is done to make encryption more secure.
            // There is also a mode called ECB which does not need an IV,
            // but it is much less secure.

            alg.Mode = cipherMode;
            alg.Padding = paddingMode;
            alg.Key = Key;
            alg.IV = IV;

            // Create a CryptoStream through which we are going to be
            // pumping our data.
            // CryptoStreamMode.Write means that we are going to be
            // writing data to the stream
            // and the output will be written in the MemoryStream
            // we have provided.

            CryptoStream cs = new CryptoStream(ms,
                alg.CreateDecryptor(), CryptoStreamMode.Write);

            // Write the data and make it do the decryption
            cs.Write(cipherData, 0, cipherData.Length);

            // Close the crypto stream (or do FlushFinalBlock).
            // This will tell it that we have done our decryption
            // and there is no more data coming in,
            // and it is now a good time to remove the padding
            // and finalize the decryption process.

            cs.Close();

            // Now get the decrypted data from the MemoryStream.
            // Some people make a mistake of using GetBuffer() here,
            // which is not the right way.

            byte[] decryptedData = ms.ToArray();

            return decryptedData;
        }
Ejemplo n.º 5
1
        public static string EncryptString(
            string plainText,
            string passPhrase,
            string saltValue,
            int passwordIterations,
            string initVector,
            int keySize)
        {

            byte[] initVectorBytes = initVector == null ? new byte[16] : Encoding.ASCII.GetBytes(initVector);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] keyBytes = GetKeyBytes(passPhrase, saltValue, passwordIterations, keySize);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            byte[] cipherTextBytes;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                }
            }
            string cipherText = Convert.ToBase64String(cipherTextBytes);
            return cipherText;
        }
Ejemplo n.º 6
1
        public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
        {
            byte[] encryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }
Ejemplo n.º 7
1
        public static void DecryptFile(string strKey, string pathCypheredTextFile, string pathPlainTextFile)
        {
            // Place la clé de déchiffrement dans un tableau d'octets
            byte[] key = GenerateAlgotihmInputs(strKey);

            // Place le vecteur d'initialisation dans un tableau d'octets
            byte[] iv = GenerateAlgotihmInputs(strKey);

            // Filestream of the new file that will be decrypted.
            Directory.CreateDirectory(Directory.GetParent(pathPlainTextFile).FullName);
            FileStream fsCrypt = new FileStream(pathPlainTextFile, FileMode.Create);

            RijndaelManaged rijndael = new RijndaelManaged();
            rijndael.Mode = CipherMode.CBC;
            rijndael.Key = key;
            rijndael.IV = iv;

            ICryptoTransform aesDecryptor = rijndael.CreateDecryptor();

            CryptoStream cs = new CryptoStream(fsCrypt, aesDecryptor, CryptoStreamMode.Write);

            // FileStream of the file that is currently encrypted.
            FileStream fsIn = new FileStream(pathCypheredTextFile, FileMode.OpenOrCreate);

            int data;

            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);
            cs.Close();
            fsIn.Close();
            fsCrypt.Close();
        }
 public static string Encrypt(string plainText, string passPhrase)
 {
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                     {
                         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                         cryptoStream.FlushFinalBlock();
                         byte[] cipherTextBytes = memoryStream.ToArray();
                         return Convert.ToBase64String(cipherTextBytes);
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 9
1
        private static readonly byte[] Iv = System.Text.Encoding.ASCII.GetBytes("E&naQSWy$QPY9K0d");                      // 16 chars - 128 bit vector

        private static byte[] StringToBytes_Aes(string plainText)
        {
            // Check arguments. 
            Require.NotNullOrEmpty(plainText, "plainText");

            // Create an AES (aka Rijndael) algorithm object 
            byte[] encryptedBytes;
            using (var aesAlgorithm = Aes.Create())
            {
                // Create a encryptor with the specified Key and Iv
                // to perform the stream transform.
                aesAlgorithm.Key = Key;
                aesAlgorithm.IV = Iv;
                using (var encryptor = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    // Create the streams used for encryption.
                    using (var encryptionStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(encryptionStream, encryptor, CryptoStreamMode.Write))
                        {
                            using (var encryptionStreamWriter = new StreamWriter(cryptoStream))
                            {
                                // Write all data to the stream.
                                encryptionStreamWriter.Write(plainText);
                            }
                            encryptedBytes = encryptionStream.ToArray();

                        }
                    }
                }
            }

            // Return the encrypted bytes from the memory stream. 
            return encryptedBytes;
        }
Ejemplo n.º 10
1
        public static string Descriptografar(string codigo)
        {
            try
            {
                if (string.IsNullOrEmpty(codigo))
                    return String.Empty;
                string retorno;
                var chave = new Rfc2898DeriveBytes(Segredo, Complemento);

                var algoritimo = new RijndaelManaged();
                algoritimo.Key = chave.GetBytes(algoritimo.KeySize / 8);
                algoritimo.IV = chave.GetBytes(algoritimo.BlockSize / 8);

                var descriptografor = algoritimo.CreateDecryptor(algoritimo.Key, algoritimo.IV);
                var bytes = Convert.FromBase64String(codigo);

                using (var memoryStream = new MemoryStream(bytes))
                using (var cryptoStream = new CryptoStream(memoryStream, descriptografor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                    retorno = streamReader.ReadToEnd();

                algoritimo.Clear();

                return retorno;
            }
            catch (Exception)
            {
                return "DEU PAU";
            }
        }
Ejemplo n.º 11
1
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="pToEncrypt">需要加密字符串</param>
        /// <param name="sKey">密钥</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string pToEncrypt, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                //把字符串放到byte数组中

                //原来使用的UTF8编码,我改成Unicode编码了,不行
                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);

                //建立加密对象的密钥和偏移量

                //使得输入密码必须输入英文文本
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                ret.ToString();
                return ret.ToString();
            }
            catch (Exception ex)
            {

            }

            return "";
        }
Ejemplo n.º 12
1
 public AesStream(Socket socket, EnhancedStream stream, byte[] key)
     : base(socket)
 {
     BaseStream = stream;
     _enc = new CryptoStream(stream, GenerateAES(key).CreateEncryptor(), CryptoStreamMode.Write);
     _dec = new CryptoStream(stream, GenerateAES(key).CreateDecryptor(), CryptoStreamMode.Read);
 }
Ejemplo n.º 13
1
        public static string Encrypt( string strEncryptString, string strEncryptionKey)
        {
            byte[] inputByteArray;

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

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Encoding.UTF8.GetBytes(strEncryptString);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);

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

                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception eX)
            {

                throw eX;
            }
        }
Ejemplo n.º 14
1
        /// <summary>
        /// AES解密(无向量)
        /// </summary>
        /// <param name="encryptedBytes">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string AESDecryptWithoutVector(String Data, String Key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

            MemoryStream mStream = new MemoryStream(encryptedBytes);
            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
            //mStream.Seek( 0, SeekOrigin.Begin );
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
                byte[] tmp = new byte[encryptedBytes.Length + 32];
                int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                byte[] ret = new byte[len];
                Array.Copy(tmp, 0, ret, 0, len);
                return Encoding.UTF8.GetString(ret);
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
Ejemplo n.º 15
1
        public static string EncryptString(string plainText)
        {
            byte[] encrypted;

            AesCryptoServiceProvider provider = createAesProvider();

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = provider.CreateEncryptor(provider.Key, null); // null IV, because ECB mode

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
            // Return the encrypted bytes from the memory stream.
            return encoding.GetString(encrypted);
        }
Ejemplo n.º 16
1
        public byte[] Encrypt(byte[] block)
        {
            ICryptoTransform enc = null;
            Aes.Mode = CipherMode.CBC;
            Aes.Key = key;
            Aes.GenerateIV();
            Console.WriteLine("Key: {0} IV: {1}", CNetwork.ByteArrayToString(Aes.Key), CNetwork.ByteArrayToString(Aes.IV));

            CryptoStream cstream = null;
            MemoryStream mem = null;
            byte[] toEncrypt = null;

            try
            {
                cstream = null;
                mem = new MemoryStream();
                toEncrypt = block;
                enc = Aes.CreateEncryptor();
                cstream = new CryptoStream(mem, enc, CryptoStreamMode.Write);
                cstream.Write(toEncrypt, 0, toEncrypt.Length);
            }
            finally
            {
                if (cstream != null)
                    Aes.Clear();
                cstream.Close();
            }

            Console.WriteLine(CNetwork.ByteArrayToString(mem.ToArray()));

            return mem.ToArray();
        }
Ejemplo n.º 17
1
 /// <summary>
 /// 解密
 /// </summary>
 /// <param name="text">要被解密字符</param>
 /// <param name="sKey">密钥</param>
 /// <returns></returns>
 public static string Decrypt(this string text, string sKey)
 {
     var provider = new DESCryptoServiceProvider();
     int num = text.Length / 2;
     byte[] buffer = new byte[num];
     try
     {
         for (int i = 0; i < num; i++)
         {
             int num3 = Convert.ToInt32(text.Substring(i * 2, 2), 0x10);
             buffer[i] = (byte)num3;
         }
     }
     catch
     {
         return string.Empty;
     }
     provider.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
     provider.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
     MemoryStream stream = new MemoryStream();
     CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
     try
     {
         stream2.Write(buffer, 0, buffer.Length);
         stream2.FlushFinalBlock();
     }
     catch
     {
         return string.Empty;
     }
     return Encoding.Default.GetString(stream.ToArray());
 }
Ejemplo n.º 18
1
        public static string Criptografar(string texto)
        {
            if(string.IsNullOrEmpty(texto))
                return String.Empty;

            string outStr;

            RijndaelManaged aesAlg = null;
            try
            {
                var key = new Rfc2898DeriveBytes(Segredo, Complemento);
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(texto);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return outStr;
        }
Ejemplo n.º 19
0
        public static string Decrypt(string encryptedText)
        {
            RegistryKey registryKey =
                Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\10.0\PbsEncryptionKey");
            var password = (string)registryKey.GetValue("Key");
            var passwordDerivedBytes = new PasswordDeriveBytes(password, _salt);
            byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText);

            using (var memoryStream = new MemoryStream())
            {
                using (var rijndael = Rijndael.Create())
                {
                    using (
                        var cryptoTransform = rijndael.CreateDecryptor(passwordDerivedBytes.GetBytes(32), 
                            passwordDerivedBytes.GetBytes(16)))
                    {
                        using (
                            var cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
                                CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
                            cryptoStream.Close();
                            return Encoding.Unicode.GetString(memoryStream.ToArray());
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
 public byte[] Encrypt(string plainText, byte[] Key, byte[] IV)
 {
     byte[] encrypted;
     // Create a new AesManaged.
     using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged())
     {
         // Create encryptor
         System.Security.Cryptography.ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);
         // Create MemoryStream
         using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
         {
             // Create crypto stream using the CryptoStream class. This class is the key to encryption
             // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream
             // to encrypt
             using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
             {
                 // Create StreamWriter and write data to a stream
                 using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cs))
                     sw.Write(plainText);
                 encrypted = ms.ToArray();
             }
         }
     }
     // Return encrypted data
     return(encrypted);
 }
Ejemplo n.º 21
0
        private static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(cipherText))
                {
                    using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(
                               msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return(plaintext);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="sIn"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public string Encrypt(string sIn, string sKey = "ColtSmart")
        {
            byte[] inputByteArray = System.Text.Encoding.ASCII.GetBytes(sIn);
            using (System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider())
            {
                des.Mode    = CipherMode.ECB;
                des.Padding = PaddingMode.Zeros;
                byte[] keyByteArray      = new byte[8];
                byte[] inputKeyByteArray = ASCIIEncoding.ASCII.GetBytes(sKey);
                for (int i = 0; i < 8; i++)
                {
                    if (inputKeyByteArray.Length > i)
                    {
                        keyByteArray[i] = inputKeyByteArray[i];
                    }
                    else
                    {
                        keyByteArray[i] = 0;
                    }
                }

                des.Key = keyByteArray;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (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();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return(str);
            }
        }
        public string Encrypt(string Text)
        {
            string outText = string.Empty;

            System.Security.Cryptography.CryptoStream myCryptoStream = null;
            try
            {
                System.Byte[]          bufferRead     = System.Text.Encoding.ASCII.GetBytes(Text);
                System.IO.MemoryStream myOutMemStream = new System.IO.MemoryStream(1024);

                myrijManaged.Key = keyByte;
                myrijManaged.IV  = IVByte;
                System.Security.Cryptography.ICryptoTransform myCryptoTransform = myrijManaged.CreateEncryptor();
                myCryptoStream = new System.Security.Cryptography.CryptoStream(myOutMemStream, myCryptoTransform, System.Security.Cryptography.CryptoStreamMode.Write);
                myCryptoStream.Write(bufferRead, 0, bufferRead.Length);
                myCryptoStream.FlushFinalBlock();
                System.Byte[] result = new byte[(int)myOutMemStream.Position];
                myOutMemStream.Position = 0;
                myOutMemStream.Read(result, 0, result.Length);
                outText = System.Convert.ToBase64String(result);
            }
            catch (Exception exp)
            {
                throw exp;
            }
            finally
            {
                if (myCryptoStream != null)
                {
                    myCryptoStream.Close();
                }
            }

            return(outText);
        }
        public string Decrypt(string CypherText)
        {
            string outText = string.Empty;

            System.Security.Cryptography.CryptoStream myCryptoStream = null;
            try
            {
                System.Byte[]          data      = System.Convert.FromBase64String(CypherText);
                System.IO.MemoryStream memStream = new System.IO.MemoryStream(data.Length);

                myrijManaged.Key = keyByte;
                myrijManaged.IV  = IVByte;
                System.Security.Cryptography.ICryptoTransform myCryptoTransform = myrijManaged.CreateDecryptor();
                myCryptoStream = new System.Security.Cryptography.CryptoStream(memStream, myCryptoTransform, System.Security.Cryptography.CryptoStreamMode.Read);

                memStream.Write(data, 0, data.Length);
                memStream.Position = 0;
                outText            = new System.IO.StreamReader(myCryptoStream).ReadToEnd();
            }
            catch (Exception exp)
            {
                throw exp;
            }
            finally
            {
                if (myCryptoStream != null)
                {
                    myCryptoStream.Close();
                }
            }
            return(outText);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Décrypte une chaine cryptée à partir d'un chiffreur symétrique
        /// </summary>
        /// <param name="base64String">chaine cryptée</param>
        /// <param name="pass">Mot de passe utilisé pour dériver la clé</param>
        /// <returns>Chaine décryptée</returns>
        private static string Decrypt(string base64String, string pass)
        {
            string result = string.Empty;

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.IV = new byte[8];
            System.Security.Cryptography.PasswordDeriveBytes pdb =
                new System.Security.Cryptography.PasswordDeriveBytes(pass, new byte[0]);
            des.Key = pdb.CryptDeriveKey("RC2", "SHA1", 128, new byte[8]);
            byte[] encryptedBytes = Convert.FromBase64String(base64String);

            using (MemoryStream ms = new MemoryStream(base64String.Length))
            {
                using (System.Security.Cryptography.CryptoStream decStream =
                           new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(),
                                                                         System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    decStream.FlushFinalBlock();
                    byte[] plainBytes = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(plainBytes, 0, (int)ms.Length);
                    result = Encoding.UTF8.GetString(plainBytes);
                }
            }
            return(result);
        }
Ejemplo n.º 26
0
    public static void Main()
    {
        //chave secreta
        byte[] Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
        //vetor de inicialização
        byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

        //Stream de memória
        IO.MemoryStream memstream = new IO.MemoryStream(15);
        //Stream de criptografia
        CP.RC2CryptoServiceProvider provider  = new CP.RC2CryptoServiceProvider();
        CP.ICryptoTransform         transform = provider.CreateEncryptor(Key, IV);
        CP.CryptoStreamMode         mode      = CP.CryptoStreamMode.Write;
        CP.CryptoStream             stream    = new CP.CryptoStream(memstream, transform, mode);

        //Lê cada caracter da string
        foreach (char ch in "Isto é um teste")
        {
            stream.WriteByte((Convert.ToByte(ch)));
        }

        int c;

        //Reposiciona o ponteiro para leitura
        memstream.Position = c = 0; //técnica não trivial, mas válida

        while ((c = memstream.ReadByte()) != -1)
        {
            Console.Write((char)c);
        }

        stream.Close();    //Libera a stream (crypto)
        memstream.Close(); //Libera a stream (mem)
    }
        private void EncryptUsingDotNet(Stream istream, Stream ostream, byte[] iv, bool forEncryption)
        {
            var engine = BlockCipherModel.Engine.Instance <SysSecurity.SymmetricAlgorithm>();
            var mode   =
                (SysSecurity.CipherMode)Enum.Parse(typeof(SysSecurity.CipherMode), BlockCipherModel.Mode.ToString());
            var padding =
                (SysSecurity.PaddingMode)
                Enum.Parse(typeof(SysSecurity.PaddingMode), BlockCipherModel.Padding.ToString());

            engine.Mode    = mode;
            engine.Padding = padding;
            SysSecurity.ICryptoTransform cryptoTranform = forEncryption
                                                              ? engine.CreateEncryptor(PbkdfModel.Key, iv)
                                                              : engine.CreateDecryptor(PbkdfModel.Key, iv);
            SysSecurity.CryptoStreamMode csMode = forEncryption
                                                      ? SysSecurity.CryptoStreamMode.Write
                                                      : SysSecurity.CryptoStreamMode.Read;
            using (
                var encStream = new SysSecurity.CryptoStream(forEncryption ? ostream : istream, cryptoTranform, csMode))
            {
                if (forEncryption)
                {
                    CopyStream(istream, encStream);
                }
                else
                {
                    CopyStream(encStream, ostream);
                }
            }
        }
 /// <summary>
 /// 加密字符串
 /// </summary>
 /// <param name="encryptString"></param>
 /// <returns></returns>
 public static string Encrypt(string encryptString)
 {
     System.IO.MemoryStream mStream = null;
     System.Security.Cryptography.CryptoStream cStream = null;
     try
     {
         EncryptUtil des            = new EncryptUtil();
         byte[]      rgbKey         = Encoding.UTF8.GetBytes(des.encryptKey.Substring(0, 8));
         byte[]      rgbIV          = Encoding.UTF8.GetBytes(des.encryptIV.Substring(0, 8));
         byte[]      inputByteArray = Encoding.UTF8.GetBytes(encryptString);
         System.Security.Cryptography.DESCryptoServiceProvider dCSP = new System.Security.Cryptography.DESCryptoServiceProvider();
         mStream = new System.IO.MemoryStream();
         cStream = new System.Security.Cryptography.CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write);
         cStream.Write(inputByteArray, 0, inputByteArray.Length);
         cStream.FlushFinalBlock();
         return(Convert.ToBase64String(mStream.ToArray()));
     }
     catch (Exception)
     {
         return(encryptString);
     }
     finally
     {
         if (mStream != null)
         {
             mStream.Close(); mStream.Dispose();
         }
         if (cStream != null)
         {
             cStream.Close(); cStream.Dispose();
         }
     }
 }
Ejemplo n.º 29
0
 public static byte[] smethod_3(byte[] byte_0, string string_0)
 {
     System.Security.Cryptography.Rijndael           rijndael           = System.Security.Cryptography.Rijndael.Create();
     System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(string_0, new byte[]
     {
         38,
         220,
         255,
         0,
         173,
         237,
         122,
         238,
         197,
         254,
         7,
         175,
         77,
         8,
         34,
         60
     });
     rijndael.Key = rfc2898DeriveBytes.GetBytes(32);
     rijndael.IV  = rfc2898DeriveBytes.GetBytes(16);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(byte_0, 0, byte_0.Length);
     cryptoStream.Close();
     return(memoryStream.ToArray());
 }
Ejemplo n.º 30
0
        private static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            byte[] encrypted;
            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(
                               msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return(encrypted);
        }
Ejemplo n.º 31
0
        private void encryptFile(string inputFile, string cryptFile)
        {
            FileStream fsCrypt = null;
            CryptoStream cryptStream = null;

            try
            {
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(TPW);
                fsCrypt = new FileStream(cryptFile, FileMode.Create);
                RijndaelManaged RMCrypto = new RijndaelManaged();
                cryptStream = new CryptoStream(fsCrypt,
                                                RMCrypto.CreateEncryptor(key, key),
                                                CryptoStreamMode.Write);

                byte[] inBytes = File.ReadAllBytes(inputFile);
                cryptStream.Write(inBytes, 0, inBytes.Length);

            }
            finally
            {
                if (cryptStream != null)
                    cryptStream.Close();

                if ( fsCrypt != null )
                    fsCrypt.Close();
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 解密
        /// </summary>
        public static string AESDecrypt(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);

            // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象
            System.Security.Cryptography.ICryptoTransform decryptTransform = aes.CreateDecryptor( );
            // 解密后的输出流
            System.IO.MemoryStream decryptStream = new System.IO.MemoryStream( );

            // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接
            System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream(
                decryptStream, decryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);
            // 将一个字节序列写入当前 CryptoStream (完成解密的过程)
            decryptor.Write(encryptBytes, 0, encryptBytes.Length);
            decryptor.Close( );

            // 将解密后所得到的流转换为字符串
            byte[] decryptBytes    = decryptStream.ToArray( );
            string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);

            return(decryptedString);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// 解密字符串
        /// </summary>
        public static string Decrypt(string CypherText)
        {
            System.Security.Cryptography.DESCryptoServiceProvider key = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] bk = System.Text.Encoding.Unicode.GetBytes(CryKey);
            byte[] bs = new byte[8];
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = bk[i];
            }
            key.Key = bs;
            key.IV  = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

            byte[] bc = new byte[CypherText.Length / 2];
            for (int i = 0; i < bc.Length; i++)
            {
                try
                {
                    bc[i] = Convert.ToByte(CypherText.Substring(2 * i, 2), 16);
                }
                catch { }
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream(bc);
            System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, key.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);
            System.IO.StreamReader sr = new System.IO.StreamReader(encStream);

            string val = sr.ReadLine();

            sr.Close();
            encStream.Close();
            ms.Close();

            return(val);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// 加密
        /// </summary>
        public static string AESEncrypt(string input)
        {
            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);
        }
Ejemplo n.º 35
0
 public string Encrypt(string clearText, string EncryptionKey)
 {
     byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
     using (Aes encryptor = Aes.Create())
     {
         System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKey, new byte[]
         {
             73,
             118,
             97,
             110,
             32,
             77,
             101,
             100,
             118,
             101,
             100,
             101,
             118
         });
         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();
             }
             clearText = System.Convert.ToBase64String(ms.ToArray());
         }
     }
     return(clearText);
 }
Ejemplo n.º 36
0
        private static string CryKey = "Xky_Lq_Py_Hu_Lp_Jhj_Zxt";//密钥
        /// <summary>
        /// 加密字符串
        /// </summary>
        public static string Encrypt(string PlainText)
        {
            System.Security.Cryptography.DESCryptoServiceProvider key = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] bk = System.Text.Encoding.Unicode.GetBytes(CryKey);
            byte[] bs = new byte[8];
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = bk[i];
            }
            key.Key = bs;
            key.IV  = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

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

            System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, key.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

            System.IO.StreamWriter sw = new System.IO.StreamWriter(encStream);
            sw.WriteLine(PlainText);
            sw.Close();
            encStream.Close();

            byte[] buffer = ms.ToArray();
            ms.Close();

            string s = "";

            for (int i = 0; i < buffer.Length; i++)
            {
                s += buffer[i].ToString("X2");
            }
            return(s);
        }
Ejemplo n.º 37
0
 public static string Decrypt(string strText)
 {
     string text1;
     if (strText == String.Empty)
     {
         return strText;
     }
     byte[] buffer1;
     byte[] buffer2;
     byte[] buffer3 = GetCryptArr();
     try
     {
         buffer1 = Encoding.UTF8.GetBytes(GetCryptKey().Substring(0,8));
         DESCryptoServiceProvider provider1 =  new DESCryptoServiceProvider();
         buffer2 = Convert.FromBase64String(strText);
         MemoryStream stream2 = new MemoryStream();
         using (CryptoStream stream1 = new CryptoStream(stream2, provider1.CreateDecryptor(buffer1, buffer3), CryptoStreamMode.Write))
         {
             stream1.Write(buffer2, 0, buffer2.Length);
             stream1.FlushFinalBlock();
             text1 = Encoding.UTF8.GetString(stream2.ToArray());
         }
     }
     catch
     {
         return "Error";
     }
     return text1;
 }
Ejemplo n.º 38
0
        public static string Encrypt3DES(string a_strString, string a_strKey, string a_strIV)
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider des = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(a_strString);
            des.Key     = System.Text.Encoding.UTF8.GetBytes(a_strKey);
            des.IV      = System.Text.Encoding.UTF8.GetBytes(a_strIV);
            des.Mode    = System.Security.Cryptography.CipherMode.CBC;
            des.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            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);
            System.IO.StreamWriter swEncrypt             = new System.IO.StreamWriter(cs);
            swEncrypt.WriteLine(a_strString);
            swEncrypt.Close();

            //把内存流转换成字节数组,内存流现在已经是密文了
            byte[] bytesCipher  = ms.ToArray();
            string base64String = System.Convert.ToBase64String(bytesCipher);

            //加密流关闭
            cs.Close();
            des.Clear();
            ms.Close();


            return(base64String);
        }
Ejemplo n.º 39
0
        public static string TripleDESEncrypt(string pToEncrypt, string key = "")
        {
            string result;

            try
            {
                key = string.IsNullOrWhiteSpace(key) ? EncryptHelper.strKey : key;
                StringBuilder stringBuilder = new StringBuilder();
                TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
                tripleDESCryptoServiceProvider.Key  = System.Text.Encoding.ASCII.GetBytes(key);
                tripleDESCryptoServiceProvider.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, tripleDESCryptoServiceProvider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(pToEncrypt);
                cryptoStream.Write(bytes, 0, bytes.Length);
                cryptoStream.FlushFinalBlock();
                byte[] array = memoryStream.ToArray();
                for (int i = 0; i < array.Length; i++)
                {
                    byte b = array[i];
                    stringBuilder.AppendFormat("{0:X2}", b);
                }
                result = stringBuilder.ToString();
            }
            catch (Exception ex)
            {
                result = ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 40
0
        // ************************************** DEBUT 1 *****************************

        //public static string Encrypt(string original)
        //{
        //    MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider();
        //    byte[] passwordHash = hashMd5.ComputeHash(
        //    UnicodeEncoding.Unicode.GetBytes(clefDuCryptage));

        //    TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
        //    des.Key = passwordHash;

        //    des.Mode = CipherMode.ECB;

        //    byte[] buffer = UnicodeEncoding.Unicode.GetBytes(original);

        //    return UnicodeEncoding.Unicode.GetString(
        //    des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));

        //}

        //public static String Decrypt(String StringToDecrypt)
        //{

        //    String StringDecrypted = "";
        //    MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider();
        //    byte[] passwordHash = hashMd5.ComputeHash(
        //    UnicodeEncoding.Unicode.GetBytes(clefDuCryptage));

        //    TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
        //    des.Key = passwordHash;
        //    des.Mode = CipherMode.ECB;

        //    byte[] buffer = UnicodeEncoding.Unicode.GetBytes(StringToDecrypt);
        //    StringDecrypted = UnicodeEncoding.Unicode.GetString(
        //    des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));

        //    return StringDecrypted;
        //}

        // ************************************** FIN 1 *****************************



        // ************************************** DEBUT 2 *****************************
        //public static string Encrypt(string input, string key)
        //{
        //    byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
        //    TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
        //    tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
        //    tripleDES.Mode = CipherMode.ECB;
        //    tripleDES.Padding = PaddingMode.PKCS7;
        //    ICryptoTransform cTransform = tripleDES.CreateEncryptor();
        //    byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
        //    tripleDES.Clear();
        //    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        //}

        //public static string Decrypt(string input, string key)
        //{
        //    byte[] inputArray = Convert.FromBase64String(input);
        //    TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
        //    tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
        //    tripleDES.Mode = CipherMode.ECB;
        //    tripleDES.Padding = PaddingMode.PKCS7;
        //    ICryptoTransform cTransform = tripleDES.CreateDecryptor();
        //    byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
        //    tripleDES.Clear();
        //    return UTF8Encoding.UTF8.GetString(resultArray);
        //}
        // **************************************  FIN 2 *****************************

        /// <summary>
        /// Crypte une chaine en utilisant un chiffreur symétrique
        /// </summary>
        /// <param name="plainText">Chaine à crypter</param>
        /// <param name="pass">Mot de passe utilisé pour dériver la clé</param>
        /// <returns>Chaine cryptée</returns>
        public static string Encrypt(string plainText, string pass)
        {
            string result = string.Empty;

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.IV = new byte[8];

            System.Security.Cryptography.PasswordDeriveBytes pdb =
                new System.Security.Cryptography.PasswordDeriveBytes(pass, new byte[0]);

            des.Key = pdb.CryptDeriveKey("RC2", "SHA1", 128, new byte[8]);

            using (MemoryStream ms = new MemoryStream(plainText.Length * 2))
            {
                using (System.Security.Cryptography.CryptoStream encStream = new
                                                                             System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(),
                                                                                                                       System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
                    encStream.Write(plainBytes, 0, plainBytes.Length);
                    encStream.FlushFinalBlock();
                    byte[] encryptedBytes = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(encryptedBytes, 0, (int)ms.Length);
                    encStream.Close();
                    ms.Close();
                    result = Convert.ToBase64String(encryptedBytes);
                }
            }
            return(result);
        }
 /// <summary>
 /// DES加密
 /// </summary>
 /// <param name="str"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static string DESEncrypt(string str, string key)
 {
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     //把字符串放到byte数组中 
     byte[] inputByteArray = Encoding.Default.GetBytes(str);
     //建立加密对象的密钥和偏移量  
     //原文使用ASCIIEncoding.ASCII方法的GetBytes方法  
     //使得输入密码必须输入英文文本  
     des.Key = ASCIIEncoding.ASCII.GetBytes(key);
     des.IV = ASCIIEncoding.ASCII.GetBytes(key);
     MemoryStream ms = new MemoryStream();
     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     //Write  the  byte  array  into  the  crypto  stream  
     //(It  will  end  up  in  the  memory  stream)  
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     //Get  the  data  back  from  the  memory  stream,  and  into  a  string  
     StringBuilder ret = new StringBuilder();
     foreach (byte b in ms.ToArray())
     {
         //Format  as  hex  
         ret.AppendFormat("{0:X2}", b);
     }
     ret.ToString();
     return ret.ToString();
 }
Ejemplo n.º 42
0
        public static string TripleDESDecrypt(string pToDecrypt, string key = "")
        {
            string result;

            try
            {
                key = (string.IsNullOrWhiteSpace(key) ? EncryptHelper.strKey : key);
                byte[] array = new byte[pToDecrypt.Length / 2];
                for (int i = 0; i < pToDecrypt.Length / 2; i++)
                {
                    int num = System.Convert.ToInt32(pToDecrypt.Substring(i * 2, 2), 16);
                    array[i] = (byte)num;
                }
                TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                tripleDESCryptoServiceProvider.Key  = System.Text.Encoding.ASCII.GetBytes(key);
                tripleDESCryptoServiceProvider.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, tripleDESCryptoServiceProvider.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cryptoStream.Write(array, 0, array.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                memoryStream.Close();
                result = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                result = ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 43
0
        public static string Encrypt(string plainText)
        {
            var registryKey =
                Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\10.0\PbsEncryptionKey");
            var password = (string)registryKey.GetValue("Key");
            var passwordDerivedBytes = new PasswordDeriveBytes(password, _salt);
            var plainTextBytes = Encoding.Unicode.GetBytes(plainText);

            using (var memoryStream = new MemoryStream())
            {
                using (Rijndael rijndael = Rijndael.Create())
                {
                    using (
                        ICryptoTransform cryptoTransform = rijndael.CreateEncryptor(passwordDerivedBytes.GetBytes(32), rgbIV: passwordDerivedBytes.GetBytes(16)))
                    {
                        using (
                            var cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
                                CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            return Convert.ToBase64String(memoryStream.ToArray());
                        }
                    }
                }
            }
        }
Ejemplo n.º 44
0
        public static string Decrypt(string cipherText)
        {
            //Get the plain text in a byte array
            System.Byte[] ByteText = System.Convert.FromBase64String(cipherText);

            System.IO.MemoryStream EncStream = new System.IO.MemoryStream(ByteText, 0, ByteText.Length);

            //Get the binary format of the hash key
            System.Byte[] HashKey = Crypter.FormatKey(Crypter.encrypKey);
            System.Byte[] IVector = Crypter.FormatInitializationVector();

            Crypter.encryptionProvider.Key = HashKey;
            Crypter.encryptionProvider.IV  = IVector;

            System.Security.Cryptography.ICryptoTransform Encrypter = Crypter.encryptionProvider.CreateDecryptor();

            //Create a Stream for the transform
            System.Security.Cryptography.CryptoStream Stream = new System.Security.Cryptography.CryptoStream(EncStream, Encrypter, System.Security.Cryptography.CryptoStreamMode.Read);

            System.IO.StreamReader PlainText = null;

            try
            {
                PlainText = new System.IO.StreamReader(Stream);

                return(PlainText.ReadToEnd());
            }
            finally
            {
                PlainText.Close();
                Stream.Close();
            }
        }
Ejemplo n.º 45
0
        public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("Key");

            string plaintext = null;

            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return plaintext;
        }
Ejemplo n.º 46
0
        private static string DESEncrypt(string MainKey, string strPlain)
        {
            string g_strDESKey = ComputeMD5HashHEX(MainKey + g_strDESIV).Substring(0, 8);
            string p_strReturn = string.Empty;

            try
            {
                string strDESKey   = g_strDESKey;
                string strDESIV    = g_strDESIV;
                byte[] bytesDESKey = System.Text.ASCIIEncoding.ASCII.GetBytes(strDESKey);
                byte[] bytesDESIV  = System.Text.ASCIIEncoding.ASCII.GetBytes(strDESIV);
                System.Security.Cryptography.DESCryptoServiceProvider desEncrypt = new System.Security.Cryptography.DESCryptoServiceProvider();
                System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, desEncrypt.CreateEncryptor(bytesDESKey, bytesDESIV), System.Security.Cryptography.CryptoStreamMode.Write);
                System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt);
                swEncrypt.WriteLine(strPlain);
                swEncrypt.Close();
                csEncrypt.Close();
                byte[] bytesCipher = msEncrypt.ToArray();
                msEncrypt.Close();
                p_strReturn = ConvertByteArrayToHex(bytesCipher);
            }
            catch (System.Exception) { }
            return(p_strReturn);
        }
Ejemplo n.º 47
0
    internal static void Decrypt(string fileIn, string fileOut)
    {
        System.IO.FileStream fsIn  = new System.IO.FileStream(fileIn, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        System.IO.FileStream fsOut = new System.IO.FileStream(fileOut, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(Password,
                                                                                                                    new byte[] { 0x49, 0x49, 0x35, 0x6e, 0x76, 0x4d,
                                                                                                                                 0x65, 0x64, 0x76, 0x76, 0x64, 0x65, 0x76 });
        System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV  = pdb.GetBytes(16);

        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(fsOut, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

        int bufferLen = 4096;

        byte[] buffer = new byte[bufferLen];
        int    bytesRead;

        do
        {
            // read a chunk of data from the input file
            bytesRead = fsIn.Read(buffer, 0, bufferLen);
            // Decrypt it
            cs.Write(buffer, 0, bytesRead);
        } while (bytesRead != 0);
        cs.Close();
        fsIn.Close();
    }
Ejemplo n.º 48
0
                /// <summary>
                /// Método para encriptar em AES
                /// </summary>
                /// <param name="plaintext"></param>
                /// <param name="text"></param>
                /// <returns></returns>
                public static byte[] Encrypt(byte[] plaintext, string text)
                {
                    /*
                     * Block Length: 128bit
                     * Block Mode: ECB
                     * Data Padding: Padded by bytes which Asc() equal for number of padded bytes (done automagically)
                     * Key Padding: 0x00 padded to multiple of 16 bytes
                     * IV: None
                     */
                    byte[] key = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
                    System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
                    AES.BlockSize = 128;
                    AES.Mode      = System.Security.Cryptography.CipherMode.ECB;
                    AES.Key       = key;

                    System.Security.Cryptography.ICryptoTransform encryptor = AES.CreateEncryptor();
                    MemoryStream mem = new MemoryStream();

                    System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(mem, encryptor,
                                                                                                                          System.Security.Cryptography.CryptoStreamMode.Write);

                    cryptStream.Write(plaintext, 0, plaintext.Length);
                    cryptStream.FlushFinalBlock();

                    byte[] cypher = mem.ToArray();

                    cryptStream.Close();
                    cryptStream = null;
                    encryptor.Dispose();
                    AES = null;

                    return(cypher);
                }
Ejemplo n.º 49
0
        public static string DecryptString(string str)
        {
            byte[] encrypted = encoding.GetBytes(str);
            string decrypted;

            AesCryptoServiceProvider provider = createAesProvider();

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = provider.CreateDecryptor(provider.Key, null); // null IV, because ECB mode

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(encrypted))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        decrypted = srDecrypt.ReadToEnd();
                    }
                }
            }
            return decrypted;
        }
Ejemplo n.º 50
0
        public static string Encrypt(string value, byte[] key, byte[] iv)
        {
            using var aes = Crypto.Aes.Create();
            aes.Key       = key;
            if (iv != null)
            {
                aes.IV = iv;
            }
            ReadOnlySpan <byte> decodedValue = Encoding.UTF8.GetBytes(value);

            if (aes == null)
            {
                throw new ArgumentException($"AES Parameter cannot be null.", nameof(aes));
            }
            using var transform = aes.CreateEncryptor(aes.Key, aes.IV);
            using var result    = new MemoryStream();
            using (var aesStream = new Crypto.CryptoStream(result, transform, Crypto.CryptoStreamMode.Write))
            {
                using var original = new MemoryStream(decodedValue.ToArray());
                original.CopyTo(aesStream);
            }

            var encrypted = result.ToArray();
            var combined  = new byte[aes.IV.Length + encrypted.Length];

            Array.ConstrainedCopy(aes.IV, 0, combined, 0, aes.IV.Length);
            Array.ConstrainedCopy(encrypted, 0, combined, aes.IV.Length, encrypted.Length);

            return(Convert.ToBase64String(combined));
        }
Ejemplo n.º 51
0
        public static string Decrypt(string strStringDecrypt, string strEncryptionKey)
        {
            byte[] inputByteArray = new byte[strStringDecrypt.Length];

            try
            {
                key = Encoding.UTF8.GetBytes(strEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                inputByteArray = Convert.FromBase64String(strStringDecrypt.Replace(" ", "+"));

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

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

                Encoding encoding = Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception eX)
            {

                throw eX;
            }
        }
        /// <summary>
        /// Encrypt/Decrypt with Read method. Recommended for decrypting only.
        /// </summary>
        /// <param name="cryptor"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private byte[] CipherStreamRead(System.Security.Cryptography.ICryptoTransform cryptor, byte[] input)
        {
            WriteLog("--- Cipher Stream:");
            WriteLog("InputBlockSize: " + cryptor.InputBlockSize.ToString());
            WriteLog("OutputBlockSize: " + cryptor.OutputBlockSize.ToString());
            byte[] inputBuffer  = new byte[input.Length];
            byte[] outputBuffer = new byte[input.Length];
            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the input bytes.
            var stream = new System.IO.MemoryStream(inputBuffer);
            // Create a CryptoStream through which we are going to be processing our data.
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, System.Security.Cryptography.CryptoStreamMode.Read);
            // Start the crypting process.
            int length = cryptoStream.Read(outputBuffer, 0, outputBuffer.Length);

            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            System.Array.Resize(ref outputBuffer, length);
            // Close both streams.
            stream.Close();
            // cryptoStream.Close();
            WriteEnc(inputBuffer, outputBuffer);
            return(outputBuffer);
        }
        public msgMaid cooking(byte[] otama)
        {
            //メイドオブジェクト
            msgMaid m = new msgMaid();

            //DESC
            TripleDESCryptoServiceProvider frill = new TripleDESCryptoServiceProvider();

            // Triple DES のサービス プロバイダを生成します
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            //取得
            m.houshinokokoro = frill.Key;
            m.zettaifukujyu = frill.IV;

            // source 配列から cryptData 配列へ変換
            // 文字列を byte 配列に変換します
            //byte[] source = Encoding.Unicode.GetBytes(cachusha);

            // 入出力用のストリームを生成します
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(m.houshinokokoro, m.zettaifukujyu), CryptoStreamMode.Write))
                {
                    // ストリームに暗号化するデータを書き込みます
                    cs.Write(otama, 0, otama.Length);
                }

                // 暗号化されたデータを byte 配列で取得します
                m.zenryokushugo = ms.ToArray();
            }

            // byte 配列を文字列に変換して表示します
            return m;
        }
Ejemplo n.º 54
0
        public static string Decode(string str, string key)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            byte[] buffer = new byte[str.Length / 2];

            for (int i = 0; i < (str.Length / 2); i++)
            {

                int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);

                buffer[i] = (byte)num2;

            }

            MemoryStream stream = new MemoryStream();

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);

            stream2.Write(buffer, 0, buffer.Length);

            stream2.FlushFinalBlock();

            stream.Close();

            return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray());
        }
Ejemplo n.º 55
0
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="pToDecrypt">需要解密的字符串</param>
        /// <param name="sKey">密匙</param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string pToDecrypt, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }

                //建立加密对象的密钥和偏移量,此值重要,不能修改
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {

            }
            return "";
        }
Ejemplo n.º 56
0
    public static byte[] InternalEncrypt(byte[] data, out byte[] key, out byte[] IV)
    {
        byte[] bytes = null;
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.Security.Cryptography.ICryptoTransform trans = GetEncServiceProvider(out key, out IV);
        System.Security.Cryptography.CryptoStream     cs    = new System.Security.Cryptography.CryptoStream(ms, trans, System.Security.Cryptography.CryptoStreamMode.Write);

        try
        {
            cs.Write(data, 0, data.Length);

            if (cs != null)
            {
                cs.FlushFinalBlock();
                cs.Close();
            }
            bytes = ms.ToArray();
        }
        finally
        {
            if (cs != null)
            {
                cs.Close();
            }
            if (ms != null)
            {
                ms.Close();
            }
        }

        return(bytes);
    }
        public string mDecryptURLEncode(string EncryptedText)
        {
            string DecryptedText = "";

            System.Security.Cryptography.ICryptoTransform ssd = rc2.CreateDecryptor();

            string sEncrypt = HttpUtility.UrlDecode(EncryptedText);

            byte[] cipherBytes = Convert.FromBase64String(sEncrypt);
            byte[] initialText = null;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(cipherBytes))
            {
                using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, ssd, System.Security.Cryptography.CryptoStreamMode.Read))
                {
                    int iCount = opGetArrLength(cipherBytes);
                    initialText = new Byte[cipherBytes.Length];
                    cs.Read(initialText, 0, initialText.Length);
                    cs.Close();
                    cs.Dispose();
                }
                ms.Close();
                ms.Dispose();
            }
            DecryptedText = System.Text.UTF8Encoding.UTF8.GetString(initialText);
            return(DecryptedText = DecryptedText.Replace("\0", ""));
        }
Ejemplo n.º 58
0
            public static string Decrypt(string strDecrypt, bool retStrOriginal)
            {
                string result = string.Empty;

                System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
                try
                {
                    byte[] bytes  = System.Text.Encoding.UTF8.GetBytes(Secret.AES.Key);
                    byte[] bytes2 = System.Text.Encoding.UTF8.GetBytes(Secret.AES.IV);
                    byte[] array  = Convert.FromBase64String(strDecrypt);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateDecryptor(bytes, bytes2), System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(array, 0, array.Length);
                            cryptoStream.FlushFinalBlock();
                            result = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
                        }
                    }
                }
                catch
                {
                    if (retStrOriginal)
                    {
                        result = strDecrypt;
                    }
                    else
                    {
                        result = string.Empty;
                    }
                }
                rijndael.Clear();
                return(result);
            }
        public static string Decrypt(string TextToBeDecrypted)
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            string Password = "******";
            string DecryptedData;

            try
            {
                byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted);

                byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
                //Making of the key for decryption
                PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
                //Creates a symmetric Rijndael decryptor object.
                ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

                MemoryStream memoryStream = new MemoryStream(EncryptedData);
                //Defines the cryptographics stream for decryption.THe stream contains decrpted data
                CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

                byte[] PlainText = new byte[EncryptedData.Length];
                int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
                memoryStream.Close();
                cryptoStream.Close();

                //Converting to string
                DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
            }
            catch
            {
                DecryptedData = TextToBeDecrypted;
            }
            return DecryptedData;
        }
Ejemplo n.º 60
0
            public static string Encrypt(string Text, string sKey)
            {
                string result;

                if (string.IsNullOrEmpty(Text))
                {
                    result = "";
                }
                else
                {
                    string text = SecretCommon.Md5Hex.Encrypt(sKey, false);
                    System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
                    byte[] bytes = System.Text.Encoding.Default.GetBytes(Text);
                    dESCryptoServiceProvider.Key = System.Text.Encoding.ASCII.GetBytes(text.Substring(8, 8));
                    dESCryptoServiceProvider.IV  = System.Text.Encoding.ASCII.GetBytes(text.Substring(0, 8));
                    MemoryStream memoryStream = new MemoryStream();
                    System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                    cryptoStream.Write(bytes, 0, bytes.Length);
                    cryptoStream.FlushFinalBlock();
                    System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
                    byte[] array = memoryStream.ToArray();
                    for (int i = 0; i < array.Length; i++)
                    {
                        byte b = array[i];
                        stringBuilder.AppendFormat("{0:X2}", b);
                    }
                    result = stringBuilder.ToString();
                }
                return(result);
            }