Example #1
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;
        }
Example #2
1
 public string Decrypt(string strEncryptedText)
 {
     if (strEncryptedText == null || strEncryptedText.Equals(""))
         return strEncryptedText;
     string strDecryptedText = null;
     RijndaelManaged rijndael = new RijndaelManaged();
     ICryptoTransform decryptor = rijndael.CreateDecryptor(Key, IV);
     byte[] byteEncryptedText = Convert.FromBase64String(strEncryptedText);
     MemoryStream memStream = new MemoryStream(byteEncryptedText);
     CryptoStream decryptStream = null;
     try
     {
         decryptStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read);
         byte[] byteDecryptedText = new byte[byteEncryptedText.Length];
         int decryptedByteCount = decryptStream.Read(byteDecryptedText, 0, byteDecryptedText.Length);
         strDecryptedText = Encoding.UTF8.GetString(byteDecryptedText, 0, decryptedByteCount);
     }
     finally
     {
         if (rijndael != null) rijndael.Clear();
         if (decryptor != null) decryptor.Dispose();
         if (memStream != null) memStream.Close();
         if (decryptStream != null) decryptStream.Close();
     }
     if (UseSalt)
         strDecryptedText = strDecryptedText.Substring(8);
     return strDecryptedText;
 }
Example #3
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";
            }
        }
        /// <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();
            }
        }
       public static void DecryptFile(string inputFile, string outputFile, string skey)
       {
           RijndaelManaged aes = new RijndaelManaged();

           try
           {
               byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);

               using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
               {
                   using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
                   {
                       using (CryptoStream cs = new CryptoStream(fsCrypt, aes.CreateDecryptor(key, key), CryptoStreamMode.Read))
                       {
                           int data;

                           while ((data = cs.ReadByte()) != -1)
                           {
                               fsOut.WriteByte((byte)data);
                           }

                           aes.Clear();
                       }
                   }
               }

           }
           catch (Exception ex)
           {
               Console.WriteLine(ex.Message);
               aes.Clear();
           }
       }
