问题
My question is, how do I encrypt and decrypt a file in C# using the RC4 encryption algorithm?
This is not a duplicate of these questions:
What is a NullReferenceException, and how do I fix it?
RC4 Algorithm: Unable to Encrypt / Decrypt data where client uses Javascript and Server c#
RC4 128 bit encryption in C#
I do however acknowledge that at first glance, this question will appear like a duplicate of this question, however, it is around 7 months old, and still has no answer with working code that solves the question directly.
I have however referred to the below links, but none of them answers the question fully, or in fact, at all.
http://www.codeproject.com/Articles/5719/Simple-encrypting-and-decrypting-data-in-C
http://www.codeproject.com/Articles/5068/RC-Encryption-Algorithm-C-Version
I do know that the built-in System.Security.Cryptography library in Visual Studio 2013 supports RC2, but what I want to focus on right now is RC4, as part of a research. I know it is weak yes, but I'm still using it. No important data is going to be using this encryption.
Preferably with a code example, that accepts a stream as an input. I have caused great confusion, as I did not describe my concerns properly. I am opting for a stream input, due to the concern that any kind of other input may cause a decrease in the speed of processing large files.
Specifications: NET Framework 4.5, C#, WinForms.
回答1:
Disclaimer: While this code works, it might not be correctly implemented and/or secure.
Here's an example of file encryption/decryption using the BouncyCastle's 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);
}
}
The resulting file was tested using this website and it appears to be working as expected.
来源:https://stackoverflow.com/questions/31765588/encrypting-files-using-rc4-encryption-algorithm-in-c-sharp