public void GivenRandomData_WhenEncryptingData_ThenSessionKeyIsReturned()
        {
            var currentUser = WindowsIdentity.GetCurrent()
                              .Name;

            var target = new RSAEncryption("target", currentUser);

            new RSAEncryption("signatureContainer", currentUser);
            var targetPublicKey = target.ExportKey(false);

            HybridEncryption hybridEncryption = HybridEncryption.CreateEncryption(targetPublicKey, "signatureContainer");

            RandomNumberGenerator random = new RNGCryptoServiceProvider();

            var data       = new byte[512];
            var sessionKey = new byte[32];
            var iv         = new byte[16];

            random.GetBytes(sessionKey);
            random.GetBytes(iv);
            random.GetBytes(data);

            var encryptedResult = hybridEncryption.EncryptData(sessionKey, data, iv);

            Assert.That(encryptedResult.key.SessionKey, Is.Not.Empty);
        }
Exemple #2
0
        public EncryptedPacket EncryptSoapBody(string original, RsaWithRsaParameterKey keys)
        {
            var hybrid         = new HybridEncryption();
            var encryptedBlock = hybrid.EncryptData(Encoding.UTF8.GetBytes(original), keys);

            return(encryptedBlock);
        }
        public void GivenEncryptingData_WhenDecryptingData_FromImportedKey_ThenDataIsDecrypted()
        {
            var currentUser = WindowsIdentity.GetCurrent()
                              .Name;

            var target             = new RSAEncryption("target", currentUser);
            var signatureContainer = new RSAEncryption("signatureContainer", currentUser);
            var signaturePublicKey = signatureContainer.ExportKey(false);
            var targetPublicKey    = target.ExportKey(false);

            HybridEncryption hybridEncryption = HybridEncryption.CreateEncryption(targetPublicKey, "signatureContainer");
            HybridDecryption hybridDecryption = HybridDecryption.CreateDecryption("target", signaturePublicKey);

            RandomNumberGenerator random = new RNGCryptoServiceProvider();

            var data       = new byte[512];
            var sessionKey = new byte[32];
            var iv         = new byte[16];

            random.GetBytes(sessionKey);
            random.GetBytes(iv);
            random.GetBytes(data);

            (EncryptionSettings key, byte[] encryptedData)encryptedResult = hybridEncryption.EncryptData(sessionKey, data, iv);

            var keyBlob = encryptedResult.key.ExportToBlob();

            var keyFromBlob = EncryptionSettings.FromBlob(keyBlob);

            var decryptedData = hybridDecryption.DecryptData(keyFromBlob, encryptedResult.encryptedData);

            Assert.That(decryptedData, Is.EqualTo(data));
        }
        private async void EncryptMessageButton_Click(object sender, RoutedEventArgs e)
        {
            StatusImage.Visibility    = Visibility.Hidden;
            ErrorTextBlock.Visibility = Visibility.Hidden;

            if (UserInputRSADetails())
            {
                return;
            }

            // ask user for location to save encrypted message
            string encryptedFile = null;

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Title  = "Save as";
            saveFileDialog.Filter = "Encrypted message (*.crypto)|*.crypto";

            if (saveFileDialog.ShowDialog() == true)
            {
                encryptedFile = saveFileDialog.FileName;
            }

            // only open filestreams if files were selected by user
            if (encryptedFile != null)
            {
                // open streams
                MemoryStream inputStream  = new MemoryStream();
                byte[]       messageBytes = Encoding.UTF8.GetBytes(InputMessageBox.Text);
                inputStream.Write(messageBytes, 0, messageBytes.Length);

                // message requires a minimum length, pad it with 32 0x00 bytes
                if (inputStream.Length < 32)
                {
                    inputStream.Write(new byte[32], 0, 32);
                }

                inputStream.Position = inputStream.Seek(0, SeekOrigin.Begin);
                FileStream outputStream = null;

                try
                {
                    outputStream = File.OpenWrite(encryptedFile);

                    await HybridEncryption.EncryptFile(inputStream, outputStream, AsymmetricEncryption.PublicKeyFromXml(PublicRSAKeyReceiver.Text));

                    MessageBox.Show("Done");
                }
                catch (IOException exception)
                {
                    ErrorTextBlock.Visibility = Visibility.Visible;
                    ErrorTextBlock.Text       = exception.Message;
                }
                finally
                {
                    inputStream?.Close();
                    outputStream?.Close();
                }
            }
        }