Example #6
0
        public static string DecryptData(string strData, string key)
        {
            if (string.IsNullOrEmpty(strData))
                return "";

            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(_initVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(_salt);
            byte[] CipherTextBytes = Convert.FromBase64String(strData);
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(key, SaltValueBytes, _hashAlgo, _passIter);
            byte[] KeyBytes = DerivedPassword.GetBytes(_keySize / 8);
            RijndaelManaged SymmetricKey = new RijndaelManaged();
            SymmetricKey.Mode = CipherMode.CBC;
            byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
            int ByteCount = 0;
            using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                    {
                        ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
        }
 public static string Decrypt(this byte[] data, byte[] key)
 {
     if (data == null) throw new ArgumentNullException("data");
     if (key == null || key.Length != 32) throw new ArgumentException("Key must have 32 length", "key");
     string result;
     using (var c = new RijndaelManaged())
     {
         c.Key = key;
         using (var ms = new MemoryStream())
         {
             int ReadPos = 0;
             byte[] IV = new byte[c.IV.Length];
             Array.Copy(data, IV, IV.Length);
             c.IV = IV;
             ReadPos += c.IV.Length;
             using (var cs = new CryptoStream(ms, c.CreateDecryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(data, ReadPos, data.Length - ReadPos);
                 cs.FlushFinalBlock();
             }
             result = Encoding.Unicode.GetString(ms.ToArray());
         }
         c.Clear();
     }
     return result;
 }
        public bool decriptarAES(out string decriptedData)
        {
            try
            {
                RijndaelManaged aesAlg = new RijndaelManaged();
                aesAlg.Key = _key;
                aesAlg.IV = _initializatorVector;

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

                MemoryStream msDecrypt = new MemoryStream(_cipherText);
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
                StreamReader srDecrypt = new StreamReader(csDecrypt);

                decriptedData = srDecrypt.ReadToEnd();

                srDecrypt.Close();
                csDecrypt.Close();
                msDecrypt.Close();

                aesAlg.Clear();

                return true;
            }
            catch
            {
                decriptedData = null;
                return false;
            }
        }
 /// <summary>
 /// Decrypt input encryptedBytes
 /// </summary>
 /// <param name="encryptedBytes">Encrypted byte array</param>
 /// <param name="Key">Secret key</param>
 /// <param name="IV">Initialize vector</param>
 /// <returns>Decrypt text</returns>
 public static string RijndaelDecrypt(byte[] encryptedBytes, byte[] Key, byte[] IV)
 {
     RijndaelManaged aesAlg = null;
     string plaintext = null;
     try
     {
         aesAlg = new RijndaelManaged();
         aesAlg.Key = Key;
         aesAlg.IV = IV;
         ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
         using (MemoryStream msDecrypt = new MemoryStream(encryptedBytes))
         {
             using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
             {
                 using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                     plaintext = srDecrypt.ReadToEnd();
             }
         }
     }
     finally
     {
         if (aesAlg != null) aesAlg.Clear();
     }
     return plaintext;
 }
Example #10
0
 /// <summary>
 /// Encrypts a string
 /// </summary>
 /// <param name="PlainText">Text to be encrypted</param>
 /// <param name="Password">Password to encrypt with</param>
 /// <param name="Salt">Salt to encrypt with</param>
 /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
 /// <param name="PasswordIterations">Number of iterations to do</param>
 /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
 /// <param name="KeySize">Can be 128, 192, or 256</param>
 /// <returns>An encrypted string</returns>
 public static string Encrypt(string PlainText, string Password,
     string Salt = "Kosher", string HashAlgorithm = "SHA1",
     int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
     int KeySize = 256)
 {
     if (string.IsNullOrEmpty(PlainText))
         return "";
     byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
     byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
     byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
     PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
     byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
     RijndaelManaged SymmetricKey = new RijndaelManaged();
     SymmetricKey.Mode = CipherMode.CBC;
     byte[] CipherTextBytes = null;
     using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
     {
         using (MemoryStream MemStream = new MemoryStream())
         {
             using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
             {
                 CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                 CryptoStream.FlushFinalBlock();
                 CipherTextBytes = MemStream.ToArray();
                 MemStream.Close();
                 CryptoStream.Close();
             }
         }
     }
     SymmetricKey.Clear();
     return Convert.ToBase64String(CipherTextBytes);
 }
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="cipherText">Text to be decrypted</param>
        /// <param name="password">Password to decrypt with</param>
        /// <param name="salt">Salt to decrypt with</param>
        /// <param name="hashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="passwordIterations">Number of iterations to do. The number of times the algorithm is run on the text. </param>
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="keySize">Can be 128, 192, or 256</param>
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string cipherText, string password, string salt = "69ad1bfbd6605f3f6a3011460cdfb9db7757e0f9", string hashAlgorithm = "SHA1", int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY", int keySize = 256)
        {
            if (string.IsNullOrEmpty(cipherText))
                return "";

            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
            var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
            var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC};
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int byteCount;

            using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
            symmetricKey.Clear();

            return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
        }
Example #12
0
        public static string AESDecrypt(string decryptString, string key)
        {
            byte[] inputData = new byte[decryptString.Length / 2]; Convert.FromBase64String(decryptString);
            int arrayIndex = 0;
            foreach (byte b in inputData)
            {
                inputData[arrayIndex] = (byte)Convert.ToInt32(decryptString.Substring(arrayIndex * 2, 2), 16);
                arrayIndex = arrayIndex + 1;
            }

            RijndaelManaged rijndaelManager = new RijndaelManaged();
            rijndaelManager.Key = Encoding.UTF8.GetBytes(key.PadRight(32, ' ').Substring(0, 32));
            rijndaelManager.IV = AESIV;
            rijndaelManager.Mode = CipherMode.CBC;
            rijndaelManager.Padding = PaddingMode.PKCS7;
            ICryptoTransform rijndaelDecryptor = rijndaelManager.CreateDecryptor();

            try
            {
                byte[] decryptedData = rijndaelDecryptor.TransformFinalBlock(inputData, 0, inputData.Length);
                return Encoding.UTF8.GetString(decryptedData);
            }
            catch
            {
                return string.Empty;
            }
            finally
            {
                rijndaelDecryptor.Dispose();
                rijndaelManager.Clear();
            }
        }
Example #13
0
        public static String read(byte[] cypher, string KeyString, string IVString)
        {
            var sRet = "";

            var encoding = new UTF8Encoding();
            var Key = encoding.GetBytes(KeyString);
            var IV = encoding.GetBytes(IVString);

            using (var rj = new RijndaelManaged())
            {
                try
                {
                    rj.Padding = PaddingMode.PKCS7;
                    rj.Mode = CipherMode.CBC;
                    rj.KeySize = 256;
                    rj.BlockSize = 256;
                    rj.Key = Key;
                    rj.IV = IV;
                    var ms = new MemoryStream(cypher);

                    using (var cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                    {
                        using (var sr = new StreamReader(cs))
                        {
                            sRet = sr.ReadLine();
                        }
                    }
                }
                finally
                {
                    rj.Clear();
                }
            }
            return sRet;
        }
Example #14
0
		public static string DecryptData(string strData, string key)
		{
			if (string.IsNullOrEmpty(strData))
				return "";

			byte[] initialVectorBytes = Encoding.ASCII.GetBytes(InitVector);
			byte[] saltValueBytes = Encoding.ASCII.GetBytes(Salt);
			byte[] cipherTextBytes = Convert.FromBase64String(strData);
			var derivedPassword = new PasswordDeriveBytes(key, saltValueBytes, HashAlgo, PassIter);
#pragma warning disable 612,618
			byte[] keyBytes = derivedPassword.GetBytes(KeySize/8);
#pragma warning restore 612,618
			var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC};
			var plainTextBytes = new byte[cipherTextBytes.Length];
			int byteCount;
			using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
			{
				using (var memStream = new MemoryStream(cipherTextBytes))
				{
					using (var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
					{
						byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
						memStream.Close();
						cryptoStream.Close();
					}
				}
			}
			symmetricKey.Clear();
			return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
		}
        static void Main(string[] args)
        {
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(args[0]);
            System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged();
            rijndaelManaged.Key = bytes;

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true;
            xmlDocument.Load("needfiles");

            XmlElement    xmlElement    = xmlDocument.GetElementsByTagName("EncryptedData")[0] as XmlElement;
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.LoadXml(xmlElement);
            EncryptedXml encryptedXml = new EncryptedXml();

            byte[] decryptedData = encryptedXml.DecryptData(encryptedData, rijndaelManaged);
            encryptedXml.ReplaceData(xmlElement, decryptedData);


            if (rijndaelManaged != null)
            {
                rijndaelManaged.Clear();
            }
            Console.WriteLine(xmlDocument.OuterXml);
        }
Example #16
0
		public static string EncryptData(string strData, string key)
		{
			if (string.IsNullOrEmpty(strData))
				return "";

			byte[] initialVectorBytes = Encoding.ASCII.GetBytes(InitVector);
			byte[] saltValueBytes = Encoding.ASCII.GetBytes(Salt);
			byte[] plainTextBytes = Encoding.UTF8.GetBytes(strData);
			var derivedPassword = new PasswordDeriveBytes(key, saltValueBytes, HashAlgo, PassIter);
#pragma warning disable 612,618
			byte[] keyBytes = derivedPassword.GetBytes(KeySize/8);
#pragma warning restore 612,618
			var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC};
			byte[] cipherTextBytes;
			using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes))
			{
				using (var memStream = new MemoryStream())
				{
					using (var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
					{
						cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
						cryptoStream.FlushFinalBlock();
						cipherTextBytes = memStream.ToArray();
						memStream.Close();
						cryptoStream.Close();
					}
				}
			}
			symmetricKey.Clear();
			return Convert.ToBase64String(cipherTextBytes);
		}
Example #17
0
 /// <summary>
 /// Encrypts a string
 /// </summary>
 /// <param name="plainText">Text to be encrypted</param>
 /// <param name="password">Password to encrypt with</param>
 /// <param name="salt">Salt to encrypt with</param>
 /// <param name="passwordIterations">Number of iterations to do</param>
 /// <param name="initialVector">Needs to be 16 ASCII characters long</param>
 /// <param name="keySize">Can be 128, 192, or 256</param>
 /// <returns>An encrypted string</returns>
 public static string Encrypt(string plainText, string password, string salt, int passwordIterations = 1000, string initialVector = "OFRna73m*aze01xY", int keySize = 256)
 {
     if (string.IsNullOrEmpty(plainText))
         return "";
     var initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
     var saltValueBytes = Encoding.ASCII.GetBytes(salt);
     var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     var derivedPassword = new Rfc2898DeriveBytes(password, saltValueBytes, passwordIterations);
     var keyBytes = derivedPassword.GetBytes(keySize / 8);
     var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC};
     byte[] cipherTextBytes = null;
     using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes))
     {
         using (var memStream = new MemoryStream())
         {
             using (var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
             {
                 cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                 cryptoStream.FlushFinalBlock();
                 cipherTextBytes = memStream.ToArray();
                 memStream.Close();
                 cryptoStream.Close();
             }
         }
     }
     symmetricKey.Clear();
     return Convert.ToBase64String(cipherTextBytes);
 }
