CreateDecryptor() публичный Метод

public CreateDecryptor ( ) : ICryptoTransform
Результат ICryptoTransform
Пример #1
13
        public static bool DecryptBase64(string cliperText, string key, out string originText)
        {
            byte[] inputData = Convert.FromBase64String(cliperText);

            var aes = new AesManaged()
            {
                Padding = _padding,
                Mode = _cipherMode,
                IV = ORIGIN_IV,
                Key = Encoding.UTF8.GetBytes(key.PadRight(KEY_LENGTH, PADDING_CHAR).Substring(0, KEY_LENGTH))
            };

            var decryptor = aes.CreateDecryptor();
            bool decryptSuccess = true;
            try
            {
                byte[] decryptedData = decryptor.TransformFinalBlock(inputData, 0, inputData.Length);
                originText = Encoding.UTF8.GetString(decryptedData);
            }
            catch
            {
                decryptSuccess = false;
                originText = string.Empty;
            }
            finally
            {
                decryptor.Dispose();
                if (aes != null)
                {
                    aes.Clear();
                }
            }
            return decryptSuccess;
        }
Пример #2
0
		public string Decryption() {
			try {
				byte[] encrypted=Convert.FromBase64String(textInput.Text);
				MemoryStream ms=null;
				CryptoStream cs=null;
				StreamReader sr=null;
				Aes aes=new AesManaged();
				aes.Key=key;
				aes.IV=new byte[16];
				ICryptoTransform decryptor=aes.CreateDecryptor(aes.Key,aes.IV);
				ms=new MemoryStream(encrypted);
				cs=new CryptoStream(ms,decryptor,CryptoStreamMode.Read);
				sr=new StreamReader(cs);
				string decrypted=sr.ReadToEnd();
				ms.Dispose();
				cs.Dispose();
				sr.Dispose();
				if(aes!=null) {
					aes.Clear();
				}
				return decrypted;
			}
			catch { 
				MessageBox.Show("Text entered was not valid encrypted text.");
				return"";
			}
		}
Пример #3
0
 public static string Decrypt(string str,byte[] key)
 {
     //No need to check RemotingRole; no call to db.
     if(str==""){
         return "";
     }
     try {
         byte[] encrypted=Convert.FromBase64String(str);
         MemoryStream ms=null;
         CryptoStream cs=null;
         StreamReader sr=null;
         Aes aes=new AesManaged();
         aes.Key=key;
         aes.IV=new byte[16];
         ICryptoTransform decryptor=aes.CreateDecryptor(aes.Key,aes.IV);
         ms=new MemoryStream(encrypted);
         cs=new CryptoStream(ms,decryptor,CryptoStreamMode.Read);
         sr=new StreamReader(cs);
         string decrypted=sr.ReadToEnd();
         ms.Dispose();
         cs.Dispose();
         sr.Dispose();
         if(aes!=null) {
             aes.Clear();
         }
         return decrypted;
     }
     catch {
         //MessageBox.Show("Text entered was not valid encrypted text.");
         return"";
     }
 }
 public static void DecryptFile(string inputFile, string outputFile, string keyIV)
 {
   byte[] array1 = new byte[32];
   byte[] array2 = new byte[16];
   AssetStoreUtils.HexStringToByteArray(keyIV, array1, 0);
   AssetStoreUtils.HexStringToByteArray(keyIV, array2, 64);
   EditorUtility.DisplayProgressBar("Decrypting", "Decrypting package", 0.0f);
   FileStream fileStream1 = File.Open(inputFile, System.IO.FileMode.Open);
   FileStream fileStream2 = File.Open(outputFile, System.IO.FileMode.CreateNew);
   long length = fileStream1.Length;
   long num = 0;
   AesManaged aesManaged = new AesManaged();
   aesManaged.Key = array1;
   aesManaged.IV = array2;
   CryptoStream cryptoStream = new CryptoStream((Stream) fileStream1, aesManaged.CreateDecryptor(aesManaged.Key, aesManaged.IV), CryptoStreamMode.Read);
   try
   {
     byte[] numArray = new byte[40960];
     int count;
     while ((count = cryptoStream.Read(numArray, 0, numArray.Length)) > 0)
     {
       fileStream2.Write(numArray, 0, count);
       num += (long) count;
       if (EditorUtility.DisplayCancelableProgressBar("Decrypting", "Decrypting package", (float) num / (float) length))
         throw new Exception("User cancelled decryption");
     }
   }
   finally
   {
     cryptoStream.Close();
     fileStream1.Close();
     fileStream2.Close();
     EditorUtility.ClearProgressBar();
   }
 }
