免责声明:虽然此代码有效,但它可能无法正确实施和/或安全。
这是使用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);
}
}
使用此网站对生成的文件进行了测试,它似乎按预期工作。