Example #18
0
        public static string EncryptData(string strData, string key)
        {
            if (string.IsNullOrEmpty(strData))
                return "";

            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(_initVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(_salt);
            byte[] PlainTextBytes = Encoding.UTF8.GetBytes(strData);
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(key, SaltValueBytes, _hashAlgo, _passIter);
            byte[] KeyBytes = DerivedPassword.GetBytes(_keySize / 8);
            RijndaelManaged SymmetricKey = new RijndaelManaged();
            SymmetricKey.Mode = CipherMode.CBC;
            byte[] CipherTextBytes = null;
            using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream())
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                    {
                        CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                        CryptoStream.FlushFinalBlock();
                        CipherTextBytes = MemStream.ToArray();
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return Convert.ToBase64String(CipherTextBytes);
        }
Example #19
0
        /// <summary>
        /// Decrypts input string from Rijndael (AES) algorithm with CBC blocking and PKCS7 padding.
        /// </summary>
        /// <param name="inputBytes">Encrypted binary array to decrypt</param>
        /// <param name="password"></param>
        /// <returns>string of Decrypted data</returns>
        /// <remarks>The key and IV are the same, and use strEncryptionPassword.</remarks>
        private static string AesDecrypt(byte[] inputBytes, string password)
        {
            var AES = new RijndaelManaged
                          {
                              Padding = PaddingMode.PKCS7,
                              Mode = CipherMode.CBC,
                              KeySize = 128,
                              BlockSize = 128
                          };

            byte[] keyAndIvBytes = Encoding.UTF8.GetBytes(password);
            //create streams and decryptor object
            try
            {
                using (var memoryStream = new MemoryStream(inputBytes))
                {
                    using (
                        var cryptoStream = new CryptoStream(memoryStream,
                                                            AES.CreateDecryptor(keyAndIvBytes, keyAndIvBytes),
                                                            CryptoStreamMode.Read))
                    {
                        var outputBytes = new byte[inputBytes.Length + 1];
                        cryptoStream.Read(outputBytes, 0, outputBytes.Length);
                        return Encoding.UTF8.GetString(outputBytes);
                    }
                }
            }
            finally
            {
                AES.Clear();
            }
        }
Example #20
0
        public static string AESDecryptBase64(string decryptString, string key)
        {
            byte[] inputData = Convert.FromBase64String(decryptString);

            RijndaelManaged rijndaelManager = new RijndaelManaged();
            rijndaelManager.Key = Encoding.UTF8.GetBytes(key.PadRight(32, ' ').Substring(0, 32));
            rijndaelManager.IV = AESIV;
            rijndaelManager.Mode = CipherMode.CBC;
            rijndaelManager.Padding = PaddingMode.PKCS7;
            ICryptoTransform rijndaelDecryptor = rijndaelManager.CreateDecryptor();

            try
            {
                byte[] decryptedData = rijndaelDecryptor.TransformFinalBlock(inputData, 0, inputData.Length);
                return Encoding.UTF8.GetString(decryptedData);
            }
            catch
            {
                return string.Empty;
            }
            finally
            {
                rijndaelDecryptor.Dispose();
                rijndaelManager.Clear();
            }
        }
        private static object ReadObjectFromXml(string path)
        {
            try
            {
                object ob;
                using (Stream fs = new FileStream(path, FileMode.Open))
                {
                    var rm = new RijndaelManaged();
                    rm.BlockSize = rm.KeySize;
                    var secretKey = new PasswordDeriveBytes(Encoding.Unicode.GetBytes(Salt),
                                                            Encoding.ASCII.GetBytes(Salt));
                    // ReSharper disable once CSharpWarnings::CS0618
                    rm.Key = secretKey.GetBytes(rm.KeySize/8);
                    rm.IV = rm.Key;
                    var desEncrypt = rm.CreateDecryptor();

                    using (var cs = new CryptoStream(fs, desEncrypt, CryptoStreamMode.Read))
                    {
                        var xmlser = new XmlSerializer(typeof (Data));
                        ob = xmlser.Deserialize(cs);
                    }
                    rm.Clear();
                    desEncrypt.Dispose();
                }
                return ob;
            }
            catch (Exception ex)
            {
                Logger.Write(ex.Message);
                return null;
            }
        }
Example #22
0
        public static byte[] Decrypt(byte[] cipherBytes)
        {
            RijndaelManaged Crypto = null;
            MemoryStream ms = null;
            ICryptoTransform Decryptor = null;
            CryptoStream cryptoStream = null;

            Byte[] plainTextBytes = new byte[cipherBytes.Length];

            using (Crypto = new RijndaelManaged())
            {
                Crypto.Key = aesKey;
                Crypto.IV = aesIV;
                ms = new MemoryStream(cipherBytes);
                Decryptor = Crypto.CreateDecryptor(Crypto.Key, Crypto.IV);
                cryptoStream = new CryptoStream(ms, Decryptor, CryptoStreamMode.Read);
                cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                if (Crypto != null)
                    Crypto.Clear();

                ms.Flush();
                ms.Close();

            }

            int i = plainTextBytes.Length - 1;
            while (plainTextBytes[i] == 0)
                --i;

            byte[] finalResule = new byte[i + 1];
            Array.Copy(plainTextBytes, finalResule, i + 1);

            return finalResule;
        }
Example #23
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="plainText">要加密的字串</param>
        /// <returns>加密后的字串</returns>
        public static string EncryptStringAES(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");

            string outStr = null;
            RijndaelManaged aesAlg = null;

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(_secret, _salt);
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return outStr;
        } 
Example #24
0
        public static byte[] Encrypt(byte[] data, byte[] key)
        {
            RijndaelManaged rijndaelManaged = new RijndaelManaged();
            rijndaelManaged.Mode = CipherMode.CBC;
            rijndaelManaged.Padding = PaddingMode.PKCS7;
            rijndaelManaged.KeySize = 256;
            rijndaelManaged.BlockSize = 256;
            rijndaelManaged.Key = key;
            rijndaelManaged.IV = key;

            ICryptoTransform Encryptor = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);

            MemoryStream MemStream = new MemoryStream();
            CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write);
            CryptoStream.Write(data, 0, data.Length);
            CryptoStream.FlushFinalBlock();

            byte[] returnValue = MemStream.ToArray();

            MemStream.Close();
            CryptoStream.Close();
            rijndaelManaged.Clear();

            return returnValue;
        }