Exemple #5
0
        public void EncryptMultipleKeys()
        {
            #region Arrange

            var ecKeyPairInfos      = Encryption.NitroKey.EllipticCurveCryptographer.GetEcKeyPairInfos();
            var encryptionParameter = new HybridEncryption.EncryptionParameter
            {
                PublicKeys = ecKeyPairInfos.Select(info => info.PublicKey.ExportPublicKey()),
            };

            #endregion

            #region Act

            using (var input = File.OpenRead(this.InputFile))
                using (var output = File.Create(this.OutputFile))
                {
                    HybridEncryption.Encrypt(input, output, encryptionParameter);
                }

            #endregion

            #region Assert

            Assert.That(FileOperation.HasFileSignature(this.OutputFile), "HasFileSignature");
            Assert.Pass("No Exception occur");

            #endregion
        }
        public void GivenEncryptionKeyBlob_WhenImportingKey_ThenImportsSessionKeyCorrectly()
        {
            var currentUser = WindowsIdentity.GetCurrent()
                              .Name;

            var target = new RSAEncryption("target", currentUser);

            new RSAEncryption("signatureContainer", currentUser);
            var targetPublicKey = target.ExportKey(false);

            HybridEncryption hybridEncryption = HybridEncryption.CreateEncryption(targetPublicKey, "signatureContainer");

            RandomNumberGenerator random = new RNGCryptoServiceProvider();

            var data       = File.ReadAllBytes("appsettings.json");
            var sessionKey = new byte[32];
            var iv         = new byte[16];

            random.GetBytes(sessionKey);
            random.GetBytes(iv);

            (EncryptionSettings key, byte[] encryptedData)encryptedResult = hybridEncryption.EncryptData(sessionKey, data, iv);

            var key = encryptedResult.key;

            var keyBlob = key.ExportToBlob();

            var keyFromBlob = EncryptionSettings.FromBlob(keyBlob);

            Assert.That(keyFromBlob.SessionKey, Is.EqualTo(key.SessionKey));
        }
Exemple #7
0
        public void EncryptMultipleKeys()
        {
            #region Arrange

            var alice    = EllipticCurveCryptographer.CreateKeyPair(true);
            var bob      = EllipticCurveCryptographer.CreateKeyPair(true);
            var guenther = EllipticCurveCryptographer.CreateKeyPair(true);

            var paramter = new HybridEncryption.EncryptionParameter()
            {
                PublicKeys = new[] { alice, bob, guenther }
            };

            #endregion

            #region Act

            using (var input = File.OpenRead(this.InputFile))
                using (var output = File.Create(this.OutputFile))
                {
                    HybridEncryption.Encrypt(input, output, paramter);
                }

            #endregion

            #region Assert

            Assert.That(FileOperation.HasFileSignature(this.OutputFile), "HasFileSignature");
            Assert.Pass("No Exception occur");

            #endregion
        }
 public void SetUp()
 {
     _startText  = "Text to be Encrypted !!";
     _hybrid     = new HybridEncryption();
     _certForMVR = new X509Certificate2("D:\\Projects\\Interop\\InteropCC\\Documents\\KORVCCB.p12", "exMF5WW9", X509KeyStorageFlags.Exportable);
     _certForUJP = new X509Certificate2("D:\\Projects\\Interop\\InteropCC\\Documents\\KORVCCA.p12", "5Aqy9GwE", X509KeyStorageFlags.Exportable);
 }
