Ejemplo n.º 1
0
        public async Task DecryptBufferToStreamAsync(byte[] buffer, Stream to, int bufferLength, long previousSumBlockLength,
                                                     bool isPadded, CancellationToken cancellationToken = default)
        {
            var offsetBytes = new byte[16];

            Array.Copy(BitConverter.GetBytes(previousSumBlockLength), offsetBytes, 8);

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

            if (isPadded)
            {
                aes.Padding = PaddingMode.PKCS7;
            }

            using var dec = aes.CreateDecryptor(key, newIv);
            using var ms  = new MemoryStream(buffer, 0, bufferLength);
            using var cs  = new CryptoStream(ms, dec, CryptoStreamMode.Read);

#if NET5_0
            await cs.CopyToAsync(to, cancellationToken).ConfigureAwait(false);
#else
            await cs.CopyToAsync(to).ConfigureAwait(false);
#endif
        }
Ejemplo n.º 2
0
        public async Task <object> Process(JsonDocument request, ILambdaContext context)
        {
            var s3 = new AmazonS3Client();

            // easier than doing math on the timestamps in logs
            var timer = new Stopwatch();

            timer.Start();

            context.Logger.LogLine($"{timer.Elapsed}: Getting started.");
            using var stream = (await s3.GetObjectAsync(BUCKET, AES_DATA)).ResponseStream;

            // setup a decryptor
            using var aes = AesManaged.Create();
            aes.IV        = Convert.FromBase64String("EqYoED0ag4vlPnFkWZMCog==");
            aes.Key       = Convert.FromBase64String("Sgf9NocncDHSBqMXrMthXbToAQmthMpC6eJ6Hw51Ghg=");

            using var idecrypt = aes.CreateDecryptor();
            using var cstream  = new CryptoStream(stream, idecrypt, CryptoStreamMode.Read);
            using (var output = new S3UploadStream(s3, BUCKET, OUTPUT_KEY)) {
                await cstream.CopyToAsync(output);
            }
            context.Logger.LogLine($"{timer.Elapsed}: Done copying.");
            timer.Stop();

            return(new {
                AesFile = $"s3://{BUCKET}/{AES_DATA}",
                CsvFile = $"s3://{BUCKET}/{OUTPUT_KEY}",
                Status = "ok"
            });
        }
        private static async Task DecryptDataStreamAsync(
            Stream data,
            byte[] secret,
            byte[] hash,
            Stream destination,
            CancellationToken cancellationToken
            )
        {
            FindDataKeyAndIv(secret, hash, out byte[] dataKey, out byte[] dataIv);

            using (var aes = Aes.Create())
            {
                // ReSharper disable once PossibleNullReferenceException
                aes.KeySize = 256;
                aes.Mode    = CipherMode.CBC;
                aes.Key     = dataKey;
                aes.IV      = dataIv;
                aes.Padding = PaddingMode.None;

                using (var decrypter = aes.CreateDecryptor())
                    using (CryptoStream aesStream = new CryptoStream(data, decrypter, CryptoStreamMode.Read))
                        using (var sha256 = SHA256.Create())
                            using (CryptoStream shaStream = new CryptoStream(aesStream, sha256, CryptoStreamMode.Read))
                            {
                                byte[] paddingBuffer = new byte[256];
                                int    read          = await shaStream.ReadAsync(paddingBuffer, 0, 256, cancellationToken)
                                                       .ConfigureAwait(false);

                                byte paddingLength = paddingBuffer[0];
                                if (paddingLength < 32)
                                {
                                    throw new PassportDataDecryptionException($"Data padding length is invalid: {paddingLength}.");
                                }

                                int actualDataLength = read - paddingLength;
                                if (actualDataLength < 1)
                                {
                                    throw new PassportDataDecryptionException($"Data length is invalid: {actualDataLength}.");
                                }

                                await destination.WriteAsync(paddingBuffer, paddingLength, actualDataLength, cancellationToken)
                                .ConfigureAwait(false);

                                // 81920 is the default Stream.CopyTo buffer size
                                // The overload without the buffer size does not accept a cancellation token
                                const int defaultBufferSize = 81920;
                                await shaStream.CopyToAsync(destination, defaultBufferSize, cancellationToken)
                                .ConfigureAwait(false);

                                byte[] paddedDataHash = sha256.Hash;
                                for (int i = 0; i < hash.Length; i++)
                                {
                                    if (hash[i] != paddedDataHash[i])
                                    {
                                        throw new PassportDataDecryptionException($"Data hash mismatch at position {i}.");
                                    }
                                }
                            }
            }
        }
        private async Task <byte[]> DecryptData(byte[] data, byte[] key)
        {
            using (var aes = Aes.Create())
            {
                aes.BlockSize = 128;
                aes.KeySize   = 256;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.PKCS7;

                var iv = new byte[16];

                Array.ConstrainedCopy(data, 0, iv, 0, 16);

                aes.IV  = iv;
                aes.Key = key;

                using (var inputStream = new MemoryStream(data))
                {
                    inputStream.Seek(16, SeekOrigin.Begin);

                    using (var cryptoStream = new CryptoStream(inputStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
                        using (var outputStream = new MemoryStream())
                        {
                            await cryptoStream.CopyToAsync(outputStream);

                            return(outputStream.ToArray());
                        }
                }
            }
        }
Ejemplo n.º 5
0
        public async Task <MemoryStream> DecryptFromStream(EncryptedData encryptedData, Stream stream = null)
        {
            var aesKeyDataJson =
                Encoding.UTF8.GetString(RSA.Decrypt(encryptedData.RSAEncryptedAESKey, RSAEncryptionPadding.Pkcs1));
            var aesKeyData = JsonConvert.DeserializeObject <AESKeyData>(aesKeyDataJson);

            AES.IV  = aesKeyData.IV;
            AES.Key = aesKeyData.Key;

            if (stream == null)
            {
                stream = new MemoryStream(encryptedData.AESEncryptedData);
            }

            var msDecrypt = new MemoryStream();

            using (var decryptor = AES.CreateDecryptor())
                using (var csDecrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
                {
                    await csDecrypt.CopyToAsync(msDecrypt);

                    msDecrypt.Seek(0, SeekOrigin.Begin);
                }

            return(msDecrypt);
        }
Ejemplo n.º 6
0
        public static async Task <Stream> Decrypt(string password, Stream inputStream)
        {
            var passwordBytes = Encoding.UTF8.GetBytes($"{password}");
            var hash          = SHA256.HashData(passwordBytes);

            var destination = new MemoryStream();

            using (var aes = Aes.Create())
            {
                var iv = new byte[aes.IV.Length];
                await inputStream.ReadAsync(iv.AsMemory(0, aes.IV.Length));

                aes.IV      = iv;
                aes.Key     = hash;
                aes.Mode    = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                await using var encryptedStream = new MemoryStream();
                await inputStream.CopyToAsync(encryptedStream);

                await inputStream.DisposeAsync();

                encryptedStream.Position = 0;

                using var cryptoTransform    = aes.CreateDecryptor(aes.Key, aes.IV);
                await using var cryptoStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Read);
                await cryptoStream.CopyToAsync(destination);
            }

            destination.Position = 0;
            return(destination);
        }
Ejemplo n.º 7
0
        private async Task DecryptAsync(Type symmetricAlgorithm, Byte[] symmetricKey, Stream cipherText, Stream plainText)
        {
            Contract.Requires(symmetricAlgorithm != null);
            Contract.Requires(symmetricKey != null && symmetricKey.Length > 0);
            Contract.Requires(cipherText != null);
            Contract.Requires(plainText != null);

            var algorithm = (SymmetricAlgorithm)Activator.CreateInstance(symmetricAlgorithm);
            var ivSize    = algorithm.BlockSize / 8;

            if (cipherText.Length < ivSize)
            {
                throw new ArgumentException("The cipherText specified is invalid and does not contain the initialization vector.");
            }

            cipherText.Position = 0;
            plainText.Position  = 0;

            algorithm.Key = symmetricKey;
            algorithm.IV  = CryptographyUtility.GetBytes(cipherText, ivSize);

            cipherText.Position = ivSize;

            var decryptionStream = new CryptoStream(cipherText, algorithm.CreateDecryptor(algorithm.Key, algorithm.IV), CryptoStreamMode.Read);

            await decryptionStream.CopyToAsync(plainText);

            cipherText.Position = 0;
            plainText.Position  = 0;
        }
Ejemplo n.º 8
0
        private async Task AESDecryptFileAsync(string _fileName, byte[] _key)
        {
            byte[] iv = new byte[16];

            using (Aes _aes = Aes.Create())
            {
                _aes.KeySize = 256;
                _aes.Mode    = CipherMode.CBC;

                _aes.Key = _key;


                using (FileStream openStream = File.Open($"{ _fileName}", FileMode.Open))
                {
                    await openStream.ReadAsync(iv, 0, iv.Length);

                    ICryptoTransform decryptor = _aes.CreateDecryptor(_aes.Key, iv);

                    using (CryptoStream csDecrypt = new CryptoStream(openStream, decryptor, CryptoStreamMode.Read))
                    {
                        using (FileStream createStream = File.Create($"{GetFileName(_fileName)}"))
                        {
                            await csDecrypt.CopyToAsync(createStream);
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public async Task Decrypt(string key, string input, string output)
        {
            var response = await client.GetAsync(key);

            byte[] encryptionKey = await response.Content.ReadAsByteArrayAsync();

            var outputFile = output;

            using (FileStream outputFileStream = new FileStream(outputFile, FileMode.Create))
            {
                byte[] encryptionIV = new byte[16];
                using (FileStream inputFileStream = new FileStream(input, FileMode.Open))
                {
                    using (var aes = new AesManaged {
                        Key = encryptionKey, IV = encryptionIV, Mode = CipherMode.CBC
                    })
                        using (var encryptor = aes.CreateDecryptor())
                            using (var cryptoStream = new CryptoStream(inputFileStream, encryptor, CryptoStreamMode.Read))
                            {
                                await cryptoStream.CopyToAsync(outputFileStream);
                            }
                }
            }
            File.Delete(input);
        }
 private static async Task DecryptAsync(Stream encryptedStream, ICryptoTransform decryptor, Stream decryptedStream)
 {
     // Create crypto stream
     using (CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read))
     {
         await cryptoStream.CopyToAsync(decryptedStream);
     }
 }
Ejemplo n.º 11
0
        /// <inheritdoc/>
        public async Task <uint> DetransformChunkAsync(
            Stream input,
            Stream output,
            NefsDataChunk chunk,
            uint maxOutputSize,
            NefsProgress p)
        {
            using (var detransformedStream = new MemoryStream())
            {
                // Copy chunk to temp stream
                await input.CopyPartialAsync(detransformedStream, chunk.Size, p.CancellationToken);

                detransformedStream.Seek(0, SeekOrigin.Begin);

                // Decrypt
                if (chunk.Transform.IsAesEncrypted)
                {
                    using (var aesManager = this.CreateAesManager(chunk.Transform.Aes256Key))
                        using (var cryptoStream = new CryptoStream(detransformedStream, aesManager.CreateDecryptor(), CryptoStreamMode.Read, leaveOpen: true))
                            using (var tempStream = new MemoryStream())
                            {
                                await cryptoStream.CopyToAsync(tempStream, p.CancellationToken);

                                tempStream.Seek(0, SeekOrigin.Begin);

                                detransformedStream.Seek(0, SeekOrigin.Begin);
                                await tempStream.CopyToAsync(detransformedStream, p.CancellationToken);

                                detransformedStream.Seek(0, SeekOrigin.Begin);
                                detransformedStream.SetLength(tempStream.Length);
                            }
                }

                // Decompress
                if (chunk.Transform.IsZlibCompressed)
                {
                    using (var inflater = new DeflateStream(detransformedStream, CompressionMode.Decompress, leaveOpen: true))
                        using (var tempStream = new MemoryStream())
                        {
                            await inflater.CopyToAsync(tempStream, p.CancellationToken);

                            tempStream.Seek(0, SeekOrigin.Begin);

                            detransformedStream.Seek(0, SeekOrigin.Begin);
                            await tempStream.CopyToAsync(detransformedStream, p.CancellationToken);

                            detransformedStream.Seek(0, SeekOrigin.Begin);
                            detransformedStream.SetLength(tempStream.Length);
                        }
                }

                // Copy detransformed chunk to output stream
                var chunkSize = Math.Min(detransformedStream.Length, maxOutputSize);
                await detransformedStream.CopyPartialAsync(output, chunkSize, p.CancellationToken);

                return((uint)chunkSize);
            }
        }
Ejemplo n.º 12
0
        /// <inheritdoc/>
        public async Task <UInt32> TransformChunkAsync(
            Stream input,
            UInt32 inputChunkSize,
            Stream output,
            NefsDataTransform transform,
            NefsProgress p)
        {
            using (var transformedStream = new MemoryStream())
            {
                // Copy raw chunk to temp stream
                await input.CopyPartialAsync(transformedStream, inputChunkSize, p.CancellationToken);

                transformedStream.Seek(0, SeekOrigin.Begin);

                // Compress
                if (transform.IsZlibCompressed)
                {
                    using (var tempStream = new MemoryStream())
                    {
                        await DeflateHelper.DeflateAsync(transformedStream, (int)inputChunkSize, tempStream);

                        tempStream.Seek(0, SeekOrigin.Begin);

                        transformedStream.Seek(0, SeekOrigin.Begin);
                        await tempStream.CopyPartialAsync(transformedStream, tempStream.Length, p.CancellationToken);

                        transformedStream.Seek(0, SeekOrigin.Begin);
                        transformedStream.SetLength(tempStream.Length);
                    }
                }

                // Encrypt
                if (transform.IsAesEncrypted)
                {
                    using (var aesManager = this.CreateAesManager(transform.Aes256Key))
                        using (var cryptoStream = new CryptoStream(transformedStream, aesManager.CreateEncryptor(), CryptoStreamMode.Read, leaveOpen: true))
                            using (var tempStream = new MemoryStream())
                            {
                                await cryptoStream.CopyToAsync(tempStream, p.CancellationToken);

                                tempStream.Seek(0, SeekOrigin.Begin);

                                transformedStream.Seek(0, SeekOrigin.Begin);
                                await tempStream.CopyPartialAsync(transformedStream, tempStream.Length, p.CancellationToken);

                                transformedStream.Seek(0, SeekOrigin.Begin);
                                transformedStream.SetLength(tempStream.Length);
                            }
                }

                // Copy transformed chunk to output stream
                await transformedStream.CopyToAsync(output, p.CancellationToken);

                // Return size of transformed chunk
                return((uint)transformedStream.Length);
            }
        }
Ejemplo n.º 13
0
		/// <summary>
		/// Captures page screenshot.
		/// </summary>
		/// <param name="webview">The WebView control.</param>
		/// <param name="settings">The capture settings or null.</param>
		/// <param name="targetStream">A stream to save the captured image to.</param>
		/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
		/// <returns>The task object representing the asynchronous operation.</returns>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="webview"/> or <paramref name="targetStream"/> is null.
		/// </exception>
		/// <exception cref="DevToolsProtocolException">
		/// An error occurred while trying to execute a DevTools Protocol method.
		/// </exception>
		/// <exception cref="InvalidOperationException">Other error occurred.</exception>
		public static async Task CaptureScreenshotAsync(this IChromiumWebView webview, PageCaptureSettings settings, Stream targetStream, CancellationToken cancellationToken)
		{
			if (webview is null)
				throw new ArgumentNullException(nameof(webview));

			if (targetStream is null)
				throw new ArgumentNullException(nameof(targetStream));

			CefDictionaryValue args;
			if (settings is null)
			{
				args = null;
			}
			else
			{
				args = new CefDictionaryValue();
				if (settings.Format == ImageCompressionFormat.Jpeg)
				{
					args.SetString("format", "jpeg");
					if (settings.Quality.HasValue)
						args.SetInt("quality", settings.Quality.Value);
				}
				if (!settings.FromSurface)
					args.SetBool("fromSurface", false);
				if (settings.Viewport != null)
				{
					PageViewport viewport = settings.Viewport;
					var viewportDict = new CefDictionaryValue();
					viewportDict.SetDouble("x", viewport.X);
					viewportDict.SetDouble("y", viewport.Y);
					viewportDict.SetDouble("width", viewport.Width);
					viewportDict.SetDouble("height", viewport.Height);
					viewportDict.SetDouble("scale", viewport.Scale);
					args.SetDictionary("clip", viewportDict);
				}
				if (settings.CaptureBeyondViewport)
					args.SetBool("captureBeyondViewport", true);
			}

			byte[] rv = (byte[])await ExecuteDevToolsMethodInternalAsync(webview, "Page.captureScreenshot", args, null, cancellationToken).ConfigureAwait(false);

			if (rv != null && rv.Length > 11 && rv[rv.Length - 1] == '}' && rv[rv.Length - 2] == '"'
				&& "{\"data\":\"".Equals(Encoding.ASCII.GetString(rv, 0, 9), StringComparison.Ordinal))
			{
				using (var input = new MemoryStream(rv, 9, rv.Length - 11))
				using (var base64Transform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces))
				using (var cryptoStream = new CryptoStream(input, base64Transform, CryptoStreamMode.Read))
				{
					await cryptoStream.CopyToAsync(targetStream, 4096, cancellationToken).ConfigureAwait(false);
					await targetStream.FlushAsync(cancellationToken).ConfigureAwait(false);
				}
			}
			else
			{
				throw new InvalidOperationException();
			}
		}
Ejemplo n.º 14
0
        private static async ValueTask <Stream> TransformAsync(Stream input, ICryptoTransform transform)
        {
            MemoryStream output = new MemoryStream();

            await using (CryptoStream crypto = new CryptoStream(input, transform, CryptoStreamMode.Read, true)) {
                await crypto.CopyToAsync(output);
            }

            output.Seek(0, SeekOrigin.Begin);
            return(output);
        }
Ejemplo n.º 15
0
        public async Task UnlockFromQuarantine(FileScan scan)
        {
            var path = Path.Combine(this.Directory, scan.QuarantinePath);

            try
            {
                if (scan.QuarantineState != QuarantineState.InQuarantine)
                {
                    throw new Exception($"Scan {scan.Path} is not in quarantine");
                }
                if (!File.Exists(path))
                {
                    throw new Exception($"Quarantine file {path} not found");
                }

                scan.QuarantineState = QuarantineState.Decrypting;
                this.OnScanUpdated?.Invoke(scan);

                using (FileStream outStream = new FileStream(scan.Path, FileMode.Create))
                    using (FileStream inStream = new FileStream(path, FileMode.Open))
                        using (RijndaelManaged aes = this.CreateAES())
                        {
                            File.SetAttributes(scan.Path, File.GetAttributes(path));

                            aes.IV = scan.IV;

                            var decryptor = aes.CreateDecryptor();
                            using (CryptoStream encryptStream = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read))
                            {
                                await encryptStream.CopyToAsync(outStream);
                            }

                            outStream.SetLength(scan.Size);
                        }

                File.Delete(path);

                scan.QuarantineState = QuarantineState.NotQuarantined;
                scan.QuarantinePath  = "";
            }
            catch (Exception e)
            {
                try
                {
                    File.Delete(scan.Path);
                }
                catch (IOException)
                {
                }

                scan.QuarantineState = QuarantineState.InQuarantine;
                throw e;
            }
        }
Ejemplo n.º 16
0
 private async Task <byte[]> GetDecryptedBytes(byte[] bytes)
 {
     using MemoryStream source        = new MemoryStream(bytes);
     using MemoryStream target        = new MemoryStream();
     using Aes aes                    = this.GetAes();
     using ICryptoTransform transform = aes.CreateDecryptor();
     using (CryptoStream cryptoStream = new CryptoStream(source, transform, CryptoStreamMode.Read))
     {
         await cryptoStream.CopyToAsync(target).ConfigureAwait(false);
     }
     return(target.ToArray());
 }
Ejemplo n.º 17
0
        async public static Task <byte[]> DecryptAsync(byte[] data, byte[] key, byte[] iv)
        {
            using (MemoryStream outputStream = new MemoryStream())
                using (MemoryStream inputStream = new MemoryStream(data))
                    using (Aes algorithm = Aes.Create())
                        using (ICryptoTransform decryptor = algorithm.CreateDecryptor(key, iv))
                            using (CryptoStream cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
                            {
                                await cryptoStream.CopyToAsync(outputStream);

                                return(outputStream.ToArray());
                            }
        }
Ejemplo n.º 18
0
        public static async Task Decrypt(string pass, string src, string outputDir)
        {
            byte[] iv   = new byte[16];
            string dest = null;

            try
            {
                using (Stream srcFile = File.OpenRead(src))
                {
                    await srcFile.ReadAsync(iv);

                    var    rfc = new Rfc2898DeriveBytes(pass, iv);
                    byte[] key = rfc.GetBytes(16);

                    byte[] namebytes = await ReadLenBytes(srcFile);

                    string name = DecryptString(key, iv, namebytes);

                    byte[] dateBytes = await ReadLenBytes(srcFile);

                    string   date     = DecryptString(key, iv, dateBytes);
                    DateTime fileDate = DateTime.FromBinary(long.Parse(date));
                    DateTime.SpecifyKind(fileDate, DateTimeKind.Utc);

                    // Console.WriteLine($"{src}   {fileDate}");

                    dest = Path.Combine(outputDir, name);

                    using (Stream destf = File.Create(dest))
                        using (Aes algorithm = Aes.Create())
                            using (ICryptoTransform decryptor = algorithm.CreateDecryptor(key, iv))
                                using (Stream c = new CryptoStream(srcFile, decryptor, CryptoStreamMode.Read))
                                {
                                    await c.CopyToAsync(destf);
                                }

                    File.SetCreationTimeUtc(dest, fileDate);
                    File.SetLastWriteTimeUtc(dest, fileDate);
                    File.SetLastAccessTimeUtc(dest, fileDate);
                }
            }
            catch (Exception)
            {
                if (!string.IsNullOrEmpty(dest) && File.Exists(dest))
                {
                    File.Delete(dest);
                }

                throw;
            }
        }
        /// <summary>
        /// Asynchronously decrypts data that was encrypted using <see cref="ISymmetricCryptography.EncryptWithPasswordAsync(byte[],string)"/>.
        /// </summary>
        /// <param name="encryptedBytes">The encrypted data.</param>
        /// <param name="password">The password that was used to encrypt the data.</param>
        /// <returns>The decrypted <c>byte[]</c> array.</returns>
        public async Task <byte[]> DecryptWithPasswordAsync(byte[] encryptedBytes, string password)
        {
            int encryptedBytesLength = encryptedBytes?.Length ?? 0;

            if (encryptedBytesLength <= 32 || string.IsNullOrEmpty(password))
            {
                return(Array.Empty <byte>());
            }

            byte[] salt = new byte[32];

            for (int i = 0; i < 32; i++)
            {
                salt[i] = encryptedBytes[i];
            }

            byte[] result;

            await using var output = new MemoryStream(encryptedBytesLength);
            await using var input  = new MemoryStream(encryptedBytes, 32, encryptedBytesLength - 32);

            try
            {
                using var rfc = new Rfc2898DeriveBytes(password, salt, RFC_ITERATIONS);

                using var aes = new AesManaged
                      {
                          KeySize = 256,
                          Mode    = CipherMode.CBC,
                          Padding = PaddingMode.PKCS7,
                          IV      = rfc.GetBytes(16),
                          Key     = rfc.GetBytes(32)
                      };

                using ICryptoTransform decryptor = aes.CreateDecryptor();

                await using var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read);
                await cryptoStream.CopyToAsync(output).ConfigureAwait(false);

                await cryptoStream.FlushAsync().ConfigureAwait(false);

                result = output.ToArray();
            }
            catch
            {
                result = null;
            }

            return(result);
        }
Ejemplo n.º 20
0
        public async Task <byte[]> Decrypt(Aes aes, byte[] data)
        {
            aes.Padding = PaddingMode.None;
            aes.Mode    = CipherMode.CBC;

            var crypt = aes.CreateDecryptor(aes.Key, aes.IV);

            using var outms = new MemoryStream();
            using var inms  = new MemoryStream(data);
            using var cs    = new CryptoStream(inms, crypt, CryptoStreamMode.Read);
            await cs.CopyToAsync(outms);

            return(outms.ToArray());
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Decrypt Sii unit data
        /// </summary>
        /// <param name="inputStream">Stream containing the encrypted unit data</param>
        /// /// <param name="outputStream">Output decrypted stream</param>
        /// <param name="iv">Algorithm initialization vector</param>
        public static async Task Decrypt(Stream inputStream, Stream outputStream, byte[] iv)
        {
            using (Aes aes = Aes.Create()) {
                aes.IV   = iv;
                aes.Key  = EncryptionKey;
                aes.Mode = CipherMode.CBC;

                using (ICryptoTransform t = aes.CreateDecryptor()) {
                    using (CryptoStream crys = new CryptoStream(inputStream, t, CryptoStreamMode.Read)) {
                        await crys.CopyToAsync(outputStream);
                    }
                }
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Asynchronously transforms an array of cryptographic data into its original form using AES256 in CBC mode.
 /// </summary>
 /// <param name="data">The encrypted data to transform into its original form.</param>
 /// <param name="password">The key to use during the transformation.</param>
 /// <returns>An array containing the original plaintext data.</returns>
 public static async Task <byte[]> DecryptDataAsync(byte[] data, byte[] password)
 {
     using (var original = new MemoryStream(data))
         using (var decrypted = new MemoryStream())
             using (var transform = new EtM_DecryptTransform(key: password))
             {
                 using (var crypto = new CryptoStream(original, transform, CryptoStreamMode.Read))
                     await crypto.CopyToAsync(decrypted);
                 if (!transform.IsComplete)
                 {
                     throw new Exception("Not all blocks have been decrypted.");
                 }
                 return(decrypted.ToArray());
             }
 }
        private static async Task <byte[]> Decrypt(byte[] ciphertext, byte[] key, byte[] iv)
        {
            using (var csp = new AesCryptoServiceProvider())
            {
                var decryptor = csp.CreateDecryptor(key, iv);
                using (var ciphertextStream = new MemoryStream(ciphertext))
                    using (var cryptoStream = new CryptoStream(ciphertextStream, decryptor, CryptoStreamMode.Read))
                        using (var cleartextStream = new MemoryStream())
                        {
                            await cryptoStream.CopyToAsync(cleartextStream);

                            return(cleartextStream.ToArray());
                        }
            }
        }
Ejemplo n.º 24
0
        public async Task DecryptStreamAsync(Key key, Stream sourceStream, long sourceLength, Stream destinationStream, IProgress <KryptoProgress> progress = null, CancellationToken cancellationToken = default)
        {
            DateTime started   = DateTime.Now;
            long     totalRead = 0;

            using var alg = CreateAlg(key);
            alg.IV        = await ReadBytesAsync(sourceStream, IVSize, cancellationToken).ConfigureAwait(false);

            if (progress != null)
            {
                sourceLength += alg.IV.Length;
                totalRead    += alg.IV.Length;
                progress.Report(new KryptoProgress(started, totalRead, sourceLength, false));
            }

            using var decryptor = alg.CreateDecryptor();
            using var cs        = new CryptoStream(sourceStream, decryptor, CryptoStreamMode.Read, true);

            if (progress == null)
            {
                await cs.CopyToAsync(destinationStream, Utilities.BUFFER_SIZE, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                byte[] buffer = new byte[Utilities.BUFFER_SIZE];
                int    bytesRead;
                do
                {
#if NET472
                    bytesRead = await cs.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
#else
                    bytesRead = await cs.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken).ConfigureAwait(false);
#endif
                    if (bytesRead > 0)
                    {
#if NET472
                        await destinationStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
#else
                        await destinationStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false);
#endif
                        totalRead += bytesRead;
                        progress?.Report(new KryptoProgress(started, totalRead, sourceLength, false));
                    }
                } while (bytesRead > 0);
            }

            progress?.Report(new KryptoProgress(started, totalRead, totalRead, true));
        }
Ejemplo n.º 25
0
        public async Task <FileStreamResult> DownloadFile(string filename)
        {
            var decuploads = Path.Combine(_environment.WebRootPath, "uploads\\decrypted");
            var encuploads = Path.Combine(_environment.WebRootPath, "uploads\\encrypted");

            if (!Directory.Exists(decuploads))
            {
                Directory.CreateDirectory(decuploads);
            }
            string fileName      = filename;
            int    keySize       = Constants.EncryptionKeys.keySize;
            string hashAlgorithm = Constants.EncryptionKeys.hashAlgorithm;
            string passPhrase    = Constants.EncryptionKeys.passPhrase;
            string saltValue     = Constants.EncryptionKeys.saltValue;
            string initVector    = Constants.EncryptionKeys.initVector;

            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);


            var _password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, 2);

            byte[]          keyBytes = _password.GetBytes(keySize / 8);
            UnicodeEncoding UE       = new UnicodeEncoding();
            RijndaelManaged RMCrypto = new RijndaelManaged();

            RMCrypto.Mode = CipherMode.CBC;
            try
            {
                var memory = new MemoryStream();
                using (FileStream fsCrypt = new FileStream(Path.Combine(encuploads, fileName), FileMode.Open))
                {
                    using (CryptoStream cs = new CryptoStream(fsCrypt,
                                                              RMCrypto.CreateDecryptor(keyBytes, initVectorBytes), CryptoStreamMode.Read))
                    {
                        await cs.CopyToAsync(memory);
                    }
                }
                string contentType = GlobalCode.GetContentType(Path.Combine(encuploads, fileName));
                memory.Position = 0;
                return(File(memory, contentType, fileName));
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Encryption failed!", "Error");
            }
            return(null);
        }
        public async Task <byte[]> Decrypt(CancellationToken ct, string keyName, byte[] data)
        {
            if (this.Log().IsEnabled(LogLevel.Debug))
            {
                this.Log().Debug($"Decrypting the fingerprint (key name: '{keyName}').");
            }

            keyName.Validation().NotNullOrEmpty(nameof(keyName));
            data.Validation().NotNull(nameof(data));
            data.Validation().IsTrue(array => array.Length >= 32, nameof(data), "Data is invalid.");

            await AssertIsEnabled(ct);

            using (await _asyncLock.LockAsync(ct))
            {
                using (Aes aes = Aes.Create())
                {
                    aes.BlockSize = 128;
                    aes.KeySize   = 256;
                    aes.Mode      = CipherMode.CBC;
                    aes.Padding   = PaddingMode.PKCS7;

                    var iv = new byte[16];
                    Array.ConstrainedCopy(data, 0, iv, 0, 16);

                    aes.IV  = iv;
                    aes.Key = RetrieveKey(keyName);

                    using (var ms = new MemoryStream(data))
                        using (var outputStream = new MemoryStream())
                            using (var cryptoStream = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
                            {
                                ms.Seek(16, SeekOrigin.Begin);

                                await cryptoStream.CopyToAsync(outputStream, 81920, ct);

                                if (this.Log().IsEnabled(LogLevel.Information))
                                {
                                    this.Log().Info($"Successfully decrypted the fingerprint (key name: '{keyName}').");
                                }

                                return(outputStream.ToArray());
                            }
                }
            }
        }
Ejemplo n.º 27
0
        public async Task <byte[]> EncryptAsync(Stream clearStream)
        {
            using TripleDES des = TripleDES.Create();
            var pdb = new Rfc2898DeriveBytes(encryptionKey.ToInsecureString(),
                                             salt);

            des.Key      = pdb.GetBytes(keySize);
            des.IV       = pdb.GetBytes(ivSize);
            using var cs = new CryptoStream(clearStream,
                                            des.CreateEncryptor(),
                                            CryptoStreamMode.Read);
            using var br = new BinaryReader(cs);
            using var ms = new MemoryStream();
            await cs.CopyToAsync(ms);

            cs.Close();
            return(ms.ToArray());
        }
        internal virtual async Task <string> GetBase64EncodedBlobAsync(string blobUrl, CancellationToken cancellationToken)
        {
            var blobServiceClient = this.azureClientFactory.CreateClient(FacadeStartup.WebJobsStorageClientName);
            var blobUri           = new BlobUriBuilder(new Uri(blobUrl));

            using var blobStream = await blobServiceClient.GetBlobContainerClient(blobUri.BlobContainerName)
                                   .GetBlobClient(blobUri.BlobName)
                                   .OpenReadAsync(new BlobOpenReadOptions(false), cancellationToken);

            using var base64transform = new ToBase64Transform();
            using var base64Stream    = new CryptoStream(blobStream, base64transform, CryptoStreamMode.Read);
            using var memoryStream    = new MemoryStream();
            using var reader          = new StreamReader(memoryStream);
            await base64Stream.CopyToAsync(memoryStream, cancellationToken);

            _ = memoryStream.Seek(0, SeekOrigin.Begin);
            return(await reader.ReadToEndAsync());
        }
Ejemplo n.º 29
0
        static async Task DecryptAsync(string fileIn, string key, string fileOut)
        {
            var binaryKey = new byte[8];

            for (int i = 0; i < binaryKey.Length; i++)
            {
                binaryKey[i] = byte.Parse(key.Substring(i * 2, 2), NumberStyles.HexNumber);
            }

            using var des       = DES.Create();
            using var decryptor = des.CreateDecryptor(binaryKey, binaryKey);

            using var streamIn  = new FileStream(fileIn, FileMode.Open);
            using var streamOut = new FileStream(fileOut, FileMode.Create);

            using var decryptedStream = new CryptoStream(streamIn, decryptor, CryptoStreamMode.Read);
            await decryptedStream.CopyToAsync(streamOut);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Decrypts an array of data and returns the decrypted array
        /// </summary>
        /// <param name="data">The data to decrypt</param>
        /// <param name="encryptionKey">The secret value to decrypt the data with</param>
        /// <returns>Returns an array of decrypted bytes</returns>
        public static async Task <byte[]> DecryptDataAsync(byte[] data, byte[] encryptionKey)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (data.Length < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(data.Length));
            }
            if (encryptionKey == null)
            {
                throw new ArgumentNullException(nameof(encryptionKey));
            }
            if (encryptionKey.Length < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(encryptionKey));
            }

            byte[] result;
            byte[] iv = new byte[IV_SIZE_IN_BYTES];
            Array.Copy(data, iv, iv.Length);

            using (SymmetricAlgorithm alg = CreateAlgorithm(encryptionKey))
            {
                // Set the initialization vector
                alg.IV = iv;

                using (ICryptoTransform decryptor = alg.CreateDecryptor(encryptionKey, iv))
                    using (MemoryStream decrypted = new MemoryStream())
                    {
                        using (MemoryStream encrypted = new MemoryStream(data, IV_SIZE_IN_BYTES, data.Length - IV_SIZE_IN_BYTES))
                            using (CryptoStream crypto = new CryptoStream(encrypted, decryptor, CryptoStreamMode.Read))
                            {
                                await crypto.CopyToAsync(decrypted);
                            }

                        result = decrypted.ToArray();
                    }
            }

            return(result);
        }