private void button_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (sender == btnAssignKey)
         {
             rsaParams.AssignNewKey();
         }
         else if (sender == btnEncrypt)
         {
             var encryptBlock = HybridEncryption.EncryptData(txtMessage.Text, rsaParams);
             txtEncryptedSessionKey.Text = Convert.ToBase64String(encryptBlock.EncryptedSessionKey);
             txtEncryptedData.Text       = Convert.ToBase64String(encryptBlock.EncryptedData);
             txtIv.Text = Convert.ToBase64String(encryptBlock.Iv);
         }
         else if (sender == btnDecrypt)
         {
             var encryptBlock = new EncryptedPacket
             {
                 EncryptedData       = Convert.FromBase64String(txtEncryptedData.Text),
                 EncryptedSessionKey = Convert.FromBase64String(txtEncryptedSessionKey.Text),
                 Iv = Convert.FromBase64String(txtIv.Text)
             };
             var decrypted = HybridEncryption.DecryptData(encryptBlock, rsaParams);
             txtResult.Text = decrypted;
         }
     }
     catch (Exception exc)
     {
         MessageBox.Show("Error\n" + exc);
     }
 }
        public static string DecryptData(EncryptedPacket encryptedPacket, RSAWithRSAParameterKey rsaParams)
        {
            var aes = new AesEncryption();
            // Decrypt AES key with RSA and then decrypt data with AES.
            var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey);
            var decryptedData       = aes.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey, encryptedPacket.Iv);

            return(Encoding.UTF8.GetString(decryptedData));
        }
        public static EncryptedPacket EncryptData(string original, RSAWithRSAParameterKey rsaParams)
        {
            var aes             = new AesEncryption();
            var sessionKey      = RandomCryptography.Random.GenerateRandomNumber(32);
            var encryptedPacket = new EncryptedPacket
            {
                Iv = RandomCryptography.Random.GenerateRandomNumber(16)
            };

            // Encrypt data with AES and AES key with RSA.
            encryptedPacket.EncryptedData       = aes.Encrypt(Encoding.UTF8.GetBytes(original), sessionKey, encryptedPacket.Iv);
            encryptedPacket.EncryptedSessionKey = rsaParams.EncryptData(sessionKey);
            return(encryptedPacket);
        }