Esempio n. 1
0
        public static void TripleDesCreate()
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes("This is a secret message and is a sentence that is longer than a block, it ensures that multi-block functions work.");
            TripleDES tripleDes = TripleDES.Create();

            byte[] encryptedBytes;
            using (MemoryStream input = new MemoryStream(inputBytes))
            using (CryptoStream cryptoStream = new CryptoStream(input, tripleDes.CreateEncryptor(), CryptoStreamMode.Read))
            using (MemoryStream output = new MemoryStream())
            {
                cryptoStream.CopyTo(output);
                encryptedBytes = output.ToArray();
            }

            Assert.NotEqual(inputBytes, encryptedBytes);

            byte[] decryptedBytes;
            using (MemoryStream input = new MemoryStream(encryptedBytes))
            using (CryptoStream cryptoStream = new CryptoStream(input, tripleDes.CreateDecryptor(), CryptoStreamMode.Read))
            using (MemoryStream output = new MemoryStream())
            {
                cryptoStream.CopyTo(output);
                decryptedBytes = output.ToArray();
            }

            Assert.Equal(inputBytes, decryptedBytes);
        }
        /// <summary>
        /// Decrypt
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public byte[] Decrypt(byte[] input)
        {
            // Grab the Initialization Vector out of the input
            var ivBytes = new byte[(mBlockSize / 8)];

            Array.Copy(input, ivBytes, ivBytes.Length);

            // Take the remaining bytes which represent the actual encrypted payload
            var encryptedBytes = new byte[input.LongLength - ivBytes.Length];

            Array.Copy(input, ivBytes.Length, encryptedBytes, 0, encryptedBytes.LongLength);

            using (AesManaged aesManaged = new AesManaged {
                Key = mKey, BlockSize = mBlockSize, IV = ivBytes, Mode = CipherMode.CBC
            })
                using (Stream ms = new MemoryStream(encryptedBytes))
                    using (ICryptoTransform ct = aesManaged.CreateDecryptor(aesManaged.Key, aesManaged.IV))
                        using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Read))
                            using (MemoryStream outputStream = new MemoryStream())
                            {
                                cs.CopyTo(outputStream);

                                if (!mUseCompression)
                                {
                                    return(outputStream.ToArray());
                                }

                                outputStream.Position = 0;
                                using (var zipStream = new GZipStream(outputStream, CompressionMode.Decompress))
                                    using (var outputZipStream = new MemoryStream())
                                    {
                                        zipStream.CopyTo(outputZipStream);
                                        zipStream.Close();
                                        return(outputZipStream.ToArray());
                                    }
                            }
        }
Esempio n. 3
0
        public byte[] DecryptBytes(byte[] bytes, string password, string salt)
        {
            // Using the default key size.
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(salt));

            RijndaelManaged aesAlgorithm = new RijndaelManaged();

            aesAlgorithm.Key = key.GetBytes(aesAlgorithm.KeySize / 8);

            using (MemoryStream inputStream = new MemoryStream(bytes))
            {
                // Read in the array size and the cryptographic data.
                byte[] ivLengthArray = new byte[sizeof(Int32)];
                inputStream.Read(ivLengthArray, 0, ivLengthArray.Length);

                int ivLength = BitConverter.ToInt32(ivLengthArray, 0);
                inputStream.Read(aesAlgorithm.IV, 0, ivLength);

                // Read the rest of the stream to decrypt the data.
                using (ICryptoTransform decryptor = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
                    {
                        using (MemoryStream outputStream = new MemoryStream())
                        {
                            cryptoStream.CopyTo(outputStream);

                            byte[] dataWithIv  = outputStream.ToArray();
                            byte[] cleanedData = new byte[dataWithIv.Length - aesAlgorithm.IV.Length];
                            Array.Copy(dataWithIv, aesAlgorithm.IV.Length, cleanedData, 0, cleanedData.Length);

                            return(cleanedData);
                        }
                    }
                }
            }
        }
Esempio n. 4
0
        // Throw error if not valid
        public IEnumerable <OpenPgpPacket> GetDecryptedPackets(SymmetricAlgorithm keyedAlgorithm)
        {
            var transform = new OpenPgpCfbTransform(keyedAlgorithm, encrypt: false);
            var decryptor = new CryptoStream(EncryptedStream, transform, CryptoStreamMode.Read);
            var decrypted = new MemoryStream();

            decryptor.CopyTo(decrypted);

            // Get rid of the modification detection code, but verify it
            var mdcStart = decrypted.Length - (1 + 1 + 20);

            decrypted.Position = mdcStart;

            var mdcStream = new MemoryStream();

            decrypted.CopyTo(mdcStream);
            decrypted.Position = 0;
            decrypted.SetLength(mdcStart + 2);
            var hasher = SHA1.Create();
            var hashIncludingHeaderAndLength = hasher.ComputeHash(transform.PrefixBytes.Concat(decrypted.ToArray()).ToArray());

            decrypted.SetLength(decrypted.Length - 2);
            decrypted.Position = 0;
            // TODO:
            mdcStream.Position = 0;
            var mdc = OpenPgpPacketReader.ReadAllPackets(mdcStream).First() as ModificationDetectionCodeOpenPgpPacket;

            for (int i = 0; i < hashIncludingHeaderAndLength.Length; i++)
            {
                if (hashIncludingHeaderAndLength[i] != mdc.HashValue[i])
                {
                    throw new ModificationDetectedException();
                }
            }

            return(OpenPgpPacketReader.ReadAllPackets(decrypted));
        }
Esempio n. 5
0
        /// <summary></summary>
        public byte[] DecryptAes(byte[] abEncrypted, byte[] abKey)
        {
            byte[] abReturn = null;

            if ((abEncrypted != null) && (abEncrypted.Length > ciAesBlockLength) && (abKey != null))
            {
                _AesServices.Padding = PaddingMode.PKCS7;

                for (int i = 0; i < ciAesBlockLength; i++)
                {
                    _abInitialisationVector[i] = abEncrypted[i];
                }

                using (ICryptoTransform AesDecryptor = _AesServices.CreateDecryptor(abKey, _abInitialisationVector))
                {
                    using (MemoryStream EncryptedStream = new MemoryStream(abEncrypted, ciAesBlockLength, abEncrypted.Length - ciAesBlockLength))
                    {
                        try
                        {
                            using (CryptoStream AesCryptoStream = new CryptoStream(EncryptedStream, AesDecryptor, CryptoStreamMode.Read))
                            {
                                using (MemoryStream DecryptedStream = new MemoryStream())
                                {
                                    AesCryptoStream.CopyTo(DecryptedStream);
                                    abReturn = DecryptedStream.ToArray();
                                }
                            }
                        }
                        catch (CryptographicException)
                        {
                            //
                        }
                    }
                }
            }
            return(abReturn);
        }