Пример #5
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);
        }
Пример #6
0
        public static byte[] Decrypt(byte[] input)
        {
            if (_key == null || _key.Length == 0) throw new Exception("Key can not be empty.");
            if (input == null || input.Length == 0) throw new ArgumentException("Input can not be empty.");

            byte[] data = new byte[0];

            try
            {
                using (var ms = new MemoryStream(input))
                {
                    using (var rd = new AesManaged { Key = _key })
                    {
                        byte[] iv = new byte[IVLENGTH];
                        ms.Read(iv, 0, IVLENGTH); // read first 16 bytes for IV, followed by encrypted message
                        rd.IV = iv;

                        using (var cs = new CryptoStream(ms, rd.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            byte[] temp = new byte[ms.Length - IVLENGTH + 1];
                            data = new byte[cs.Read(temp, 0, temp.Length)];
                            Buffer.BlockCopy(temp, 0, data, 0, data.Length);
                        }
                    }
                }
            }
            catch
            {
            }
            return data;
        }
Пример #7
0
        public static string Decrypt(byte[] encryptedData, string password, byte[] salt = null)
        {
            if (encryptedData == null) throw new ArgumentNullException("encryptedData");
            if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");

            if (salt == null) salt = DefaultSalt;
            var aes = new AesManaged();

            string text;

            try
            {
                aes.SetKey(password, salt);
                using (var ms = new MemoryStream(encryptedData))
                {
                    aes.IV = ms.GetIV();
                    var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
                    using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    using (var sr = new StreamReader(cs))
                        text = sr.ReadToEnd();
                }
            }
            finally
            {
                aes.Clear();
            }

            return text;
        }
Пример #8
0
    public static string Decrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;

                using (MemoryStream decryptionStream = new MemoryStream())
                {
                    using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] encryptedData = Convert.FromBase64String(text);


                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                    }

                    byte[] decryptedData = decryptionStream.ToArray();
                    string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);


                    return decryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
Пример #9
0
    public static bool ForCodeCoverage()
    {
        AesManaged aes = new AesManaged();
        using (ICryptoTransform cte = aes.CreateEncryptor(), ctd = aes.CreateDecryptor())
        {
            byte[] plain1 = new byte[64];
            for (int i = 0; i < plain1.Length; i++)
                plain1[i] = (byte)i;

            byte[] encr1 = cte.TransformFinalBlock(plain1, 0, plain1.Length);
            using(MemoryStream ms = new MemoryStream())
            using(CryptoStream cs = new CryptoStream(ms, ctd, CryptoStreamMode.Write))
            {
                cs.Write(encr1, 0, 16);
                cs.Write(encr1, 16, 16);
                cs.Write(encr1, 32, 16);
                cs.Write(encr1, 48, encr1.Length-48);
                cs.FlushFinalBlock();
                byte[] plain2 = ms.ToArray();

                if (!Compare(plain1, plain2))
                {
                    Console.WriteLine("CodeCoverage case failed");
                    return false;
                }
                return true;
            }
        }
    }
