Encrypting files using RC4 encryption algorithm in C#

前端 未结 1 1149
春和景丽
春和景丽 2021-01-27 03:03

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 Null

相关标签:
1条回答
  • 2021-01-27 03:33

    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.

    0 讨论(0)
提交回复
热议问题