Как сохранить содержимое зашифрованного файла в C# - PullRequest
0 голосов
/ 07 августа 2020

Итак, я пытаюсь написать приложение, которое позволяет пользователю шифровать и дешифровать файлы, используя AES и пароль по своему выбору. Однако проблема в том, что FileStream не позволяет мне копировать зашифрованное сообщение (которое пользователь создает в виде документа Word или блокнота), а затем указывает программе, где они его сохранили.

Проблема, с которой я столкнулся, FileStream не может записать зашифрованное содержимое в файл, говоря, что серьезность

Аргумент 1: невозможно преобразовать из 'string' в 'System.IO.Stream' CMDUniversalPGP C: \ Users \ keife \ source \ repos \ CMDUniversalPGP \ CMDUniversalPGP \ Program.cs 106 Н / Д

Вот код:

using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.VisualStudio.Web.CodeGeneration;
using com.sun.beans.decoder;
using System.IO.Compression;
using com.sun.tools.@internal.xjc.reader.gbind;
using org.omg.CORBA_2_3.portable;

namespace CMDUniversalPGP
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Welcome to Windows Universal PGP! Here you will compose emails or files to 
be encrypted by me. You will create the password. Program C 2020 Keifmeister.");
        Console.WriteLine("");
        Console.WriteLine("Press 1 to encrypt a file, 2 to decrypt one.");
        int action = Convert.ToInt32(Console.ReadLine());


        switch (action)
        {

            case 1:
                try
                {
                    Console.WriteLine("");
                    Console.WriteLine("I will now launch Microsoft Word. I may only find office if it's installed in C:\\Program Files\\Microsoft Office\\root\\Office16. If it's not installed I will launch notepad. Please compose your message in a new word or notepad document then point me to where it is, I will encrypt it for you. You may then send the encrypted file via email attchment. Only those with the password will be able to open.Please remember when emailing the sending and reiceving email addresses as well as subject are  still viewable. Cheers.");
                    
                    Process.Start("C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD");




                }
                catch (Exception e)
                {
                    Console.WriteLine("I could not find word, so launching notepad.");
                    Process.Start("C:\\WINDOWS\\system32\\notepad.exe");


                }


                Console.WriteLine("Please point me to the saved file.");
                string sourceFile = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Please point me to where you want the encrypted file saved.");
                string encFile = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Enter the encrypted file name and extension.");
                string encDir  = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Please enter your desired password.");
                string password = Convert.ToString(Console.ReadLine());



                void EncryptFile(string sourceFile, string encFile)
                {

                    try
                    
                        {

                            DirectoryInfo info = new DirectoryInfo(encDir);
                            if (!info.Exists)
                            {
                                info.Create();
                            }

                            string path = Path.Combine (encDir, encFile);
                            using (FileStream outputFileStream = new FileStream(path, FileMode.Create))
                            {
                            
                            }
                        

                        UnicodeEncoding UE = new UnicodeEncoding();
                        byte[] key = UE.GetBytes(password);

                        string cryptFile = encFile;
                        FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

                        RijndaelManaged RMCrypto = new RijndaelManaged();

                        CryptoStream cs = new CryptoStream(fsCrypt,
                            RMCrypto.CreateEncryptor(key, key),
                            CryptoStreamMode.Write);

                        FileStream fsIn = new FileStream(sourceFile, FileMode.Open);
                        
                       
                        int data;
                        while ((data = fsIn.ReadByte()) != -1)
                            cs.WriteByte((byte)data);


                        fsIn.Close();
                        cs.Close();
                        fsCrypt.Close();

// Здесь и возникает ошибка, спасибо.

                        FileStream.CopyTo(encFile);
                        

                    }
                    catch
                    {
                        Console.WriteLine("Could not enrypt.");
                        Console.WriteLine(""); 
                        Console.WriteLine("Do you want to email the encryoted file? Type yes and I will open your default mail client and email account with it attached to a new email. If not type no and I will exit.");

                  

                    }
                }
                break;

            case 2:
                try
                {
                    Console.WriteLine("Please point me to the encrypted file.");
                    string sourceFile2 = Convert.ToString(Console.ReadLine());
                    Console.WriteLine("Please point me to where you want the decrypted file saved.");
                    string decFile = Convert.ToString(Console.ReadLine());
                    Console.WriteLine("Please enter the password.");
                    string passworddec = Convert.ToString(Console.ReadLine());


                    {
                        byte[] passwords = Encoding.UTF8.GetBytes(passworddec);
                        byte[] salt = new byte[32];
                        using (FileStream fsCrypt = new FileStream(sourceFile2, FileMode.Open))
                        {
                            fsCrypt.Read(salt, 0, salt.Length);
                            RijndaelManaged AES = new RijndaelManaged();
                            AES.KeySize = 256;//aes 256 bit encryption c#
                            AES.BlockSize = 128;//aes 128 bit encryption c#
                            var key = new Rfc2898DeriveBytes(passwords, salt, 50000);
                            AES.Key = key.GetBytes(AES.KeySize / 8);
                            AES.IV = key.GetBytes(AES.BlockSize / 8);
                            AES.Padding = PaddingMode.PKCS7;
                            AES.Mode = CipherMode.CFB;
                            using (CryptoStream cryptoStream = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read))
                            {
                                using (FileStream fsOut = new FileStream(decFile, FileMode.Create))
                                {
                                    int read;
                                    byte[] buffer = new byte[1048576];
                                    while ((read = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        Console.WriteLine("The decrypted message:");
                                        Console.WriteLine("");
                                        fsOut.Write(buffer, 0, read);
                                    }





                                }
                            }
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("Could not decrypt. Possibly file is too large or password is incorrect.");

                }
                break;
        }
    }
}

}

// Строка FileStream.CopyTo (encFile); Здесь происходит ошибка, спасибо.

Любая помощь будет принята с благодарностью. Спасибо

...