Exemple #9
0
        public void EncryptIsCanceled()
        {
            #region Arrange

            var alice = EllipticCurveCryptographer.CreateKeyPair(true);

            var progressValues = new List <double>();
            var multiplier     = 10;

            var paramter = new HybridEncryption.EncryptionParameter()
            {
                PublicKeys = new[] { alice },
                Progress   = d => progressValues.Add(d),
                IsCanceled = () => true,
            };

            #endregion

            #region Act

            using (var input = new MemoryStream(new byte[SymmetricEncryption.BufferSize * multiplier]))
                using (var output = File.Create(this.OutputFile))
                {
                    HybridEncryption.Encrypt(input, output, paramter);
                }

            #endregion

            #region Assert

            Assert.That(progressValues.Count, Is.EqualTo(0));

            #endregion
        }
Exemple #10
0
        public void HybridEncryption_FilePath()
        {
            var myPrivateKeyJson = @"
{
   ""PrivateKey"":""NquxhQX9cmWkyDulDIm6OEzty5roXQHApdJInL4gPQbmkXqrVBHhkA=="",
   ""PublicKey"":{
      ""Qx"":""tS37fNpfdy5diNusCoalxUn0HOdjqJk2OybUA9jy8HnzCSg0rFi3bA=="",
      ""Qy"":""sYIRXtP1j3tspMyJOeuCDdG4Ifm3DKC+yIHOFyLUTt8R4z0OxWpLqg==""
   },
   ""InculdePrivateKey"":true
}
";
            var myPrivateKey     = EcKeyPair.FromJson(myPrivateKeyJson);
            var bobPublicAns1Key = EcKeyPair.CreateFromAnsi(Convert.FromBase64String("BFEECnHOtY1L3He8vwsH0ahiDZZzavjxZzciXYXrzaNP1Zn/x1sL+4lvOpktdaZSjgWH/X2JI1rAqBVl7NO3R0UWJ4WtKnrGa5IhSiW0oC7s2lU="));

            File.WriteAllText(this.InputFile, "My Stuff");

            var encryptionParameter = new HybridEncryption.EncryptionParameter
            {
                PublicKeys = new[] { myPrivateKey.ExportPublicKey(), bobPublicAns1Key.ExportPublicKey() },
            };

            HybridEncryption.Encrypt(this.InputFile, this.EncryptedFile, encryptionParameter);

            var decryptionParameter = new HybridEncryption.DecryptionParameter
            {
                PrivateKey = myPrivateKey,
            };
            var info = HybridEncryption.Decrypt(this.EncryptedFile, this.PlainFile, decryptionParameter);

            Console.Out.WriteLine(info.FileName);
            Console.Out.WriteLine(File.ReadAllText(this.PlainFile));
        }
        private async void EncryptCommandHandling()
        {
            this.IsBusy = true;

            await Task.Run(() =>
            {
                var targetPath = this.HideFilename
                    ? Path.Combine(Path.GetDirectoryName(this.FilePath), $"{Guid.NewGuid()}.enc")
                    : $"{this.FilePath}.enc";

                using (var input = File.OpenRead(this.FilePath))
                    using (var output = File.Create(targetPath))
                    {
                        var selectedPublicKeys = this.PublicKeys.Where(model => model.IsSelected).Select(model => model.KeyPairInfos.PublicKey.ExportPublicKey());

                        HybridEncryption.Encrypt(input, output, new HybridEncryption.EncryptionParameter
                        {
                            Progress   = this.ReportProgress,
                            IsCanceled = () => this.IsCanceled,
                            PublicKeys = selectedPublicKeys,
                            Filename   = Path.GetFileName(this.FilePath),
                        });
                    }
            });

            this.IsBusy = false;
        }
        /// <summary>
        /// Decrypt received file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DownloadButton_Click(object sender, RoutedEventArgs e)
        {
            // TODO: select a place to save
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Title = "Save as"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                FileStream   outputStream = null;
                MemoryStream memoryStream = null;

                try
                {
                    outputStream = new FileStream(saveFileDialog.FileName, FileMode.CreateNew, FileAccess.Write);

                    if (sender is Button button)
                    {
                        if (button.DataContext is Message message)
                        {
                            // convert packet to memoryStream
                            memoryStream = new MemoryStream(message.Packet.EncryptedData.Length + 2_000);

                            memoryStream.Write(new byte[] { (byte)message.Packet.DataType }, 0, 1);

                            memoryStream.Write(BitConverter.GetBytes((ushort)message.Packet.EncryptedSessionKey.Length), 0, 2);
                            memoryStream.Write(message.Packet.EncryptedSessionKey, 0, message.Packet.EncryptedSessionKey.Length);

                            memoryStream.Write(message.Packet.Iv, 0, message.Packet.Iv.Length);
                            memoryStream.Write(message.Packet.Hmac, 0, message.Packet.Hmac.Length);
                            memoryStream.Write(message.Packet.Signature, 0, message.Packet.Signature.Length);
                            await memoryStream.WriteAsync(message.Packet.EncryptedData, 0, message.Packet.EncryptedData.Length).ConfigureAwait(false);

                            try
                            {
                                await HybridEncryption.DecryptFile(memoryStream, outputStream, AsymmetricEncryption.PublicKeyFromXml(message.Sender.PublicKey)).ConfigureAwait(false);

                                await outputStream.FlushAsync().ConfigureAwait(false);
                            }
                            catch (CryptoException exception)
                            {
                                ErrorText = exception.Message;
                                MessageBox.Show(exception.Message);
                            }
                        }
                    }
                }
                catch (IOException exception)
                {
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    outputStream?.Close();
                    memoryStream?.Close();
                }
            }
        }
        public void Decrypt_Should_Throw_Crypto_Exception_If_Encrypted_Data_Was_Changed()
        {
            EncryptedPacket packet = ValidMessagePacket;

            packet.EncryptedData = new byte[256];

            Assert.That(() => { HybridEncryption.Decrypt(packet, asymmetricPublicKey); }, Throws.InstanceOf(typeof(CryptoException)));
        }
        public void Encrypt_Should_Throw_Crypto_Exception_If_RSA_Public_Key_Is_Invalid()
        {
            byte[] fileBytes = Random.GetNumbers(2048);

            asymmetricPublicKey.Modulus = new byte[1];

            Assert.That(() => { HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey); }, Throws.InstanceOf(typeof(CryptoException)));
        }
        public void Can_Recover_Encrypted_File()
        {
            byte[]          fileBytes       = Random.GetNumbers(2048);
            EncryptedPacket encryptedPacket = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            byte[] decryptedBytes = HybridEncryption.Decrypt(encryptedPacket, asymmetricPublicKey);

            CollectionAssert.AreEqual(fileBytes, decryptedBytes);
        }
        public void Encryption_Generates_Different_Hmac_Each_Time()
        {
            byte[] fileBytes = Random.GetNumbers(2048);

            EncryptedPacket encryptedPacket1 = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);
            EncryptedPacket encryptedPacket2 = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            CollectionAssert.AreNotEqual(encryptedPacket1.Hmac, encryptedPacket2.Hmac);
        }
        public void Encryption_Generates_New_Aes_Key_Each_Time()
        {
            byte[] fileBytes = Random.GetNumbers(2048);

            EncryptedPacket encryptedPacket1 = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);
            EncryptedPacket encryptedPacket2 = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            CollectionAssert.AreNotEqual(encryptedPacket1.EncryptedSessionKey, encryptedPacket2.EncryptedSessionKey);
        }