Пример #10
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;
        }
        /// <summary>
        /// this algorithm uses the AES algorithm to decrypt the given cipherText
        /// </summary>
        /// <param name="cipherText"></param>
        /// <param name="sharedSecret"></param>
        /// <returns></returns>
        public static string DecryptCipherAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                return cipherText;
            }

            AesManaged aesAlg = null;
            string plaintext = null;
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, salt);

            // Create the streams used for decryption.
            byte[] bytes = Convert.FromBase64String(cipherText);
            using (MemoryStream memoryDecrypt = new MemoryStream(bytes))
            {
                aesAlg = new AesManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                // Get the initialization vector from the encrypted stream
                aesAlg.IV = ReadByteArray(memoryDecrypt);
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                using (CryptoStream cryptoDecrypt =
                    new CryptoStream(memoryDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader streamDecrypt = new StreamReader(cryptoDecrypt))
                    {
                        plaintext = streamDecrypt.ReadToEnd();
                    }
                }
            }
            return plaintext;
        }
        /// <summary>
        /// Decrypts the ciphertext using the Key.
        /// </summary>
        /// <param name="ciphertext">The ciphertext to decrypt.</param>
        /// <param name="password">The plain text encryption key.</param>
        /// <returns>The decrypted text.</returns>
        public static byte[] Decrypt(byte[] cipherText, string password)
        {
            if (cipherText == null || cipherText.Length == 0) throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");

            // Extract the salt from our ciphertext
            var saltBytes = cipherText.Take(SaltSize).ToArray();
            var ciphertextBytes = cipherText.Skip(SaltSize).ToArray();

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(password, saltBytes))
            {
                // Derive the previous Key and IV from the password and salt
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream(ciphertextBytes))
                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                using (var outputStream = new StreamReader(cryptoStream))
                using (var outMemoryStream = new MemoryStream())
                {
                    outputStream.BaseStream.CopyTo(outMemoryStream);
                    return outMemoryStream.ToArray();
                }
            }
        }
Пример #13
0
		public static void Register()
		{
			using (var manifestResourceStream = typeof(SettingsRegister).Assembly.GetManifestResourceStream("Raven.Studio.Settings.dat"))
			{
				if (manifestResourceStream == null || manifestResourceStream.Length == 0)
				{
					return;
				}

				using (var reader = new BinaryReader(manifestResourceStream))
				using (var aes = new AesManaged())
				{
					aes.Key = reader.ReadBytes(32);
					aes.IV = reader.ReadBytes(16);

					using (var cryptoStream = new CryptoStream(manifestResourceStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
					using (var cryptoReader = new BinaryReader(cryptoStream))
					{
						var licensee = cryptoReader.ReadString();
						var licenseKey = cryptoReader.ReadString();
						ActiproSoftware.Products.ActiproLicenseManager.RegisterLicense(licensee, licenseKey);
					}
				}
			}
		} 
Пример #14
0
        //Decrypts the 16 bytes block @cipherText using @key in ECB mode
        public static byte[] AES_DecryptBlock(byte[] cipherText, byte[] key)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length != 16)
                throw new ArgumentException ("cipherText must be a 16 byte array");
            if (key == null || key.Length <= 0)
                throw new ArgumentNullException ("Key");

            // Declare the string used to hold the decrypted text.
            byte[] output_buffer = new byte[cipherText.Length];

            using (AesManaged aesAlg = new AesManaged()) {
                aesAlg.Mode = CipherMode.ECB;

                aesAlg.BlockSize = 128;
                aesAlg.KeySize = 128;
                aesAlg.Padding = PaddingMode.None;
                aesAlg.Key = key;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor (aesAlg.Key, aesAlg.IV);
                decryptor.TransformBlock (cipherText, 0, cipherText.Length, output_buffer, 0);
            }

            return output_buffer;
        }
        public static string decrypt(string valueToDecrypt)
        {
            using (Aes aes = new AesManaged())
            {
                aes.Padding = PaddingMode.PKCS7;
                aes.KeySize = 128;          // in bits
                aes.Key = new byte[128 / 8];  // 16 bytes for 128 bit encryption
                aes.IV = new byte[128 / 8];   // AES needs a 16-byte IV

                // Should set Key and IV here.  Good approach: derive them from 
                // a password via Cryptography.Rfc2898DeriveBytes 
                byte[] cipherText = Convert.FromBase64String(valueToDecrypt);
                byte[] plainText = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherText, 0, cipherText.Length);
                    }

                    plainText = ms.ToArray();
                }

                return UTF8Encoding.UTF8.GetString(plainText);
            }
        }