Example #25
0
		/// <summary>
		/// Encrypts a string
		/// </summary>
		/// <param name="PlainText">Text to be encrypted</param>
		/// <param name="Password">Password to encrypt with</param>
		/// <param name="Salt">Salt to encrypt with</param>
		/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
		/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
		/// <param name="PasswordIterations">Number of iterations to do</param>
		/// <param name="KeySize">Can be 128, 192, or 256</param>
		/// <returns>An encrypted bytes</returns>
		public static byte[] Encrypt(byte[] PlainText, byte[] Password, byte[] InitialVector,
			byte[] Salt)
		{
			PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, Salt, HASH_ALGORITHM, PASSWORDITERATIONS);
			byte[] KeyBytes = DerivedPassword.GetBytes(KEY_SIZE / 8);
			RijndaelManaged SymmetricKey = new RijndaelManaged();
			SymmetricKey.Mode = CipherMode.CBC;
			byte[] CipherTextBytes = null;

			using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVector))
			{
				using (MemoryStream MemStream = new MemoryStream())
				{
					using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
					{
						CryptoStream.Write(PlainText, 0, PlainText.Length);
						CryptoStream.FlushFinalBlock();
						CipherTextBytes = MemStream.ToArray();
						MemStream.Close();
						CryptoStream.Close();
					}
				}
			}

			SymmetricKey.Clear();
			return CipherTextBytes;
			//return Encoding.UTF8.GetBytes(Convert.ToBase64String(CipherTextBytes));
		}