Esempio n. 6
0
        public void Decrypt(IByteBufferAllocator allocator, EncryptMode mode, Stream src, Stream dst, bool reliable)
        {
            using (var data = new BufferWrapper(allocator.Buffer().WithOrder(ByteOrder.LittleEndian)))
                using (var decryptor = GetAlgorithm(mode).CreateDecryptor())
                    using (var cs = new CryptoStream(src, decryptor, CryptoStreamMode.Read))
                    {
                        var padding  = cs.ReadByte();
                        var checksum = cs.ReadByte() | cs.ReadByte() << 8 | cs.ReadByte() << 16 | cs.ReadByte() << 24;

                        using (var dataStream = new WriteOnlyByteBufferStream(data.Buffer, false))
                            cs.CopyTo(dataStream);

                        if (reliable)
                        {
                            var counter        = (ushort)(Interlocked.Increment(ref _decryptCounter) - 1);
                            var messageCounter = data.Buffer.GetShort(data.Buffer.ReaderIndex);

                            if (counter != messageCounter)
                            {
                                throw new ProudException($"Invalid decrypt counter! Remote: {messageCounter} Local: {counter}");
                            }
                        }

                        var slice = data.Buffer.ReadSlice(data.Buffer.ReadableBytes - padding);
                        using (var dataStream = new ReadOnlyByteBufferStream(slice, false))
                        {
                            if (Hash.GetUInt32 <CRC32>(dataStream) != (uint)checksum)
                            {
                                throw new ProudException("Invalid checksum");
                            }

                            dataStream.Position = reliable ? 2 : 0;
                            dataStream.CopyTo(dst);
                        }
                    }
        }
        public static Byte[] SimmetricDecrypt(string password, byte[] salt, byte[] data)
        {
            try
            {
                using var aes                     = Aes.Create();
                using var encryptor               = aes.GetDecryptorFromPassword(password, salt);
                using MemoryStream msDecrypt      = new MemoryStream();
                using MemoryStream msOriginalData = new MemoryStream(data);

                using (CryptoStream csDecrypt = new CryptoStream(msOriginalData, encryptor, CryptoStreamMode.Read))
                {
                    csDecrypt.CopyTo(msDecrypt);
                }

                // important, dispose CryptoStream before accessing the array
                return(msDecrypt.ToArray());
            }
            catch (CryptographicException cex)
            {
                Log.Error(cex, "Error decrypting message");
                //Do not disclose anything to the caller.
                throw new SecurityException("Error in decrypting");
            }
        }
    public static byte[] DecryptData(byte[] encrypted, byte[] key)
    {
        var iv = new byte[16];

        Buffer.BlockCopy(encrypted, 0, iv, 0, iv.Length);
        using (var aesAlg = Aes.Create())
        {
            aesAlg.Mode = CipherMode.CBC;
            using (var decryptor = aesAlg.CreateDecryptor(key, iv))
            {
                using (var msDecrypt = new MemoryStream(encrypted, iv.Length, encrypted.Length - iv.Length))
                {
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (var resultStream = new MemoryStream())
                        {
                            csDecrypt.CopyTo(resultStream);
                            return(resultStream.ToArray());
                        }
                    }
                }
            }
        }
    }
Esempio n. 9
0
        public void Decrypt(Stream src, Stream dst, bool reliable)
        {
            if (RC4 == null)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            using (var decryptor = RC4.CreateDecryptor())
                using (var cs = new CryptoStream(src, decryptor, CryptoStreamMode.Read))
                {
                    if (reliable)
                    {
                        var counter        = (ushort)(Interlocked.Increment(ref _decryptCounter) - 1);
                        var messageCounter = cs.ReadByte() | cs.ReadByte() << 8;

                        if (counter != messageCounter)
                        {
                            throw new ProudException($"Invalid decrypt counter! Remote: {messageCounter} Local: {counter}");
                        }
                    }

                    cs.CopyTo(dst);
                }
        }
Esempio n. 10
0
        /// <summary>
        /// Decrypts the specified encrypted data using a symmetric key algorithm.
        /// </summary>
        /// <param name="encryptedData">The encrypted data.</param>
        /// <param name="key">The key.</param>
        /// <param name="initializationVector">The initialization vector.</param>
        /// <param name="method">The encryption method.</param>
        /// <returns></returns>
        public static byte[] Decrypt(
            byte[] encryptedData, byte[] key, byte[] initializationVector, SymmetricEncryptionMethod method)
        {
            using (SymmetricAlgorithm provider = GetSymmetricEncryptionAlgorithm(method))
            {
                // assigned the specified key and IV as
                // a pair is created upon creation of the provider
                provider.Key = key;
                provider.IV  = initializationVector;
                ICryptoTransform decryptor = provider.CreateDecryptor();

                using (MemoryStream ms = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (MemoryStream os = new MemoryStream())
                        {
                            cs.CopyTo(os);
                            return(os.ToArray());
                        }
                    }
                }
            }
        }
Esempio n. 11
0
 // SetValue gets called by Json.Net during deserialization.
 // The value parameter has the encrypted value read from the JSON;
 // target is the object on which to set the decrypted value.
 public void SetValue(object target, object value)
 {
     byte[] buffer = Convert.FromBase64String((string)value);
     using (MemoryStream inputStream = new MemoryStream(buffer, false))
         using (MemoryStream outputStream = new MemoryStream())
             using (AesManaged aes = new AesManaged {
                 Key = encryptionKey
             })
             {
                 byte[] iv        = new byte[16];
                 int    bytesRead = inputStream.Read(iv, 0, 16);
                 if (bytesRead < 16)
                 {
                     throw new CryptographicException("IV is missing or invalid.");
                 }
                 ICryptoTransform decryptor = aes.CreateDecryptor(encryptionKey, iv);
                 using (CryptoStream cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
                 {
                     cryptoStream.CopyTo(outputStream);
                 }
                 string decryptedValue = Encoding.UTF8.GetString(outputStream.ToArray());
                 targetProperty.SetValue(target, decryptedValue);
             }
 }
Esempio n. 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="transform"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        protected static BitStream CryptoStream(BitwiseStream stream, ICryptoTransform transform, CryptoStreamMode mode)
        {
            BitStream ret = new BitStream();

            if (mode == CryptoStreamMode.Write)
            {
                var cs = new CryptoStream(ret, transform, mode);
                stream.CopyTo(cs);
                cs.FlushFinalBlock();
            }
            else
            {
                var cs = new CryptoStream(stream, transform, mode);
                cs.CopyTo(ret);
            }

            if (stream.Position != stream.Length)
            {
                throw new PeachException("Didn't transform all bytes.");
            }

            ret.Seek(0, SeekOrigin.Begin);
            return(ret);
        }
        public CachedLicense TryRetrieve(string productIdentifier, string email)
        {
            string filename = Path.Combine(RootDirectory, FilenameFromIdentifier(productIdentifier + email));

            if (File.Exists(filename))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (Aes aes = Aes.Create())
                        using (ICryptoTransform transform = aes.CreateDecryptor(Key, IV))
                            using (FileStream fileStream = File.OpenRead(filename))
                                using (CryptoStream cs = new CryptoStream(fileStream, transform, CryptoStreamMode.Read))
                                {
                                    cs.CopyTo(ms);
                                }

                    ms.Seek(0, SeekOrigin.Begin);

                    return((CachedLicense) new XmlSerializer(typeof(CachedLicense)).Deserialize(ms));
                }
            }

            return(null);
        }