Пример #16
0
 public static void DecryptFile(string inputFile, string outputFile, string keyIV)
 {
     byte[] array = new byte[0x20];
     byte[] buffer2 = new byte[0x10];
     HexStringToByteArray(keyIV, array, 0);
     HexStringToByteArray(keyIV, buffer2, 0x40);
     FileStream stream = File.Open(inputFile, System.IO.FileMode.Open);
     FileStream stream2 = File.Open(outputFile, System.IO.FileMode.CreateNew);
     AesManaged managed = new AesManaged {
         Key = array,
         IV = buffer2
     };
     CryptoStream stream3 = new CryptoStream(stream, managed.CreateDecryptor(managed.Key, managed.IV), CryptoStreamMode.Read);
     try
     {
         int num;
         byte[] buffer = new byte[0xa000];
         while ((num = stream3.Read(buffer, 0, buffer.Length)) > 0)
         {
             stream2.Write(buffer, 0, num);
         }
     }
     finally
     {
         stream3.Close();
         stream.Close();
         stream2.Close();
     }
 }
        public static void DecryptFile(string inputFile, string outputFile, string skey)
        {
            try
            {
                using (Aes aes = new AesManaged() { KeySize = 256, BlockSize = 128 })
                {
                    var key = new Rfc2898DeriveBytes(skey, salt);

                    aes.Key = key.GetBytes(aes.KeySize / 8);
                    aes.IV = key.GetBytes(aes.BlockSize / 8);

                    using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
                    {
                        using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
                        {
                            using (ICryptoTransform decryptor = aes.CreateDecryptor())
                            {
                                using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read))
                                {
                                    int data;
                                    while ((data = cs.ReadByte()) != -1)
                                    {
                                        fsOut.WriteByte((byte)data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { throw; }
        }
Пример #18
0
        public string Decrypt(Secret secret)
        {
            string plainText = null;
            using (MemoryStream msDecrypt = new MemoryStream(secret.Data))
            {
                // Create an AesManaged object with the specified key and IV.
                using (Aes aesAlg = new AesManaged())
                {
                    aesAlg.Key = _key;
                    aesAlg.IV = secret.IV;

                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor();

                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt, Encoding.Unicode))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plainText = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return plainText;
        }
Пример #19
0
        /// <summary>
        /// <see cref="IAesManagedWrapper.Encrypt"/>
        /// </summary>
        public byte[] Decrypt(byte[] bytesToBeDecrypted, byte[] aesKey, byte[] aesIv)
        {
            byte[] decryptedBytes;

            using (var ms = new MemoryStream())
            {
                using (var aes = new AesManaged())
                {
                    SetStandardConfiguration(aes);

                    aes.Key = aesKey;
                    aes.IV = aesIv;

                    using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }

                    decryptedBytes = ms.ToArray();
                }
            }

            return decryptedBytes;
        }
Пример #20
0
        /// <summary>
        /// Decrypts the ciphertext using the Key.
        /// </summary>
        /// <param name="ciphertext">The ciphertext to decrypt.</param>
        /// <param name="key">The plain text encryption key.</param>
        /// <returns>The decrypted text.</returns>
        public static string Decrypt(string ciphertext, string key)
        {
            if (string.IsNullOrEmpty(ciphertext))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            // Extract the salt from our ciphertext
            var allTheBytes = Convert.FromBase64String(ciphertext);
            var saltBytes = allTheBytes.Take(_saltSize).ToArray();
            var ciphertextBytes = allTheBytes.Skip(_saltSize).Take(allTheBytes.Length - _saltSize).ToArray();

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, saltBytes))
            {
                // Derive the previous IV from the Key and Salt
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                // Create a decrytor to perform the stream transform.
                // Create the streams used for decryption.
                // The default Cipher Mode is CBC and the Padding is PKCS7 which are both good
                using (var aesManaged = new AesManaged())
                using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream(ciphertextBytes))
                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                {
                    // Return the decrypted bytes from the decrypting stream.
                    return streamReader.ReadToEnd();
                }
            }
        }
Пример #21
0
 public static MyWallet Load(string path, string password)
 {
     MyWallet wallet = new MyWallet();
     byte[] aes_key = Encoding.UTF8.GetBytes(password).Sha256().Sha256();
     byte[] aes_iv = new byte[16];
     using (AesManaged aes = new AesManaged())
     using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
     {
         fs.Read(aes_iv, 0, aes_iv.Length);
         using (ICryptoTransform decryptor = aes.CreateDecryptor(aes_key, aes_iv))
         using (CryptoStream cs = new CryptoStream(fs, decryptor, CryptoStreamMode.Read))
         using (BinaryReader reader = new BinaryReader(cs))
         {
             int count = (int)reader.ReadVarInt();
             for (int i = 0; i < count; i++)
             {
                 byte[] privateKey = reader.ReadBytes(32);
                 bool compressed = reader.ReadBoolean();
                 ECPoint publicKey = ECCurve.Secp256k1.G * privateKey;
                 UInt160 publicKeyHash = publicKey.EncodePoint(compressed).ToScriptHash();
                 wallet.accounts.Add(new WalletEntry(privateKey, publicKey, publicKeyHash, compressed));
             }
         }
     }
     Array.Clear(aes_key, 0, aes_key.Length);
     return wallet;
 }
Пример #22
0
 public static string Decrypt(this string text)
 {
     if (string.IsNullOrEmpty(text))
     {
         return null;
     }
     using (MemoryStream ms = new MemoryStream())
     {
         byte[] cipherText = StringToByteArray(text);
         byte[] plainText;
         using (Aes aes = new AesManaged())
         {
             aes.Padding = PaddingMode.PKCS7;
             aes.KeySize = AesKeySizeInBits;
             int KeyStrengthInBytes = aes.KeySize / 8;
             System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 =
                 new System.Security.Cryptography.Rfc2898DeriveBytes(Password, Salt, Rfc2898KeygenIterations);
             aes.Key = rfc2898.GetBytes(KeyStrengthInBytes);
             aes.IV = rfc2898.GetBytes(KeyStrengthInBytes);
             using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(cipherText, 0, cipherText.Length);
             }
             plainText = ms.ToArray();
             return System.Text.Encoding.Unicode.GetString(plainText);
         }
     }
 }
Пример #23
0
        public byte[] Decrypt(byte[] cipher, byte[] key, byte[] IV)
        {
            System.Collections.Generic.List<byte> bytes = new List<byte>();

            using (AesManaged _aesAlgorithm = new AesManaged())
            {
                _aesAlgorithm.Key = key;
                _aesAlgorithm.IV = IV;

                using (ICryptoTransform decryptor = _aesAlgorithm.CreateDecryptor(_aesAlgorithm.Key, _aesAlgorithm.IV))
                {
                    using (System.IO.MemoryStream str = new System.IO.MemoryStream(cipher))
                    {
                        using (CryptoStream crypto = new CryptoStream(str, decryptor, CryptoStreamMode.Read))
                        {
                            int b = crypto.ReadByte();

                            while (b > -1)
                            {
                                b = crypto.ReadByte();
                                bytes.Add((byte)b);
                            }
                        }
                    }
                    _aesAlgorithm.Clear();
                }
            }

            return bytes.ToArray();
        }
 internal static byte[] Decrypt(byte[] data)
 {
     byte[] output = null;
     using (var aes = new AesManaged())
     {
         using (var decryptor = aes.CreateDecryptor(Configuration.Default.EncryptionKey, Configuration.Default.EncryptionIV))
         {
             using (var dataStream = new MemoryStream())
             {
                 using (var encryptionStream = new CryptoStream(dataStream, decryptor, CryptoStreamMode.Write))
                 {
                     encryptionStream.Write(data, 0, data.Length);
                     encryptionStream.FlushFinalBlock();
                     dataStream.Position = 0;
                     byte[] transformedBytes = new byte[dataStream.Length];
                     dataStream.Read(transformedBytes, 0, transformedBytes.Length);
                     encryptionStream.Close();
                     dataStream.Close();
                     output = transformedBytes;
                 }
             }
         }
     }
     return output;
 }
Пример #25
0
        public static Stream Decrypt(Stream source,
            Headers headers, byte[] masterKey)
        {
            byte[] easKey;
            using (var buffer = new MemoryStream())
            {
                var masterSeed = headers.MasterSeed;
                buffer.Write(masterSeed, 0, masterSeed.Length);
                buffer.Write(masterKey, 0, masterKey.Length);

                easKey = BufferEx.GetHash(buffer.ToArray());
            }

            var eas = new AesManaged
            {
                KeySize = 256,
                Key = BufferEx.Clone(easKey),
                IV = BufferEx.Clone(headers.EncryptionIV)
            };

            Stream stream = new CryptoStream(source,
                eas.CreateDecryptor(),
                CryptoStreamMode.Read);

            if (!VerifyStartBytes(headers, stream))
                return null;

            stream = new HashedBlockStream(stream, true);
            return headers.Compression == Compressions.GZip
                ? new GZipInputStream(stream) : stream;
        }
Пример #26
0
        /// <summary> 
        /// Decrypt a string 
        /// </summary> 
        /// <param name="input">Input string in base 64 format</param> 
        /// <returns>Decrypted string</returns> 
        public static string Decrypt(string input, string password)
        {
            byte[] encryptedBytes = Convert.FromBase64String(input);
            byte[] saltBytes = Encoding.UTF8.GetBytes(password);
            string decryptedString = string.Empty;
            using (var aes = new AesManaged())
            {
                Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);
                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);

                using (ICryptoTransform decryptTransform = aes.CreateDecryptor())
                {
                    using (MemoryStream decryptedStream = new MemoryStream())
                    {
                        CryptoStream decryptor =
                            new CryptoStream(decryptedStream, decryptTransform, CryptoStreamMode.Write);
                        decryptor.Write(encryptedBytes, 0, encryptedBytes.Length);
                        decryptor.Flush();
                        decryptor.Close();

                        byte[] decryptBytes = decryptedStream.ToArray();
                        decryptedString =
                            UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
                    }
                }
            }

            return decryptedString;
        }
        public static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] IV)
        {
            string plaintext = null;

            using (Aes aesAlg = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IV, 0, IV.Length), key);
                aesAlg.Key = deriveBytes.GetBytes(128 / 8);
                aesAlg.IV = aesAlg.Key;

                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;
        }