Example #26
0
        public static string Encrypt(string toEncrypt, string key)
        {
            string result = string.Empty;
            if (string.IsNullOrEmpty(toEncrypt))
            {
                return result;
            }
            try
            {
                byte[] keyArray = ToByte(key);
                byte[] toEncryptArray = Encoding.Default.GetBytes(toEncrypt);
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = rDel.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                rDel.Clear();
                result = ToText(resultArray);
            }
            catch
            {

            }
            return result;
        }
Example #27
0
        public static string Decrypt(string cipher)
        {
            if (string.IsNullOrEmpty(cipher))
                throw new ArgumentNullException("cipher");

            RijndaelManaged alg = null;
            string plaintext = null;

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(shared, _salt);
                byte[] bytes = Convert.FromBase64String(cipher);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    alg = new RijndaelManaged();
                    alg.Key = key.GetBytes(alg.KeySize / 8);
                    alg.IV = ReadByteArray(msDecrypt);
                    ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            finally
            {
                if (alg != null)
                    alg.Clear();
            }
            return plaintext;
        }
Example #28
0
 public static string DecryptString(string data, byte[] key)
 {
     RijndaelManaged aesAlg = new RijndaelManaged();
     try
     {
         byte[] bytes = Convert.FromBase64String(data);
         Rfc2898DeriveBytes pwddb = new Rfc2898DeriveBytes(key, _salt, 1);
         aesAlg.Key = pwddb.GetBytes(aesAlg.KeySize / 8);
         using (MemoryStream ms = new MemoryStream(bytes))
         {
             aesAlg.IV = ReadByteArray(ms);
             ICryptoTransform dec = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
             using (CryptoStream cs = new CryptoStream(ms, dec, CryptoStreamMode.Read))
             {
                 using (StreamReader sr = new StreamReader(cs))
                 {
                     return sr.ReadToEnd();
                 }
             }
         }
     }
     catch
     {
         return string.Empty;
     }
     finally
     {
         aesAlg.Clear();
     }
 }