Esempio n. 14
0
        public string Decrypt(string cipherText)
        {
            byte[] encryptedPayload = Convert.FromBase64String(cipherText);

            using (var aes = new AesManaged())
            {
                int    ivLength    = aes.BlockSize / 8;
                byte[] iv          = encryptedPayload.Take(ivLength).ToArray();
                byte[] cipherBytes = encryptedPayload.Skip(ivLength).ToArray();

                ICryptoTransform decryptor = aes.CreateDecryptor(_key, iv);

                using (var memStream = new MemoryStream(cipherBytes))
                    using (var decryptedStream = new MemoryStream())
                    {
                        using (var cryptStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                            cryptStream.CopyTo(decryptedStream);

                        byte[] payload = decryptedStream.ToArray();

                        return(DecodePayload(payload));
                    }
            }
        }
Esempio n. 15
0
        //private static string Decrypt(byte[] paddingPrefixedBlob)
        //{
        //    return Encoding.Unicode.GetString(RawDecrypt(paddingPrefixedBlob)).TrimEnd('\0');
        //}

        private static byte[] DecryptRaw(byte[] paddingPrefixedBlob)
        {
            if (paddingPrefixedBlob == null)
            {
                return(new byte[0]);
            }

            using (MemoryStream ms = new MemoryStream(paddingPrefixedBlob, 4, paddingPrefixedBlob.Length - 4))
            {
                using (CryptoStream cs = new CryptoStream(ms, _decryptor, CryptoStreamMode.Read))
                {
                    using (MemoryStream msResult = new MemoryStream())
                    {
                        cs.CopyTo(msResult);
                        byte[] buffer = msResult.ToArray();
                        Dump("buffer", buffer);

                        byte[] b2 = new byte[buffer.Length - 4];
                        Buffer.BlockCopy(buffer, 4, b2, 0, b2.Length);
                        return(b2);
                    }
                }
            }
        }
Esempio n. 16
0
 public static byte[] DecryptAes256(byte[] ciphertext, byte[] iv, byte[] encryptionKey)
 {
     try
     {
         using (var aes = new AesManaged {
             KeySize = 256, Key = encryptionKey, Mode = CipherMode.CBC, IV = iv
         })
             using (var decryptor = aes.CreateDecryptor())
                 using (var inputStream = new MemoryStream(ciphertext, false))
                     using (var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
                         using (var outputStream = new MemoryStream())
                         {
                             cryptoStream.CopyTo(outputStream);
                             return(outputStream.ToArray());
                         }
     }
     catch (CryptographicException e)
     {
         throw new ParseException(
                   ParseException.FailureReason.IncorrectPassword,
                   "Decryption failed due to incorrect password or data corruption",
                   e);
     }
 }
Esempio n. 17
0
        public static void Encrypt(string input, string output, SymmetricAlgorithm alg)
        {
            using (var inputStream = new FileStream(input, FileMode.Open, FileAccess.Read))
            {
                using (var outputStream = new FileStream(output, FileMode.Create, FileAccess.Write))
                {
                    using (var cryptoStream = new CryptoStream(inputStream, alg.CreateEncryptor(), CryptoStreamMode.Read))
                    {
                        {
                            cryptoStream.CopyTo(outputStream);
                        }
                    }
                }
            }

            using (var outputStream = new FileStream(key, FileMode.Create, FileAccess.Write))
            {
                using (var streamWriter = new StreamWriter(outputStream))
                {
                    streamWriter.WriteLine(Convert.ToBase64String(alg.Key));
                    streamWriter.WriteLine(Convert.ToBase64String(alg.IV));
                }
            }
        }
Esempio n. 18
0
        public byte[] Decrypt <T>(byte[] aEncryptedMessage, SymetricKey SymetricKey)
            where T : SymmetricAlgorithm, new()
        {
            DeriveBytes rgb = new Rfc2898DeriveBytes(SymetricKey.Key, SymetricKey.Salt, SymetricKey.Iteration);

            SymmetricAlgorithm algorithm = new T();

            algorithm.Key = SymetricKey.Key;
            algorithm.IV  = SymetricKey.Salt;

            algorithm.Mode = this.Mode;
            //algorithm.Padding = PaddingMode.PKCS7;

            ICryptoTransform transform = algorithm.CreateDecryptor(SymetricKey.Key, SymetricKey.Salt);

            using (MemoryStream buffer = new MemoryStream(aEncryptedMessage))
                using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Read))
                    using (MemoryStream mo = new MemoryStream())
                    {
                        stream.CopyTo(mo);
                        mo.Position = 0;
                        return(mo.ToArray());
                    }
        }
Esempio n. 19
0
 public static byte[] DecryptFileToArray(User user, string iFileName, string token)
 {
     try
     {
         if (!File.Exists(iFileName) || !IsTokenGood(token))
         {
             return(new byte[0]);
         }
         byte[] keyArr = StringToByteArray(token.Substring(0, 32));
         byte[] ivArr  = StringToByteArray(token.Substring(32));
         if (!(keyArr.Length == ivArr.Length && keyArr.Length == 16))
         {
             return(new byte[0]);
         }
         using (MemoryStream doStream = new MemoryStream())
         {
             using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
             {
                 aesProvider.KeySize = KeySizeBits;
                 aesProvider.IV      = ivArr;
                 aesProvider.Key     = keyArr;
                 using (FileStream eiStream = File.OpenRead(iFileName))
                     using (CryptoStream cryptoStream = new CryptoStream(eiStream, aesProvider.CreateDecryptor(), CryptoStreamMode.Read))
                     {
                         cryptoStream.CopyTo(doStream);
                     }
             }
             return(doStream.ToArray());
         }
     }
     catch (Exception e)
     {
         ProgramLog.LogError(user, "Crypt", "DecryptFileToArray", e.Message);
         return(new byte[0]);
     }
 }