Exemple #18
0
        private (SessionKeyContainer key, byte[] encryptedData) EncryptFile(string signatureContainer, string secretsettingsJson, string encryptionKey)
        {
            HybridEncryption encryption = HybridEncryption.Create(encryptionKey, signatureContainer);

            var symmetricKey = CreateSymmetricKey();

            (SessionKeyContainer key, byte[] encryptedData)kvp = encryption.EncryptData(symmetricKey.SessionKey,
                                                                                        File.ReadAllBytes(secretsettingsJson),
                                                                                        symmetricKey.Iv);
            return(kvp);
        }
        public void Can_Encrypt_Stream_Of_Data()
        {
            byte[] fileBytes = Random.GetNumbers(2048);

            MemoryStream inputStream = new MemoryStream(fileBytes);

            EncryptedPacket encryptedPacket = HybridEncryption.EncryptFile(inputStream, asymmetricPublicKey);

            Assert.NotNull(encryptedPacket);
            CollectionAssert.AreNotEqual(fileBytes, encryptedPacket.EncryptedData);
        }
Exemple #20
0
        public void Encrypt()
        {
            var data = "P@ssw0rd";

            var keys      = HybridEncryption.GenerateKeys();
            var encrypted = HybridEncryption.Encrypt(data, keys.PublicKey);
            var decrypted = HybridEncryption.Decrypt(encrypted, keys.KeysPair);

            Console.WriteLine(encrypted);
            Assert.AreEqual(data, decrypted);
        }
        public void Can_Recover_Encrypted_Message()
        {
            string inputString = "This is another test string";

            byte[]          messageBytes    = Encoding.UTF8.GetBytes(inputString);
            EncryptedPacket encryptedPacket = HybridEncryption.Encrypt(DataType.Message, messageBytes, asymmetricPublicKey);

            byte[] decryptedBytes   = HybridEncryption.Decrypt(encryptedPacket, asymmetricPublicKey);
            string decryptedMessage = Encoding.UTF8.GetString(decryptedBytes);

            Assert.AreEqual(inputString, decryptedMessage);
        }
        public void Decryption_Throws_CryptoException_When_Hmac_Differs()
        {
            byte[] fileBytes = Random.GetNumbers(2048);

            EncryptedPacket encryptedPacket = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            encryptedPacket.Hmac[25] = (byte)((encryptedPacket.Hmac[25] + 1) % 255);

            Assert.Throws(typeof(CryptoException), () =>
            {
                HybridEncryption.Decrypt(encryptedPacket, asymmetricPublicKey);
            });
        }
        /// <summary>
        /// Send a new message
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SendButton_Click(object sender, RoutedEventArgs e)
        {
            ContactPerson contact = (ContactPerson)ContactListListView.SelectedItem;

            if (contact == null)
            {
                return;
            }

            EncryptedPacket packetForReceiver = null, packetForSender = null;
            string          text = MessageTextBox.Text;
            await Task.Run(() =>
            {
                try
                {
                    packetForReceiver = HybridEncryption.Encrypt(DataType.Message, Encoding.UTF8.GetBytes(text), AsymmetricEncryption.PublicKeyFromXml(contact.PublicKey));
                    packetForSender   = HybridEncryption.Encrypt(DataType.Message, Encoding.UTF8.GetBytes(text), AsymmetricEncryption.PublicKey);
                }
                catch (CryptoException exception)
                {
                    ErrorText = exception.Message;
                }
            });

            // try to send message and clear input
            if (packetForReceiver != null && packetForSender != null)
            {
                try
                {
                    // send to server
                    await Client.SendNewMessage(packetForReceiver, contact.Id, true);

                    await Client.SendNewMessage(packetForSender, contact.Id, false);

                    // add to chat
                    contact.Messages.Add(new Message
                    {
                        SenderName        = Client.UserName,
                        SendTime          = DateTime.Now,
                        MessageFromSender = MessageTextBox.Text,
                        DataType          = DataType.Message
                    });
                    MessageTextBox.Clear();
                }
                catch (ClientException exception)
                {
                    // show message to user
                    ErrorText = exception.Message;
                }
            }
        }
        public void EncryptedData_WithKey_IsSuccessfullyDecrypted()
        {
            // Arrange
            var message = "my super secret message";
            var keyPair = AsymmetricEncryption.GenerateKey(32);

            // Act
            var encryptedData = HybridEncryption.Encrypt(message, keyPair.PublicKey);
            var decryptedData = HybridEncryption.DecryptValue(encryptedData.EncryptedData, keyPair.PrivateKey, encryptedData.EncryptedKey, encryptedData.InitializationVector);

            // Assert
            Assert.Equal(message, decryptedData);
            Assert.NotEqual(encryptedData.EncryptedData, System.Text.Encoding.UTF8.GetBytes(message));
        }
        public void Can_Encrypt_Big_File()
        {
            byte[] fileBytes = Random.GetNumbers(5_889_614);

            EncryptedPacket encryptedPacket = null;

            Assert.DoesNotThrow(() =>
            {
                encryptedPacket = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);
            });

            Assert.NotNull(encryptedPacket);
            Assert.That(encryptedPacket.DataType, Is.EqualTo(DataType.File), "EncryptedPacket DataType property not set correctly");
        }
        public void Can_Encrypt_Message()
        {
            byte[] messageBytes = Encoding.UTF8.GetBytes("This is a test string");

            EncryptedPacket encryptedPacket = null;

            Assert.DoesNotThrow(() =>
            {
                encryptedPacket = HybridEncryption.Encrypt(DataType.Message, messageBytes, asymmetricPublicKey);
            });

            Assert.NotNull(encryptedPacket);
            Assert.That(encryptedPacket.DataType, Is.EqualTo(DataType.Message), "EncryptedPacket DataType property not set correctly");
        }
        public void Can_Encrypt_Steganography_File()
        {
            byte[] fileBytes = Random.GetNumbers(2_726_403);

            EncryptedPacket encryptedPacket = null;

            Assert.DoesNotThrow(() =>
            {
                encryptedPacket = HybridEncryption.Encrypt(DataType.Steganography, fileBytes, asymmetricPublicKey);
            });

            Assert.NotNull(encryptedPacket);
            Assert.That(encryptedPacket.DataType, Is.EqualTo(DataType.Steganography), "EncryptedPacket DataType property not set correctly");
        }