Пример #28
0
        public static string Decrypt(string ciphertext, string key)
        {
            if (string.IsNullOrEmpty(ciphertext))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            var allTheBytes = Convert.FromBase64String(ciphertext);
            var saltBytes = allTheBytes.Take(_saltSize).ToArray();
            var ciphertextBytes = allTheBytes.Skip(_saltSize).Take(allTheBytes.Length - _saltSize).ToArray();

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, saltBytes))
            {
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream(ciphertextBytes))
                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
Пример #29
0
        public static string DecryptStringFromByte(byte[] sourceLine, byte[] key, byte[] IV)
        {
            if (sourceLine == null || sourceLine.Length == 0)
            {
                return null;
            }

            if (key == null || key.Length <= 0 || IV == null || IV.Length <= 0)
            {
                return null;
            }

            AesManaged aesAlg = new AesManaged();
            aesAlg.Key = key;
            aesAlg.IV = IV;

            ICryptoTransform decryptor = aesAlg.CreateDecryptor();

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

            string result = srDecrypt.ReadToEnd();

            return result;
        }
        public void DecryptFile(string sourceFilename, string destinationFilename, string password)
        {
            AesManaged aes = new AesManaged();
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
            aes.Key = key.GetBytes(aes.KeySize / 8);
            aes.IV = key.GetBytes(aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;
            ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);

            using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
                {
                    try
                    {
                        using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            source.CopyTo(cryptoStream);
                        }
                    }
                    catch (CryptographicException exception)
                    {
                        if (exception.Message == "Padding is invalid and cannot be removed.")
                            throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
                        else
                            throw;
                    }
                }
            }
        }
