繁体   English   中英

Rijndael文件加密/解密

[英]Rijndael file encryption / decryption

最近几天,我根据RijndaelManaged类提供的Rijndael加密标准创建了文件加密/解密类,并搜寻了我能找到的所有资源和示例。 这些示例已经过时,损坏或受限制,但至少设法学到了很多东西,并认为在确保其健壮性和超越您的批评之后,我会发布它的最新版本。

到目前为止,我发现的唯一陷阱是必须知道盐,因为没有办法像在字符串中那样将其存储在加密文件中,除非将每个字节的读/写转换为基于缓冲区的读/写,但您需要在解密时满足这一要求,并且还需要至少4个字节的数据进行加密(尽管我并不认为这是个问题,但确实需要提及)。

我也不完全确定1种盐是否足以满足密钥和初始化向量,还是两种出于安全性考虑是否更好?

任何其他观察和/或优化也将不胜感激

class FileEncDec
{
    private int keySize;
    private string passPhrase;

    internal FileEncDec( int keySize = 256, string passPhrase = @"This is pass phrase key to use for testing" )
    {
        this.keySize = keySize;
        this.passPhrase = passPhrase; // Can be user selected and must be kept secret
    }

    private static byte[] GenerateSalt( int length )
    {
        byte[] salt = new byte[ length ];

        // Populate salt with cryptographically strong bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        rng.GetNonZeroBytes( salt );

        // Split salt length (always one byte) into four two-bit pieces and store these pieces in the first four bytes 
        // of the salt array.
        salt[ 0 ] = (byte)( ( salt[ 0 ] & 0xfc ) | ( length & 0x03 ) );
        salt[ 1 ] = (byte)( ( salt[ 1 ] & 0xf3 ) | ( length & 0x0c ) );
        salt[ 2 ] = (byte)( ( salt[ 2 ] & 0xcf ) | ( length & 0x30 ) );
        salt[ 3 ] = (byte)( ( salt[ 3 ] & 0x3f ) | ( length & 0xc0 ) );

        return salt;
    }

    internal bool EncryptFile( string inputFile, string outputFile )
    {
        try
        {
            byte[] salt = GenerateSalt( 16 ); // Salt needs to be known for decryption (can be safely stored in the file)
            Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes( passPhrase, salt, 10000 );
            int bytesRead, bufferSize = keySize / 8;
            byte[] data = new byte[ bufferSize ];
            RijndaelManaged cryptor = new RijndaelManaged();
            cryptor.Key = derivedBytes.GetBytes( keySize / 8 );
            cryptor.IV = derivedBytes.GetBytes( cryptor.BlockSize / 8 );

            using ( var fsIn = new FileStream( inputFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan ) )
            {
                using ( var fsOut = new FileStream( outputFile, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.SequentialScan ) )
                {
                    // Add the salt to the file
                    fsOut.Write( salt, 0, salt.Length );

                    using ( CryptoStream cs = new CryptoStream( fsOut, cryptor.CreateEncryptor(), CryptoStreamMode.Write ) )
                    {
                        while ( ( bytesRead = fsIn.Read( data, 0, bufferSize ) ) > 0 )
                        {
                            cs.Write( data, 0, bytesRead );
                        }
                    }
                }
            }

            return true;
        }
        catch ( Exception )
        {
            return false;
        }
    }

    internal bool DecryptFile( string inputFile, string outputFile )
    {
        try
        {
            int bytesRead = 0, bufferSize = keySize / 8, saltLen;
            byte[] data = new byte[ bufferSize ], salt;
            Rfc2898DeriveBytes derivedBytes;
            RijndaelManaged cryptor = new RijndaelManaged();    // Create new cryptor so it's thread safe and don't need to use locks

            using ( var fsIn = new FileStream( inputFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan ) )
            {
                // Retrieve the salt length from the file
                fsIn.Read( data, 0, 4 );

                saltLen =   ( data[ 0 ] & 0x03 ) |
                            ( data[ 1 ] & 0x0c ) |
                            ( data[ 2 ] & 0x30 ) |
                            ( data[ 3 ] & 0xc0 );

                salt = new byte[ saltLen ];
                Array.Copy( data, salt, 4 );

                // Retrieve the remaining salt from the file and create the cryptor
                fsIn.Read( salt, 4, saltLen - 4 );
                derivedBytes = new Rfc2898DeriveBytes( passPhrase, salt, 10000 );
                cryptor.Key = derivedBytes.GetBytes( keySize / 8 );
                cryptor.IV = derivedBytes.GetBytes( cryptor.BlockSize / 8 );

                using ( var fsOut = new FileStream( outputFile, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.SequentialScan ) )
                {
                    using ( var cs = new CryptoStream( fsIn, cryptor.CreateDecryptor(), CryptoStreamMode.Read ) )
                    {
                        while ( ( bytesRead = cs.Read( data, 0, bufferSize ) ) > 0 )
                        {
                            fsOut.Write( data, 0, bytesRead );
                        }
                    }
                }
            }

            return true;
        }
        catch ( Exception )
        {
            return false;
        }
    }
}

编辑:1.添加了盐生成器。 2.重构为单个saltRfc2898DerivedBytes ,现在从password + salt推导出IV 3.使加密/解密线程安全(如果操作不正确,请告知我)。

编辑2:1.重构,以便读/写使用缓冲区而不是单字节读/写。 2.在加密文件中嵌入了salt并清理了变量(但对于“复制/粘贴”示例,仍允许使用passPhrase默认值。3.重构的文件句柄。

您可能应该每次都使用不同的IV。 如果您对相同的数据使用相同的IV,则结果是相同的。 攻击者现在可以推断出文件(部分)相同(这是泄漏)。 您可以生成16个高度随机字节,并将它们用作Rfc2898DeriveBytes的盐。 将这些字节添加到文件之前。 仅使用一个Rfc2898DeriveBytes生成IV和密钥。 或者,您可以完全不使用盐作为密钥,并随机生成IV。 该盐可以用于使密钥派生对于您的用例而言是唯一的,或者例如为您的应用程序的每个用户提供不同的密钥派生算法。

注意,按字节处理流非常慢。 使用缓冲区。 可能应该使用Stream.Copy

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM