【问题标题】:How to encrypt / decrypt only certain amount of bytes (file)?如何仅加密/解密一定数量的字节(文件)?
【发布时间】:2015-01-16 22:47:52
【问题描述】:

我正在实现文件的加密/解密,其中只应加密一定数量的字节。 例如:我有 500 MB 的大文件,我只想加密(当然还有解密)2 MB 的文件。

我已经实现了一切,加密工作正常(没有错误),但是当我运行解密时它总是抛出这个错误:

System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed.
at System.Security.Cryptography.CapiSymmetricAlgorithm.DepadBlock(Byte[] block, Int32 offset, Int32 count) at  System.Security.Cryptography.CapiSymmetricAlgorithm.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
at System.IO.Stream.Dispose()
at ...

然后我尝试将 Padding 设置为encryptor.Padding = PaddingMode.None;(并且还尝试了 PaddingMode.Zeros 等)。使用这种填充模式运行加密和解密后解密的结果没有错误/异常,但文件的加密部分仍然被加密,但有点不同。我还检查了密码是否正确

现在我没有更多的解决方案来处理这种文件的“部分”加密。有任何想法吗?如何处理这个填充或字节?

这是我的一定数量字节的加密和解密过程的代码(对不起长度,但只有你会知道:)):

static byte[] FILE_HEADER = Encoding.Default.GetBytes("header_of_file"); //this is written to the first line of encrypted file
static long limitBytes = 4096 * 8; //limit encryption to this amount of bytes

public static bool Encrypt(string inputFilePath, string outputfilePath, string EncryptionKey)
{
int bytesRead = 1;
long byteWriteCounter = 0;
long encryptedByteCounter = 0;
byte[] blength = null;
byte[] intBytes = null;
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
blength = new byte[FILE_HEADER.Length];
long sumBytesRead = 0;

try
{
    using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
    {                    
        fsInput.Read(blength, 0, blength.Length);

        if (!blength.SequenceEqual(FILE_HEADER)) //read the FILE_HEADER - if not equal that we can encrypt otherwise is already encrypted
        {
            fsInput.Position = 0;

            using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
            {                            
                using (Aes encryptor = Aes.Create())
                {

                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);

                    using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        try
                        {

                            while (bytesRead != 0)
                            {
                                bytesRead = fsInput.Read(buffer, 0, bufferLen);
                                sumBytesRead += bytesRead;

                                if (sumBytesRead <= limitBytes) //limit encryption
                                {                                  

                                    if (bytesRead < bufferLen)
                                    {                                                   

                                        cs.Write(buffer, 0, bytesRead);
                                        encryptedByteCounter += bytesRead;
                                        byteWriteCounter += bytesRead;

                                        intBytes = Encoding.Default.GetBytes(encryptedByteCounter.ToString("D7"));

                                        fsOutput.Position = 0;
                                        fsOutput.Write(FILE_HEADER, 0, FILE_HEADER.Length); //we write our header to file, to know which is encrypted
                                        fsOutput.Write(intBytes, 0, intBytes.Length); //we write number of encrypted bytes next to header, for decryption to know
                                        bytesRead = 0;
                                    }
                                    else
                                    {
                                        cs.Write(buffer, 0, bytesRead);
                                        encryptedByteCounter += bytesRead;
                                        byteWriteCounter += bytesRead;

                                    }
                                }
                                else //if the file is bigger than limit, we continue to write normal data (unencrypted)
                                {
                                    if (bytesRead < bufferLen)
                                    {
                                        fsOutput.Write(buffer, 0, bytesRead);
                                        byteWriteCounter += bytesRead;
                                        intBytes = Encoding.Default.GetBytes(encryptedByteCounter.ToString("D7"));

                                        fsOutput.Position = 0;
                                        fsOutput.Write(FILE_HEADER, 0, FILE_HEADER.Length);
                                        fsOutput.Write(intBytes, 0, intBytes.Length);
                                        bytesRead = 0;
                                    }
                                    else
                                    {
                                        fsOutput.Write(buffer, 0, bytesRead);
                                        byteWriteCounter += bytesRead;
                                    }
                                }

                            }

                        }
                        catch (SystemException se)
                        {
                            Console.WriteLine("Exception ENC: " + se);
                        }
                    }
                }
            }
            return true;

        }
        else
        {
            //file is already encrypted
            return false;
        }
    }


}
catch (SystemException se)
{

    Console.WriteLine("Main ENC exception: "+se);

    return false;
}

}

...及解密功能:

