2

私の質問は、RC4 暗号化アルゴリズムを使用して C# でファイルを暗号化および復号化するにはどうすればよいですか?

これは、これらの質問の重複ではありません。

ただし、一見したところ、この質問はこの質問の複製のように見えますが、約7か月前であり、質問を直接解決する作業コードにはまだ答えがありません.

ただし、以下のリンクを参照しましたが、質問に完全に答えているものはなく、実際にはまったく答えていません。

Visual Studio 2013 に組み込まれている System.Security.Cryptography ライブラリが RC2 をサポートしていることは知っていますが、調査の一環として、今注目したいのは RC4 です。弱いのは承知ですが、まだまだ使っています。この暗号化を使用する重要なデータはありません。

できれば、ストリームを入力として受け入れるコード例を使用してください。懸念事項を適切に説明しなかったため、大きな混乱を招きました。他の種類の入力が大きなファイルの処理速度の低下を引き起こす可能性があるため、ストリーム入力を選択しています。

仕様: NET Framework 4.5、C#、WinForms。

4

1 に答える 1

1

免責事項:このコードは機能しますが、正しく実装されていないか、安全でない可能性があります。

BouncyCastleの RC4Engineを使用したファイルの暗号化/復号化の例を次に示します。

// You encryption/decryption key as a bytes array
var key = Encoding.UTF8.GetBytes("secretpassword");
var cipher = new RC4Engine();
var keyParam = new KeyParameter(key);

// for decrypting the file just switch the first param here to false
cipher.Init(true, keyParam);

using (var inputFile = new FileStream(@"C:\path\to\your\input.file", FileMode.Open, FileAccess.Read))
using (var outputFile = new FileStream(@"C:\path\to\your\output.file", FileMode.OpenOrCreate, FileAccess.Write))
{
    // processing the file 4KB at a time.
    byte[] buffer = new byte[1024 * 4];
    long totalBytesRead = 0;
    long totalBytesToRead = inputFile.Length;
    while (totalBytesToRead > 0)
    {
        // make sure that your method is marked as async
        int read = await inputFile.ReadAsync(buffer, 0, buffer.Length);

        // break the loop if we didn't read anything (EOF)
        if (read == 0)
        {
            break;
        }

        totalBytesRead += read;
        totalBytesToRead -= read;

        byte[] outBuffer = new byte[1024 * 4];
        cipher.ProcessBytes(buffer, 0, read, outBuffer,0);
        await outputFile.WriteAsync(outBuffer,0,read);
    }
}

結果のファイルは、この Web サイトを使用してテストされ、期待どおりに機能しているようです。

于 2015-08-01T21:06:03.020 に答える