一种加密算法,允许对部分下载的文件进行解密

本文关键字:下载 文件 解密 一种 加密算法 | 更新日期: 2023-09-27 18:25:11

我正在从服务器下载一个二进制文件,并在下载过程中对其进行部分访问。我想在上传之前加密文件,并在我的程序接收到它时解密它的内容

使用下面的代码,文件以随机大小的字节块的形式到达,所以我认为我需要一种方法来处理单个字节,或者至少是固定数量的字节,并保持整个文件大小不变。

    private void DownloadFile()
    {
        WebClient client = new WebClient();
        Stream stream = client.OpenRead(address);
        byte[] readBuffer = new byte[139043];   // File size known ahead of time
        int totalBytesRead = 0;
        int bytesRead;
        int i = 0;
        while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
        {
            File.WriteAllBytes("file_" + i + ".ext", readBuffer);   // Save partially downloaded file
            totalBytesRead += bytesRead;
            i++;
        }
    }

解决方案:我选择了下面的答案中所示的简单XOR算法。它对单个字节有效,考虑到我可以为每个文件生成一个唯一的密钥,我对保护级别感到满意。

一种加密算法,允许对部分下载的文件进行解密

您可能希望了解AES CTR加密。有一个相关的SO问题:我可以在.NET的CTR模式下使用AES吗?

有一个答案指向MSDN上一篇关于在应用程序中实现加密的文章:https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aesmanaged%28v=vs.90%29.aspx#2

我已经编写了以下基于XOR的算法,我认为这对我的目的来说已经足够了。

密码和salt可以从有关文件的各种信息(例如,文件大小或唯一文件名)中派生出来,因此,任何密钥都不会被多次使用。

欢迎所有的批评和仇恨。

    public void Crypt(byte[] data, string filepath)
    {
        // Define password and salt
        byte[] pwd = GetBytes("PASSWORD");
        byte[] salt = GetBytes("SALT");
        // Generate PasswordDeriveBytes from the password and salt.
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);
        // Generate key from PasswordDeriveBytes
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);
        // Encrypt/Decrypt
        for(int i = 0; i < data.Length; i++)
        {
            data[i] = (byte)(data[i] ^ tdes.Key[i % tdes.Key.Length]);
        }
        // Save File
        File.WriteAllBytes(filepath, data);   
    }