public static bool Decrypt(string inputFilePath, string outputfilePath, string EncryptionKey)
{
byte[] blength = null;
blength = new byte[FILE_HEADER.Length];
long byteWriteCounter = 0;
int bufferLen = 4096; 
byte[] buffer = new byte[bufferLen];
int bytesRead = 1;
long decryptedByteCounter = 0;
long sumBytesRead = 0;
byte[] bufferEncBytes = new byte[7];

try
{

    using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
    {

        fsInput.Read(blength, 0, blength.Length);

        if (blength.SequenceEqual(FILE_HEADER))//check if is our encrypted file
        {


            fsInput.Read(bufferEncBytes, 0, bufferEncBytes.Length);

            int numOfDecBytes = Convert.ToInt32(Encoding.Default.GetString(bufferEncBytes)); //get number of encrypted bytes

            using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
            {                   
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);                        

                    using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        try
                        {

                            while (bytesRead != 0)
                            {
                                bytesRead = fsInput.Read(buffer, 0, bufferLen);
                                sumBytesRead += bytesRead;

                                if (sumBytesRead <= numOfDecBytes) //decrypt until limit
                                {

                                    if (bytesRead < bufferLen)
                                    {
                                        cs.Write(buffer, 0, bytesRead);
                                        decryptedByteCounter += bytesRead;
                                        byteWriteCounter += bytesRead;

                                        bytesRead = 0; //we are at the end of file, end everything
                                    }
                                    else
                                    {
                                        cs.Write(buffer, 0, bytesRead);
                                        decryptedByteCounter += bytesRead;
                                        byteWriteCounter += bytesRead;                                         
                                    }
                                }
                                else //if we have decrypted encrypted bytes, continue with rest of the (normal) data
                                {
                                    if (bytesRead < bufferLen)
                                    {
                                        fsOutput.Write(buffer, 0, bytesRead);
                                        byteWriteCounter += bytesRead;

                                        bytesRead = 0;
                                    }
                                    else
                                    {
                                        fsOutput.Write(buffer, 0, bytesRead);
                                        byteWriteCounter += bytesRead;
                                    }
                                }

                            }

                        }
                        catch (SystemException se)
                        {
                            Console.WriteLine("Exception DECR: " + se);
                        }

                    }

                }

            }
            return true;
        }
        else
        {
            //not right file for decryption
            return false;
        }
    }

}
catch (SystemException eks)
{
    Console.WriteLine("Error: " + eks); //here the exception of Invalid Padding is thrown

    return false;
}
}

【问题讨论】:

  • 这基本上相当于调试文件处理。您的密文与纯文本一样大的假设是错误的。您完全阅读到要加密的明文末尾的假设似乎也是错误的。密文也可能比明文大。总而言之,许多错误,以及试图做所有事情而不是做出好的设计的加密/解密方法。
  • 为什么只想加密部分文件?这显然不安全。
  • @MaartenBodewes-owlstead 我知道,有很多错误,如果它符合我的逻辑,我正在开发阶段测试。但是你能帮助并提供解决方案如何实现加密字节数,在解密中可以计算和解密吗?还是应该使用其他加密算法?
  • @CodesInChaos 我没有找到任何其他解决方案来更快地加密大量 2GB+ (.iso) 文件。如果你对这么大文件的一小部分进行加密,总体结果是一样的——文件不能使用..
  • @OnlyKing 对于 DRM 来说可能是可以接受的(无论如何它已经被破坏了),对于任何与安全相关的东西都不是。如果您只加密开头,一个称职的攻击者将能够从该 iso 文件中提取大多数文件。但即使对于 DRM,它也没有什么意义,因为您只需要在受限于 IO 性能的情况下进行动态解密,而不是解密的 CPU 成本。

标签: c# security encryption cryptography partial


【解决方案1】:

当您使用块密码进行加密时,大多数模式都会添加填充。这意味着加密数据将比原始明文更长,因为有额外的填充。您需要保留加密数据的填充,否则您将收到错误的填充错误。

您可以确保小心处理填充,或者切换到不使用填充的 CTR 模式,从而提供与明文相同长度的密文。

使用 Stream Cypher,如 Rabbit 或 Salsa20 将具有相同的效果。

【讨论】:

  • 在这种情况下如何谨慎处理 Padding?该算法不支持CTR模式..
  • 如果您将明文大小存储在密文前面,那么您可以尝试实现填充到块大小(即 AES 的 0..15 字节)。在这种情况下,请确保您的缓冲区和要加密的字节数都是块大小的倍数。然后您可以使用NoPadding 来加密/解密所需的字节。如果您已经加密到最大值,那么您不需要填充。在另一种情况下,您可以通过用零填充缓冲区的最后一部分来填充。 PS 在你的情况下,我当然会考虑存储 64 位的明文大小。
  • 加密,并记录加密字节的大小。将这些字节添加到文件未加密部分的前面。保留您添加到密文的密文大小的固定大小记录。在解密端,首先读取密文大小。然后准确解密那么多字节(填充应该自动消失)。将解密的明文附加到文件的未加密其余部分。确保固定大小的长度变量足够大,可以容纳您需要的最长密文大小。
猜你喜欢
  • 2015-03-11
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多