Example #29
0
        public String DecryptIt(String s, byte[] key = null, byte[] IV = null, PaddingMode padding = PaddingMode.PKCS7)
        {
            String result;
            //magically assign key and IV if one isn't given as an argument
            key = key ?? cryptKey;
            IV = IV ?? cryptIV;
            RijndaelManaged rijn = new RijndaelManaged();
            rijn.Mode = CipherMode.CBC;
            rijn.Padding = padding;
            rijn.BlockSize = 256;

            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(s)))
            {
                using (ICryptoTransform decryptor = rijn.CreateDecryptor(key, IV))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader swDecrypt = new StreamReader(csDecrypt))
                        {
                            result = swDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            rijn.Clear();
            return result;
        }
Example #30
0
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="CipherText">Text to be decrypted</param>
        /// <param name="Password">Password to decrypt with</param>
        /// <param name="Salt">Salt to decrypt with</param>
        /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="PasswordIterations">Number of iterations to do</param>
        /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="KeySize">Can be 128, 192, or 256</param>
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string CipherText, string Password,
            string Salt = "Kosher", string HashAlgorithm = "SHA1",
            int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
            int KeySize = 256)
        {
            if (string.IsNullOrEmpty(CipherText))
                return "";
            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
            byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
            RijndaelManaged SymmetricKey = new RijndaelManaged();
            SymmetricKey.Mode = CipherMode.CBC;
            byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
            int ByteCount = 0;
            using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                    {

                        ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
        }
Example #31
0
        private static string decrypt_function(byte[] Cipher_Text, byte[] Key, byte[] IV)
        {
            RijndaelManaged Crypto = null;
            MemoryStream MemStream = null;
            ICryptoTransform Decryptor = null;
            CryptoStream Crypto_Stream = null;
            StreamReader Stream_Read = null;
            string Plain_Text;

            try {
                Crypto = new RijndaelManaged ();
                Crypto.Key = Key;
                Crypto.IV = IV;

                MemStream = new MemoryStream (Cipher_Text);

                //Create Decryptor make sure if you are decrypting that this is here and you did not copy paste encryptor.
                Decryptor = Crypto.CreateDecryptor (Crypto.Key, Crypto.IV);

                //This is different from the encryption look at the mode make sure you are reading from the stream.
                Crypto_Stream = new CryptoStream (MemStream, Decryptor, CryptoStreamMode.Read);

                //I used the stream reader here because the ReadToEnd method is easy and because it return a string, also easy.
                Stream_Read = new StreamReader (Crypto_Stream);
                Plain_Text = Stream_Read.ReadToEnd ();
            } finally {
                if (Crypto != null)
                    Crypto.Clear ();

                MemStream.Flush ();
                MemStream.Close ();

            }
            return Plain_Text;
        }
        public static void ValueWriteToFile()
        {
            string            filename          = "needfiles_xxx";
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();

            xmlWriterSettings.CheckCharacters    = false;
            xmlWriterSettings.ConformanceLevel   = ConformanceLevel.Auto;
            xmlWriterSettings.OmitXmlDeclaration = false;
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings);

            xmlWriter.WriteStartDocument(true);
            xmlWriter.WriteStartElement("Limit");
            xmlWriter.WriteStartElement("DisLimit");
            xmlWriter.WriteElementString("OnOff", "aaaaaaaa");
            xmlWriter.WriteElementString("Radius", "bbbbbbbbbb");
            xmlWriter.WriteEndElement();
            int num = 0;

            System.Collections.ArrayList myAreaLimitList = new System.Collections.ArrayList();

            foreach (string areaLimitClass in myAreaLimitList) // We are not actually writing ANY limits in this case...  feel free to define the class and fix it.
            {
                xmlWriter.WriteStartElement("AreaLimit");
                xmlWriter.WriteAttributeString("id", "ccccccc");
                xmlWriter.WriteElementString("OnOff", "ddddddddddd");
                xmlWriter.WriteElementString("Long", "eeeeeeeeeee");
                xmlWriter.WriteElementString("Lati", "ffffffffffff");
                xmlWriter.WriteElementString("Radius", "ggggggggggg");
                xmlWriter.WriteEndElement();
                num++;
            }
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndDocument();
            xmlWriter.Flush();
            xmlWriter.Close();
            string xml = stringWriter.ToString();

            stringWriter.Close();
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xml);
            System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged();
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(args[0]);
            rijndaelManaged.Key            = bytes;
            xmlDocument.PreserveWhitespace = true;
            Encrypt(xmlDocument, "Limit", rijndaelManaged);
            if (rijndaelManaged != null)
            {
                rijndaelManaged.Clear();
            }
            xmlDocument.Save(filename);
        }