Esempio n. 20
0
        private void DecryptFileCore(string inputFile, string outputFile, byte[] key, bool overwrite)
        {
            var fileMode = (overwrite) ? FileMode.Create : FileMode.CreateNew;

            using (var alg = new AesManaged())
            {
                alg.Key  = key;
                alg.IV   = DefaultFileEncryptionIV;
                alg.Mode = CipherMode.CBC;

                var decryptor = alg.CreateDecryptor();

                using (var inStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (var outStream = new FileStream(outputFile, fileMode))
                    {
                        using (var cryptoStream = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read))
                        {
                            cryptoStream.CopyTo(outStream);
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        private static byte[] DecryptBytes(byte[] encryptedBytes)
        {
            Stream sourceStream = null;

            try
            {
                sourceStream = new MemoryStream(encryptedBytes);
                using (var aes = Aes.Create("AesManaged"))
                {
                    aes.Key = encryptionKey;
                    var iv = new byte[aes.BlockSize / 8];
                    sourceStream.Read(iv, 0, iv.Length);
                    aes.IV = iv;

                    using (var decryptor = aes.CreateDecryptor())
                    {
                        using (var cryptoStream = new CryptoStream(sourceStream, decryptor, CryptoStreamMode.Read))
                        {
                            sourceStream = null;
                            using (var targetStream = new MemoryStream())
                            {
                                cryptoStream.CopyTo(targetStream);
                                return(targetStream.ToArray());
                            }
                        }
                    }
                }
            }
            finally
            {
                if (sourceStream != null)
                {
                    sourceStream.Dispose();
                }
            }
        }
Esempio n. 22
0
        private static Stream ReceiveEncryptedDataStream(AsymmetricAlgorithm privateKey, Stream encryptedDataStream, byte[] iv, byte[] sessionKey)
        {
            var decryptedDataStream = new MemoryStream();

            var deformatter = new GostKeyExchangeDeformatter(privateKey);

            // Получатель принимает от отправителя зашифрованный сессионный ключ и дешифрует его
            using (var receiverSessionKey = deformatter.DecryptKeyExchangeAlgorithm(sessionKey))
            {
                // Получатель принимает от отправителя вектор инициализации
                receiverSessionKey.IV = iv;

                // Получатель дешифрует данные с использованием сессионного ключа
                using (var decryptor = receiverSessionKey.CreateDecryptor())
                {
                    var cryptoStream = new CryptoStream(encryptedDataStream, decryptor, CryptoStreamMode.Read);
                    cryptoStream.CopyTo(decryptedDataStream);
                }
            }

            decryptedDataStream.Position = 0;

            return(decryptedDataStream);
        }
Esempio n. 23
0
        private static void DecryptStream(FileStream encryptedFile, FileStream decryptedFile, byte[] key)
        {
            var aes         = Aes.Create();
            var shrinkedKey = new byte[32];
            var ivBase      = new byte[16];

            Array.Copy(key, 0, shrinkedKey, 0, 32);
            Array.Copy(key, 32, ivBase, 0, 16);

            aes.Mode    = CipherMode.CBC;
            aes.Key     = shrinkedKey;
            aes.Padding = PaddingMode.None;

            int numRead;
            var buffer = new byte[65536];

            var iv = new byte[16];

            Array.Copy(ivBase, iv, 16);

            while ((numRead = encryptedFile.Read(buffer, 0, buffer.Length)) > 0)
            {
                var offsetBytes = new byte[16];
                Array.Copy(BitConverter.GetBytes(encryptedFile.Position - numRead), offsetBytes, 8);

                var ivCrypter = aes.CreateEncryptor(shrinkedKey, new byte[16]);
                var newIv     = ivCrypter.TransformFinalBlock(offsetBytes, 0, 16);

                var ms = new MemoryStream(buffer, 0, numRead);

                var dec = aes.CreateDecryptor(shrinkedKey, newIv);

                using (var cs = new CryptoStream(ms, dec, CryptoStreamMode.Read))
                    cs.CopyTo(decryptedFile);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Функция дешифрования файла
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="key"></param>
        /// <param name="iV"></param>
        /// <returns></returns>
        private void DecryptFileFromAES(string filePath, byte[] key, byte[] iV)
        {
            // Check arguments.
            if (filePath == null || filePath.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("IV");
            }


            // Create an AesCryptoServiceProvider object
            // with the specified key and IV.
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.Key = key;
                aesAlg.IV  = iV;

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


                #region Old Worked
                //using (StreamReader reader = new StreamReader(filePath, Encoding.Default))
                //{
                //    var tmp = Encoding.Default.GetBytes(reader.ReadToEnd());
                //    // Create the streams used for decryption.
                //    using (MemoryStream msDecrypt = new MemoryStream(tmp))
                //    {
                //        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                //        {
                //            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                //            {
                //                reader.Close();

                //                string chiperText = srDecrypt.ReadToEnd();

                //                // Перезаписываем шифрованный файл на место файла
                //                using (FileStream openFile = File.Create(filePath))
                //                {
                //                    // Перезаписываем шифрованный файл на место файла
                //                    using (StreamWriter writer = new StreamWriter(openFile, Encoding.Default))
                //                    {
                //                        writer.Write(chiperText);
                //                    }
                //                }

                //                File.Move(filePath, filePath.Replace(".crypto", ""));
                //            }
                //        }
                //    }
                //}
                #endregion

                #region New Perfect Worked

                string tmpPath = Path.GetTempFileName();
                using (FileStream fsSrc = File.OpenRead(filePath))
                {
                    using (CryptoStream cs = new CryptoStream(fsSrc, decryptor, CryptoStreamMode.Read, true))
                        using (FileStream fsDst = File.Create(tmpPath))
                        {
                            cs.CopyTo(fsDst);
                        }
                }
                File.Delete(filePath);
                File.Move(tmpPath, filePath.Replace(".crypto", ""));

                #endregion
            }
        }
Esempio n. 25
0
        Script LoadScript(string p, ScriptType type, Dictionary <string, string> switches = null, Dictionary <string, string[]> assertSwitches = null)
        {
            var script = new Script()
            {
                name = p.Split('\\').Last()
            };
            string pbase = "";

            ZipArchive archive  = null;
            IArchive   compress = null;

            archive = null;
            MemoryStream zrpstream = null;

            Bitmap GetBitmap(string path)
            {
                if (type == ScriptType.Folder)
                {
                    if (path == null)
                    {
                    }
                    path = Path.Combine(p, pbase, path);
                    FileStream s;
                    try
                    {
                        s = File.OpenRead(path);
                    }
                    catch { throw new Exception("Could not open " + path); }
                    Bitmap b;
                    try
                    {
                        b = new Bitmap(s);
                    }
                    catch { throw new Exception("Corrupt image: " + path); }
                    s.Close();
                    return(b);
                }
                else if (type == ScriptType.Zip || type == ScriptType.Zrp)
                {
                    path = Path.Combine(pbase, path);
                    Stream s;
                    try
                    {
                        s = archive.GetEntry(path).Open();
                    }
                    catch { throw new Exception("Could not open " + path); }
                    Bitmap b;
                    try
                    {
                        b = new Bitmap(s);
                    }
                    catch { throw new Exception("Corrupt image: " + path); }
                    s.Close();
                    return(b);
                }
                else
                {
                    path = Path.Combine(pbase, path);
                    Stream s;
                    var    e = compress.Entries.Where(a => a.Key == path).ToArray();
                    if (e.Length == 0)
                    {
                        throw new Exception("Could not open " + path);
                    }
                    s = e[0].OpenEntryStream();
                    Bitmap b;
                    try
                    {
                        b = new Bitmap(s);
                    }
                    catch { throw new Exception("Corrupt image: " + path); }
                    s.Close();
                    return(b);
                }
            }

            try
            {
                string code = "";
                if (type == ScriptType.Folder)
                {
                    var files = Directory.GetFiles(p, "*script.cs", SearchOption.AllDirectories)
                                .Where(s => s.EndsWith("\\script.cs"))
                                .Select(s => s.Substring(p.Length + 1))
                                .ToArray();
                    Array.Sort(files.Select(s => s.Length).ToArray(), files);
                    if (files.Length == 0)
                    {
                        throw new Exception("Could not find script.cs file");
                    }
                    var jsonpath = files[0];
                    pbase = jsonpath.Substring(0, jsonpath.Length - "script.cs".Length);
                    if (files.Length == 0)
                    {
                        throw new Exception("Could not find script.cs file");
                    }
                    try
                    {
                        code = File.ReadAllText(Path.Combine(p, jsonpath));
                    }
                    catch { throw new Exception("Could not read script.cs file"); }
                }
                else if (type == ScriptType.Zip || type == ScriptType.Zrp)
                {
                    if (type == ScriptType.Zrp)
                    {
                        var encoded = File.OpenRead(p);
                        var key     = new byte[16];
                        var iv      = new byte[16];
                        encoded.Read(key, 0, 16);
                        encoded.Read(iv, 0, 16);

                        zrpstream = new MemoryStream();

                        using (AesManaged aes = new AesManaged())
                        {
                            ICryptoTransform decryptor = aes.CreateDecryptor(key, iv);
                            using (CryptoStream cs = new CryptoStream(encoded, decryptor, CryptoStreamMode.Read))
                            {
                                cs.CopyTo(zrpstream);
                            }
                            zrpstream.Position = 0;
                            archive            = new ZipArchive(zrpstream);
                        }
                    }
                    else
                    {
                        archive = ZipFile.OpenRead(p);
                    }
                    var files = archive.Entries.Where(e => e.Name == "script.cs").ToArray();
                    Array.Sort(files.Select(s => s.FullName.Length).ToArray(), files);
                    if (files.Length == 0)
                    {
                        throw new Exception("Could not find script.cs file");
                    }
                    var jsonfile = files[0];
                    pbase = jsonfile.FullName.Substring(0, jsonfile.FullName.Length - "script.cs".Length);
                    using (var jfile = new StreamReader(jsonfile.Open()))
                    {
                        code = jfile.ReadToEnd();
                    }
                }
                else
                {
                    if (type == ScriptType.Rar)
                    {
                        compress = RarArchive.Open(p);
                    }
                    if (type == ScriptType.SevenZip)
                    {
                        compress = SevenZipArchive.Open(p);
                    }
                    if (type == ScriptType.Tar)
                    {
                        compress = TarArchive.Open(p);
                    }

                    var files = compress.Entries.Where(e => e.Key.EndsWith("/script.cs") || e.Key == "script.cs").ToArray();
                    Array.Sort(files.Select(s => s.Key.Length).ToArray(), files);
                    if (files.Length == 0)
                    {
                        throw new Exception("Could not find script.cs file");
                    }
                    var jsonfile = files[0];
                    pbase = jsonfile.Key.Substring(0, jsonfile.Key.Length - "script.cs".Length);
                    using (var jfile = new StreamReader(jsonfile.OpenEntryStream()))
                    {
                        code = jfile.ReadToEnd();
                    }
                }

                var fc = code.Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", "");

                Dictionary <string, string> notallowed = new Dictionary <string, string>()
                {
                    { "System.IO", null },
                    { "System.Reflection", null },
                    { "Microsoft.CSharp", null },
                    { "System.Net", null },
                    { "Microsoft.VisualBasic", null },
                    { "System.Drawing", null },
                    { "System.AttributeUsage", null },
                    { "System.EnterpriseServices", null },
                    { "System.Media", null },
                    { "System.Messaging", null },
                    { "System.Printing", null },
                    { "System.Security", null },
                    { "System.ServiceModel", null },
                    { "System.ServiceProcess", null },
                    { "System.Speech", null },
                    { "System.Web", null },
                    { "System.Windows", null },
                    { "System.Xml", null },
                    { "Microsoft.Windows", null },
                    { "Microsoft.Win32", null },
                    { "Microsoft.SqlServer", null },
                    { "Microsoft.JScript", null },
                    { "Microsoft.Build", null },
                    { "Accessibility", null },
                    { "Microsoft.Activities", null },
                    { "System.Diagnostics", "random user" },
                    { "System.Runtime", "random user" },
                    { "System.Management", "random user" }
                };

                foreach (var n in notallowed)
                {
                    if (fc.Contains(n.Key))
                    {
                        if (n.Value == null)
                        {
                            throw new Exception(n.Key + " is not allowed");
                        }
                        else
                        if (fc.Contains(n.Key))
                        {
                            throw new Exception(n.Key + " is not allowed (found by " + n.Value + ")");
                        }
                    }
                }

                CompilerParameters compiler_parameters = new CompilerParameters();

                compiler_parameters.GenerateInMemory = true;

                compiler_parameters.GenerateExecutable = false;

                compiler_parameters.ReferencedAssemblies.Add(typeof(object).Assembly.Location);
                compiler_parameters.ReferencedAssemblies.Add(typeof(OpenTK.Vector2).Assembly.Location);
                compiler_parameters.ReferencedAssemblies.Add(typeof(IEnumerable <object>).Assembly.Location);
                compiler_parameters.ReferencedAssemblies.Add(typeof(LinkedList <object>).Assembly.Location);
                compiler_parameters.ReferencedAssemblies.Add(typeof(System.Drawing.Color).Assembly.Location);
                compiler_parameters.ReferencedAssemblies.Add(typeof(IO).Assembly.Location);
                compiler_parameters.ReferencedAssemblies.Add(typeof(System.Linq.Enumerable).Assembly.Location);

                compiler_parameters.CompilerOptions = "/optimize /unsafe /nostdlib";

                CompilerResults results = provider.CompileAssemblyFromSource(compiler_parameters, code);

                if (results.Errors.HasErrors)
                {
                    StringBuilder builder = new StringBuilder();
                    foreach (CompilerError error in results.Errors)
                    {
                        builder.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                    }
                    throw new Exception(String.Format("Error on line {0}:\n{1}", results.Errors[0].Line, results.Errors[0].ErrorText) + "\n" + builder.ToString());
                }

                IO.loadTexture = (path, loop, linear) =>
                {
                    var bmp    = GetBitmap(path);
                    var loaded = new Texture()
                    {
                        bitmap      = bmp,
                        path        = path,
                        width       = bmp.Width,
                        height      = bmp.Height,
                        aspectRatio = bmp.Width / (double)bmp.Height,
                        looped      = loop,
                        linear      = linear
                    };
                    script.textures.Add(loaded);
                    return(loaded);
                };

                IO.loadFont = (size, name, style, chars) =>
                {
                    var font = new Font()
                    {
                        charMap       = chars,
                        fontName      = name,
                        fontPixelSize = size,
                        fontStyle     = style
                    };
                    script.fonts.Add(font);
                    return(font);
                };

                Assembly assembly   = results.CompiledAssembly;
                var      renderType = assembly.GetType("Script");
                var      instance   = (dynamic)Activator.CreateInstance(renderType);
                script.instance   = instance;
                script.renderType = renderType;

                IO.callLoadFunction(script.instance);

                if (renderType.GetField("Description") != null)
                {
                    script.description = instance.Description;
                }
                if (renderType.GetField("Preview") != null)
                {
                    script.preview = GetBitmap(instance.Preview);
                }

                if (renderType.GetMethod("Load") == null)
                {
                    throw new Exception("Load method required");
                }
                if (renderType.GetMethod("Render") == null)
                {
                    throw new Exception("Render method required");
                }

                if (renderType.GetMethod("RenderInit") != null)
                {
                    script.hasPreRender = true;
                }
                if (renderType.GetMethod("RenderDispose") != null)
                {
                    script.hasPostRender = true;
                }

                bool hasVar(string name, Type ftype)
                {
                    if (renderType.GetField(name) != null)
                    {
                        if (ftype.IsAssignableFrom(renderType.GetField(name).FieldType))
                        {
                            return(true);
                        }
                    }
                    if (renderType.GetProperty(name) != null)
                    {
                        if (ftype.IsAssignableFrom(renderType.GetProperty(name).PropertyType))
                        {
                            return(true);
                        }
                    }
                    return(false);
                }

                if (hasVar("ManualNoteDelete", typeof(bool)))
                {
                    script.hasManualNoteDelete = true;
                }
                if (hasVar("NoteCollectorOffset", typeof(double)))
                {
                    script.hasCollectorOffset = true;
                }
                if (hasVar("NoteScreenTime", typeof(double)))
                {
                    script.hasNoteScreenTime = true;
                }
                if (hasVar("LastNoteCount", typeof(long)))
                {
                    script.hasNoteCount = true;
                }
                if (hasVar("UseProfiles", typeof(bool)))
                {
                    script.hasProfiles = script.instance.UseProfiles;
                }

                if (hasVar("SettingsUI", typeof(IEnumerable <UISetting>)))
                {
                    script.uiSettings = instance.SettingsUI;
                }
            }
            catch (Exception e)
            {
                if (e is TargetInvocationException)
                {
                    e = e.InnerException;
                }
                script.error       = true;
                script.description = e.Message;
            }
            finally
            {
                if (archive != null)
                {
                    archive.Dispose();
                }
                if (zrpstream != null)
                {
                    zrpstream.Dispose();
                }
                if (compress != null)
                {
                    compress.Dispose();
                }
            }
            return(script);
        }
Esempio n. 26
0
        public static byte[] Decrypt(byte[] cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            //RijndaelManaged aesAlg = null;
            //AesManaged aesAlg = new AesManaged();

            // Declare the string used to hold
            // the decrypted text.
            List <byte> outputData = new List <byte>();

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                // with the specified key and IV.
                //aesAlg = new RijndaelManaged();
                AesManaged aesAlg = new AesManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV  = key.GetBytes(aesAlg.BlockSize / 8);

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    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.
                        //    Convert.FromBase64String(srDecrypt.ReadToEnd());

                        //while (true)
                        //{
                        //    int b = csDecrypt.ReadByte();
                        //    if (b != -1)
                        //        outputData.Add((byte)b);
                        //    else
                        //        break;
                        //}

                        using (MemoryStream outputMemoryStream = new MemoryStream())
                        {
                            csDecrypt.CopyTo(outputMemoryStream);
                            return(outputMemoryStream.ToArray());
                        }
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                //if (aesAlg != null)
                //    aesAlg.Clear();
            }
        }
Esempio n. 27
0
        public static void Unpack(string inputFileName, string outputDirectory, byte[] key, byte[] iv)
        {
            var info = new List <string>();

            if (key.Length != 16)
            {
                throw new ApplicationException("Invalid key length");
            }
            if (iv.Length != 16)
            {
                throw new ApplicationException("Invalid IV length");
            }
            if (!File.Exists(inputFileName))
            {
                throw new ApplicationException("Input file not found");
            }


            info.Add("name " + Path.GetFileName(inputFileName));
            info.Add("key " + BitConverter.ToString(key).Replace("-", ""));
            info.Add("iv " + BitConverter.ToString(iv).Replace("-", ""));

            // decrypt
            var decryptedData = new MemoryStream();
            var aes           = new RijndaelManaged
            {
                Mode    = CipherMode.CFB,
                Key     = key,
                IV      = iv,
                Padding = PaddingMode.None
            };
            var decryptor = new NoPaddingTransformWrapper(aes.CreateDecryptor());

            using (var inputFile = File.OpenRead(inputFileName))
            {
                info.Add("original.size " + inputFile.Length);
                info.Add("original.sha256 " + HashStream(inputFile));
                using (var cryptoStream = new CryptoStream(inputFile, decryptor, CryptoStreamMode.Read))
                {
                    cryptoStream.CopyTo(decryptedData);
                }
                info.Add("decrypted.size " + decryptedData.Length);
                info.Add("decrypted.sha256 " + HashStream(decryptedData));
            }

            var outputDecryptedName = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(inputFileName)) + ".decrypted";

            File.WriteAllBytes(outputDecryptedName, decryptedData.ToArray());

            // First 4 bytes are unknown. The next 2 bytes are the zlib header 789C. After that the raw deflate data follows.
            var header = new byte[6];

            if (decryptedData.Read(header, 0, header.Length) != header.Length)
            {
                throw new IOException("Did not read the full header");
            }
            if (header[4] != 0x78 || header[5] != 0x9C)//zlib header
            {
                throw new ApplicationException("Incorrect key/iv");
            }

            decryptedData.Position = 6;

            int revision;

            // decompress using deflate
            var tempFileName = Path.Combine(outputDirectory, "TempDataCenter");

            using (var unpackedData = File.Create(tempFileName))
            {
                using (var deflateStream = new DeflateStream(decryptedData, CompressionMode.Decompress, true))
                {
                    deflateStream.CopyTo(unpackedData);
                }
                info.Add("unpacked.size " + unpackedData.Length);
                info.Add("unpacked.sha256 " + HashStream(unpackedData));

                using (var reader = new BinaryReader(unpackedData, Encoding.Unicode, true))
                {
                    unpackedData.Position = 0x0C;
                    revision = reader.ReadInt32();
                    info.Insert(1, "revision " + revision);
                }
            }
            File.WriteAllLines(Path.ChangeExtension(outputDecryptedName, revision + ".dcinfo"), info);
            File.Copy(tempFileName, Path.ChangeExtension(outputDecryptedName, revision + ".unpacked"), true);
            File.Delete(tempFileName);
            File.Delete(outputDecryptedName);
        }
Esempio n. 28
0
 private void Decrypt(Stream dataStream, Stream destinationStream, byte[] buffer)
 {
     destinationStream.SetLength(0);
     using (var cryptoStream = new CryptoStream(dataStream, decryptor, CryptoStreamMode.Read))
         cryptoStream.CopyTo(destinationStream, buffer);
 }
Esempio n. 29
0
        private void BruteForce(int currentIndex)
        {
            for (int i1 = 0; i1 < alphabet.Length; i1++)
            {
                guess[0] = alphabet[i1];

                for (int i2 = 0; i2 < alphabet.Length; i2++)
                {
                    guess[1] = alphabet[i2];

                    for (int i3 = 0; i3 < alphabet.Length; i3++)
                    {
                        guess[2] = alphabet[i3];

                        for (int i4 = 0; i4 < alphabet.Length; i4++)
                        {
                            guess[3] = alphabet[i4];

                            for (int i5 = 0; i5 < alphabet.Length; i5++)
                            {
                                guess[4] = alphabet[i5];

                                for (int i6 = 0; i6 < alphabet.Length; i6++)
                                {
                                    guess[5] = alphabet[i6];

                                    for (int i7 = 0; i7 < alphabet.Length; i7++)
                                    {
                                        guess[6] = alphabet[i7];

                                        for (int i8 = 0; i8 < alphabet.Length; i8++)
                                        {
                                            guess[7] = alphabet[i8];

                                            counter++;

                                            if (counter == 1000000)
                                            {
                                                sw.Stop();
                                                addLog(sw.Elapsed.TotalSeconds.ToString());
                                                return;
                                            }

                                            byte[] key = new UnicodeEncoding().GetBytes(guess);
                                            byte[] iv  = new UnicodeEncoding().GetBytes(guess);

                                            var rmCrypto = new RijndaelManaged();
                                            rmCrypto.Padding = PaddingMode.Zeros;
                                            var decryptor = rmCrypto.CreateDecryptor(key, iv);

                                            using (MemoryStream msCrypt = new MemoryStream(buffer))
                                            {
                                                CryptoStream cs        = new CryptoStream(msCrypt, decryptor, CryptoStreamMode.Read);
                                                var          decrypted = new MemoryStream();
                                                cs.CopyTo(decrypted);

                                                var decryptedArray = decrypted.ToArray();

                                                bool result = true;

                                                for (int j = 0; j < 4; j++)
                                                {
                                                    if (decryptedArray[j] != pdfSignature[j])
                                                    {
                                                        result = false;
                                                    }
                                                }

                                                if (result)
                                                {
                                                    password = new string(guess);
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        public static void Decrypt <TType>(String inFileName, String keyFileName, String outFileName)
            where TType : SymmetricAlgorithm, new()
        {
            Console.WriteLine("Try to decrypt data...");
            try
            {
                using (FileStream inFs = new FileStream(inFileName, FileMode.Open, FileAccess.Read))
                {
                    using (TType coder = new TType())
                    {
                        try
                        {
                            using (FileStream keyFs = new FileStream(keyFileName, FileMode.Open, FileAccess.Read))
                            {
                                using (BinaryReader str = new BinaryReader(keyFs))
                                {
                                    string base64IV = str.ReadString();
                                    coder.IV = Convert.FromBase64String(base64IV);
                                    string base64Key = str.ReadString();
                                    coder.Key = Convert.FromBase64String(base64Key);
                                }
                            }
                        }
                        catch (FileNotFoundException)
                        {
                            Console.WriteLine("ERROR!!! - can't find key file");
                            return;
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("ERROR!!! - can't read initialization vector or key, maybe wrong algorythm selected");
                            return;
                        }

                        using (ICryptoTransform transform = coder.CreateDecryptor())
                        {
                            using (CryptoStream cs = new CryptoStream(inFs, transform, CryptoStreamMode.Read))
                            {
                                using (FileStream outFs = new FileStream(outFileName, FileMode.Create, FileAccess.Write))
                                {
                                    cs.CopyTo(outFs);
                                    cs.Flush();    //necessary?
                                    outFs.Flush(); //necessary?
                                }
                            }
                        }
                    }
                }
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("ERROR!!! - encoded file is not found");
                return;
            }
            catch (Exception)
            {
                Console.WriteLine("ERROR!!! - can't decode data");
                return;
            }
            Console.WriteLine("Data successfully decrypted!");
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            //Check for bytes buffered that weren't recieved last time.
            //This operation shifts any unread data to the left, at position 0.
            long available = inputBuffer.Length - inputBuffer.Position;

            if (available > 0)
            {
                byte[] availableData = new byte[available];
                int    availableRead = inputBuffer.Read(availableData, 0, availableData.Length);

                //Check to be sure the available data is enough to fix on the stream.
                if (availableRead > 0)
                {
                    //Reset the input buffer's position and write the un-read data.
                    inputBuffer.Position = 0;
                    inputBuffer.Write(availableData, 0, availableRead);

                    //Reset the length and position to match the unread data's length.
                    inputBuffer.SetLength(availableRead);
                    inputBuffer.Position = availableRead;
                }
            }
            else
            {
                //No bytes were missed last read, reset the stream.
                inputBuffer.Position = 0;
                inputBuffer.SetLength(0);
            }

            //While we don't have enough bytes for the upper-level stream, read more from the network.
            while (inputBuffer.Length < count)
            {
                //Read in the encrypted data.
                BinaryReader binaryReader    = new BinaryReader(baseStream);
                byte[]       encryptedBuffer = Packet.ReadBytes(binaryReader);

                //Read in the HMAC and ensure the data has not been tampered.
                byte[] hmac = new byte[inputHmac.HashSize / 8];
                baseStream.Read(hmac, 0, hmac.Length);
                if (!inputHmac.ComputeHash(encryptedBuffer).SequenceEqual(hmac))
                {
                    throw new SecurityException("Recieved HMAC does not match expected cryptographic digest.");
                }

                //Create a new crypto stream around an array of bytes on the underlying stream.
                CryptoStream cryptoStream = new CryptoStream(
                    new MemoryStream(
                        encryptedBuffer
                        ),
                    symmetricKeyPair.Remote.CreateDecryptor(),
                    CryptoStreamMode.Read
                    );

                //Copy the decompressed bytes to the input buffer.
                cryptoStream.CopyTo(inputBuffer);

                //Dispose of the data.
                cryptoStream.Dispose();
            }

            //Reset the position of the input buffer, now full of fresh data.
            inputBuffer.Position = 0;

            //Return the data required by the operation to the upper-level.
            return(inputBuffer.Read(buffer, offset, count));
        }
Esempio n. 32
0
        private static void TestAesDecrypt(
            CipherMode mode,
            byte[] key,
            byte[] iv,
            byte[] encryptedBytes,
            byte[] expectedAnswer)
        {
            byte[] decryptedBytes;

            using (Aes aes = AesFactory.Create())
            {
                aes.Mode = mode;
                aes.Key = key;

                if (iv != null)
                {
                    aes.IV = iv;
                }

                using (MemoryStream input = new MemoryStream(encryptedBytes))
                using (CryptoStream cryptoStream = new CryptoStream(input, aes.CreateDecryptor(), CryptoStreamMode.Read))
                using (MemoryStream output = new MemoryStream())
                {
                    cryptoStream.CopyTo(output);
                    decryptedBytes = output.ToArray();
                }
            }

            Assert.NotEqual(encryptedBytes, decryptedBytes);
            Assert.Equal(expectedAnswer, decryptedBytes);
        }
Esempio n. 33
0
        private static void RandomKeyRoundtrip(Aes aes)
        {
            byte[] decryptedBytes;
            byte[] encryptedBytes;

            using (MemoryStream input = new MemoryStream(s_multiBlockBytes))
            using (CryptoStream cryptoStream = new CryptoStream(input, aes.CreateEncryptor(), CryptoStreamMode.Read))
            using (MemoryStream output = new MemoryStream())
            {
                cryptoStream.CopyTo(output);
                encryptedBytes = output.ToArray();
            }

            Assert.NotEqual(s_multiBlockBytes, encryptedBytes);

            using (MemoryStream input = new MemoryStream(encryptedBytes))
            using (CryptoStream cryptoStream = new CryptoStream(input, aes.CreateDecryptor(), CryptoStreamMode.Read))
            using (MemoryStream output = new MemoryStream())
            {
                cryptoStream.CopyTo(output);
                decryptedBytes = output.ToArray();
            }

            Assert.Equal(s_multiBlockBytes, decryptedBytes);
        }
Esempio n. 34
0
        public static void AesZeroPad()
        {
            byte[] decryptedBytes;
            byte[] expectedAnswer;

            using (Aes aes = AesFactory.Create())
            {
                aes.Padding = PaddingMode.Zeros;

                int blockBytes = aes.BlockSize / 8;
                int missingBytes = blockBytes - (s_multiBlockBytes.Length % blockBytes);

                // Zero-padding doesn't have enough information to remove the trailing zeroes.
                // Therefore we expect the answer of ZeroPad(s_multiBlockBytes).
                // So, make a long enough array, and copy s_multiBlockBytes to the beginning of it.
                expectedAnswer = new byte[s_multiBlockBytes.Length + missingBytes];
                Buffer.BlockCopy(s_multiBlockBytes, 0, expectedAnswer, 0, s_multiBlockBytes.Length);

                byte[] encryptedBytes;

                using (MemoryStream input = new MemoryStream(s_multiBlockBytes))
                using (CryptoStream cryptoStream = new CryptoStream(input, aes.CreateEncryptor(), CryptoStreamMode.Read))
                using (MemoryStream output = new MemoryStream())
                {
                    cryptoStream.CopyTo(output);
                    encryptedBytes = output.ToArray();
                }

                using (MemoryStream input = new MemoryStream(encryptedBytes))
                using (CryptoStream cryptoStream = new CryptoStream(input, aes.CreateDecryptor(), CryptoStreamMode.Read))
                using (MemoryStream output = new MemoryStream())
                {
                    cryptoStream.CopyTo(output);
                    decryptedBytes = output.ToArray();
                }
            }

            Assert.Equal(expectedAnswer, decryptedBytes);
        }
Esempio n. 35
0
        public static void WrongKeyFailDecrypt_2()
        {
            // The test:
            // Using the encrypted bytes from the AES-192-ECB test, try decrypting
            // with the first 192 bits from the AES-256-CBC test.  That would only work if
            // the implementation of AES was "return s_multiBlockBytes".
            // For this specific key/data combination, we actually expect a padding exception.
            byte[] encryptedBytes = new byte[]
            {
                0xC9, 0x7F, 0xA5, 0x5B, 0xC3, 0x92, 0xDC, 0xA6,
                0xE4, 0x9F, 0x2D, 0x1A, 0xEF, 0x7A, 0x27, 0x03,
                0x04, 0x9C, 0xFB, 0x56, 0x63, 0x38, 0xAE, 0x4F,
                0xDC, 0xF6, 0x36, 0x98, 0x28, 0x05, 0x32, 0xE9,
                0xF2, 0x6E, 0xEC, 0x0C, 0x04, 0x9D, 0x12, 0x17,
                0x18, 0x35, 0xD4, 0x29, 0xFC, 0x01, 0xB1, 0x20,
                0xFA, 0x30, 0xAE, 0x00, 0x53, 0xD4, 0x26, 0x25,
                0xA4, 0xFD, 0xD5, 0xE6, 0xED, 0x79, 0x35, 0x2A,
                0xE2, 0xBB, 0x95, 0x0D, 0xEF, 0x09, 0xBB, 0x6D,
                0xC5, 0xC4, 0xDB, 0x28, 0xC6, 0xF4, 0x31, 0x33,
                0x9A, 0x90, 0x12, 0x36, 0x50, 0xA0, 0xB7, 0xD1,
                0x35, 0xC4, 0xCE, 0x81, 0xE5, 0x2B, 0x85, 0x6B,
            };

            byte[] decryptedBytes;

            // Load key as the first 192 bits of s_aes256Key.
            // It has the correct cipher block size, but the wrong value.
            byte[] key = new byte[s_aes192Key.Length];
            Buffer.BlockCopy(s_aes256Key, 0, key, 0, key.Length);

            using (Aes aes = AesFactory.Create())
            {
                aes.Mode = CipherMode.ECB;
                aes.Key = key;

                Assert.Throws<CryptographicException>(() =>
                {
                    using (MemoryStream input = new MemoryStream(encryptedBytes))
                    using (CryptoStream cryptoStream = new CryptoStream(input, aes.CreateDecryptor(), CryptoStreamMode.Read))
                    using (MemoryStream output = new MemoryStream())
                    {
                        cryptoStream.CopyTo(output);
                        decryptedBytes = output.ToArray();
                    }
                });
            }
        }