Exemple #28
0
        public string DecryptSoapBody(byte[] encryptedData, byte[] sessionKey, byte[] iVector, RsaWithRsaParameterKey rsaParams)
        {
            var encryptedBlock = new EncryptedPacket();

            encryptedBlock.EncryptedData       = encryptedData;
            encryptedBlock.EncryptedSessionKey = sessionKey;
            encryptedBlock.Iv        = iVector;
            encryptedBlock.RsaParams = rsaParams;

            var hybrid          = new HybridEncryption();
            var decrpyted       = hybrid.DecryptData(encryptedBlock, encryptedBlock.RsaParams);
            var decryptedString = Encoding.UTF8.GetString(decrpyted);

            return(decryptedString);
        }
Exemple #29
0
        public void EncryptAndDecrypt()
        {
            #region Arrange

            var alice = EllipticCurveCryptographer.CreateKeyPair(true);

            var encryptionParameter = new HybridEncryption.EncryptionParameter()
            {
                PublicKeys = new[] { alice.ExportPublicKey() },
            };

            var decryptionParameter = new HybridEncryption.DecryptionParameter()
            {
                PrivateKey = alice,
            };

            #endregion

            #region Act

            using (var input = File.OpenRead(this.InputFile))
                using (var output = File.Create(this.OutputFile))
                {
                    HybridEncryption.Encrypt(input, output, encryptionParameter);
                }

            using (var input = File.OpenRead(this.OutputFile))
                using (var output = File.Create(this.ResultFile))
                {
                    HybridEncryption.Decrypt(input, output, decryptionParameter);
                }

            #endregion

            #region Assert

            var inputData  = File.ReadAllBytes(this.InputFile);
            var outputData = File.ReadAllBytes(this.OutputFile);
            var resultData = File.ReadAllBytes(this.ResultFile);

            Assert.That(FileOperation.HasFileSignature(this.OutputFile), "HasFileSignature");
            Assert.That(inputData.Length, Is.LessThan(outputData.Length), "Input file is smaller than output file");
            Assert.That(outputData, Is.Not.EquivalentTo(resultData), "Encrypted file is not equal to plain file");
            Assert.That(inputData.Length, Is.EqualTo(resultData.Length), "size of plain file is equal to encrypted file");
            Assert.That(inputData, Is.EquivalentTo(resultData), "plain file is equal to encrypted file");

            #endregion
        }
        public void EncryptedData_WithModifiedHMAC_IsNotSuccessfullyDecrypted()
        {
            // Arrange
            var message = "my super secret message";
            var keyPair = AsymmetricEncryption.GenerateKey(32);

            var encryptedData = HybridEncryption.Encrypt(message, keyPair.PublicKey);

            encryptedData.Hmac[1] = byte.MaxValue;

            // Act
            var exception = Assert.ThrowsAny <System.Security.Cryptography.CryptographicException>(() => { HybridEncryption.DecryptValue(encryptedData.EncryptedData, keyPair.PrivateKey, encryptedData.EncryptedKey, encryptedData.InitializationVector, encryptedData.Hmac); });

            // Assert
            Assert.Contains("HMAC for decryption does not match encrypted packet", exception.Message);
        }
		static void Main()
		{
			//const string original = "Very secret and important information that can not fall into the wrong hands.";
			//string original = new String('0', 127);
			string original = "abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrs";
			original = GenerateRandomText();
			//string original = "abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890";
			//string original = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam non dictum diam. Donec feugiat libero sed arcu interdum consectetur vitae amet.";
			//string original = @"?=??Y@쳘?{?? &긳 ? v ? ";

			var hybrid = new HybridEncryption();

			var rsaParams = new RSAWithRSAParameterKey();
			rsaParams.ImportKeys();

			var digitalSignature = new DigitalSignature();
			digitalSignature.AssignNewKey();

			Console.WriteLine("Hybrid Encryption with Integrity Check Demonstration in .NET");
			Console.WriteLine("------------------------------------------------------------");
			Console.WriteLine();

			try
			{
				var originalData = Encoding.UTF8.GetBytes(original);

				byte[] compressedBytes = Compress(originalData);
				byte[] decompressedBytes = Decompress(compressedBytes);

				var encryptedBlock = hybrid.EncryptData(
					originalData, rsaParams, digitalSignature);

				var decrpyted = hybrid.DecryptData(encryptedBlock, rsaParams, digitalSignature);

				//byte[] gzippedBytes = GetGZippedBytes(encryptedBlock.EncryptedData);
				//byte[] ungzippedBytes = GetUnGZippedBytes(gzippedBytes);
				byte[] gzippedBytes = Compress(encryptedBlock.EncryptedData);
				byte[] ungzippedBytes = Decompress(gzippedBytes);

				Console.WriteLine("Original Message = " + original);
				Console.WriteLine("Original Message Length: {0}", original.Length);
				Console.WriteLine("Compressed Original Message = " + Convert.ToBase64String(compressedBytes));
				Console.WriteLine("Compressed Original Message Length: {0}", compressedBytes.Length);
				Console.WriteLine("DeCompressed Original Message = " + Convert.ToBase64String(decompressedBytes));
				Console.WriteLine("DeCompressed Original Message Length: {0}", decompressedBytes.Length);
				Console.WriteLine("Encrypted Data: {0}", Convert.ToBase64String(encryptedBlock.EncryptedData));
				Console.WriteLine("Encrypted Data Size: {0}", encryptedBlock.EncryptedData.Length);
				Console.WriteLine("GZipped Encrypted Data: {0}", Convert.ToBase64String(gzippedBytes));
				Console.WriteLine("GZipped Encrypted Data Size: {0}", gzippedBytes.Length);
				Console.WriteLine("UnGZipped Encrypted Data: {0}", Convert.ToBase64String(ungzippedBytes));
				Console.WriteLine("UnGZipped Encrypted Data Size: {0}", ungzippedBytes.Length);
				Console.WriteLine();
				Console.WriteLine("Message After Decryption = " + Encoding.UTF8.GetString(decrpyted));
			}
			catch (CryptographicException ex)
			{
				Console.WriteLine("Error : " + ex.Message);
			}

			Console.ReadLine();
		}