Пример #31
0
        /// <summary>
        /// Decrypt encrypted string
        /// </summary>
        /// <param name="Str">Encrypted string</param>
        /// <param name="Password">Password used for encryption</param>
        /// <param name="Salt">Salt string used for encryption (at least 8 bytes)</param>
        /// <returns>Decrypted string if success; otherwise - empty string</returns>
        public static string DecryptString(string Str, string Password = "******", string Salt = "tdcm1234")
        {
            try
            {
                using (Aes aes = new AesManaged())
                {
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(Salt));
                    aes.Key = deriveBytes.GetBytes(128 / 8);
                    aes.IV = aes.Key;

                    using (MemoryStream decryptionStream = new MemoryStream())
                    {
                        using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            byte[] encryptedData = Convert.FromBase64String(Str);
                            decrypt.Write(encryptedData, 0, encryptedData.Length);
                            decrypt.Flush();
                        }
                        byte[] decryptedData = decryptionStream.ToArray();
                        return UTF8Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error : AES ~ DecryptString ; " + ex.Message);
                return "";
            }
        }
Пример #32
0
        protected static void SecurityAesDecrypt(BlamVersion game, Blam.CacheSectionType section_type, byte[] input, out byte[] output,
                                                 GetAesParametersProc GetAesParameters)
        {
            output = null;

            using (var aesm = new Crypt.AesManaged())
            {
                aesm.KeySize = 128;
                aesm.Padding = Crypt.PaddingMode.Zeros;
                aesm.Mode    = Crypt.CipherMode.CBC;

                byte[] key, iv;
                GetAesParameters(game, section_type, out key, out iv);

                if (key != null && iv != null)
                {
                    using (var ctx = aesm.CreateDecryptor(key, iv))
                    {
                        output = ctx.TransformFinalBlock(input, 0, input.Length);
                    }
                }
            }
        }
Пример #33
0
    public string Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
    {
        string plaintext = null;

        // Create AesManaged
        using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged())
        {
            // Create a decryptor
            System.Security.Cryptography.ICryptoTransform decryptor = aes.CreateDecryptor(Key, IV);
            // Create the streams used for decryption.
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(cipherText))
            {
                // Create crypto stream
                using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                {
                    // Read crypto stream
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(cs))
                        plaintext = reader.ReadToEnd();
                }
            }
        }
        return(plaintext);
    }
Пример #34
0
 public static byte[] AESDecrypt(this byte[] data, byte[] password, CipherMode mode = CipherMode.CBC)
 {
     byte[] result;
     try
     {
         using (Aes aes = new AesManaged())
         {
             aes.Mode = mode;
             aes.Key  = password;
             aes.IV   = password;
             using (MemoryStream memoryStream = new MemoryStream())
             {
                 using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                 {
                     cryptoStream.Write(data, 0, data.Length);
                     cryptoStream.FlushFinalBlock();
                 }
                 result = memoryStream.ToArray();
             }
         }
     }
     catch (Exception ex)
     {
         Debug.Print("aes encryption failed ", new object[] { ex });
         result = null;
     }
     return(result);
 }
Пример #35
0
        public byte[] Decrypt(byte[] B, String PSW)
        {
            System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(PSW, new Byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            System.IO.MemoryStream           ms   = new System.IO.MemoryStream();
            System.Security.Cryptography.Aes AESE = new System.Security.Cryptography.AesManaged();

            AESE.Key = pdb.GetBytes(AESE.KeySize / 8);
            AESE.IV  = pdb.GetBytes(AESE.BlockSize / 8);

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

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

            cs.Close();

            return(ms.ToArray());
        }