使用C#

时间:2015-08-01 19:51:16

标签: c# .net winforms encryption rc4-cipher

我的问题是,如何使用RC4加密算法在C#中加密和解密文件?

这不是这些问题的重复:

但我确实乍一看,这个问题看起来像是this question的副本,然而,这个问题大约有7个月之久,而且仍然无法解决直接解决问题的工作代码。< / p>

我已经提到了下面的链接,但没有一个完全回答这个问题,或者实际上完全没有回答。

我知道Visual Studio 2013中的内置System.Security.Cryptography库支持RC2,但我现在要关注的是RC4,作为研究的一部分。我知道它很弱,但我还在使用它。没有重要数据会使用此加密。

优选地使用代码示例,其接受流作为输入。我引起了很大的困惑,因为我没有正确描述我的担忧。我选择了一个流输入,因为担心任何其他类型的输入可能会导致处理大文件的速度降低。

规格:.NET Framework 4.5,C#,WinForms。

1 个答案:

答案 0 :(得分: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);
    }
}

生成的文件使用this website进行了测试,似乎按预期工作。

相关问题