Как интегрировать процедуру расшифровки в зашифрованный файл? - PullRequest
0 голосов
/ 27 марта 2011

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

Исходный код, который я взял из codeproject

Можно ли добавить запрос пароля и процедуру расшифровки в процедуру шифрования?Процедура шифрования:

/// <summary>
/// This takes an input file and encrypts it into the output file
/// </summary>
/// <param name="inFile">the file to encrypt</param>
/// <param name="outFile">the file to write the encrypted data to</param>
/// <param name="password">the password for use as the key</param>
/// <param name="callback">the method to call to notify of progress</param>
public static void EncryptFile(string inFile, string outFile, string password, CryptoProgressCallBack callback)
{
    using(FileStream fin = File.OpenRead(inFile),
                fout = File.OpenWrite(outFile))
    {
        long lSize = fin.Length; // the size of the input file for storing
        int size = (int)lSize;  // the size of the input file for progress
        byte[] bytes = new byte[BUFFER_SIZE]; // the buffer
        int read = -1; // the amount of bytes read from the input file
        int value = 0; // the amount overall read from the input file for progress

        // generate IV and Salt
        byte[] IV = GenerateRandomBytes(16);
        byte[] salt = GenerateRandomBytes(16);

        // create the crypting object
        SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt);
        sma.IV = IV;            

        // write the IV and salt to the beginning of the file
        fout.Write(IV,0,IV.Length);
        fout.Write(salt,0,salt.Length);

        // create the hashing and crypto streams
        HashAlgorithm hasher = SHA256.Create();
        using(CryptoStream cout = new CryptoStream(fout,sma.CreateEncryptor(),CryptoStreamMode.Write),
                    chash = new CryptoStream(Stream.Null,hasher,CryptoStreamMode.Write))
        {
            // write the size of the file to the output file
            BinaryWriter bw = new BinaryWriter(cout);
            bw.Write(lSize);

            // write the file cryptor tag to the file
            bw.Write(FC_TAG);

            // read and the write the bytes to the crypto stream in BUFFER_SIZEd chunks
            while( (read = fin.Read(bytes,0,bytes.Length)) != 0 )
            {
                cout.Write(bytes,0,read);
                chash.Write(bytes,0,read);  
                value += read;
                callback(0,size,value);
            }
            // flush and close the hashing object
            chash.Flush();
            chash.Close();

            // read the hash
            byte[] hash = hasher.Hash;

            // write the hash to the end of the file
            cout.Write(hash,0,hash.Length);

            // flush and close the cryptostream
            cout.Flush();
            cout.Close();
        }
    }
}

1 Ответ

1 голос
/ 27 марта 2011

если я понимаю, вы хотите, чтобы файл открылся, запросил пароль, а если пароль правильный, запустите реальную программу?

Если это так, просто сделайте быструю проверку хеша md5 (с солью), посмотрите на это: HOWTO: кодируйте пароль с использованием MD5 в C # , затем получите встроенный код : Как внедрить и получить доступ к ресурсам с помощью Visual C # , а затем запустить его: Как программно скомпилировать код с использованием компилятора C # .

В качестве альтернативы базовой проверке md5 (которая ничего не делает с отражателем), вы должны шифровать внедренные данные симметричным шифрованием (используя что-то вроде C # Symmetric Encryption ), а затем расшифровывать это с введенным паролем.

Надеюсь, это поможет вам начать

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...