1

I use AesManaged/CryptoStream to encrypt files based on a password.

        public static void EncryptStream(Stream streamToEncrypt, Stream outPutStream, string password)
        {
            SaltAndKey saltAndKey = PasswordAsByte(password);
            // writes salt
            outPutStream.Write(saltAndKey.SaltAsBytes, 0, SaltLenght);

            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.Mode = AesCipherMode; //CBC
                aesAlg.Key = saltAndKey.KeyAsBytes;
                // writes vector
                outPutStream.Write(aesAlg.IV, 0, IvLenght);
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (CryptoStream csEncrypt = new CryptoStream(outPutStream, encryptor, CryptoStreamMode.Write))
                {
                    int data;

                    data = streamToEncrypt.ReadByte();
                    while ((data > -1))
                    {
                        csEncrypt.WriteByte(System.Convert.ToByte(data));
                        data = streamToEncrypt.ReadByte();
                    }
                    if (csEncrypt.HasFlushedFinalBlock)
                        csEncrypt.FlushFinalBlock();
                }
            }
        }

This works and i'm able to decrypt the file without any issues.

I now need to detect whether the encrypted file was altered. One way is to decrypt the whole file, but with a large number of files to check, this is quite an expensive operation.

Is there any other way to validate that i'm able to decrypt a file without actually decrypting it?

Manuel
  • 1,985
  • 3
  • 31
  • 51
  • 3
    You could apply a [MAC](https://en.wikipedia.org/wiki/Message_authentication_code). See also [here](https://crypto.stackexchange.com/q/202) for the practical use. There are also operation modes that combine confidentiality and authentication, e.g. [GCM](https://en.wikipedia.org/wiki/Galois/Counter_Mode). C# offers [`AesGcm`](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm?view=netcore-3.1) since .NET Core 3.0, another possibility is [BouncyCastle](https://stackoverflow.com/a/54096382). – Topaco Sep 17 '20 at 07:11
  • Your question (or better the answer) depends on the question WHY do you sk for any altering? If e.g. the file is simple stored on your device you run a SHA256-hash over the file, store this hash and compare it later before you decrypt it (this is very similar to build a MAC as @Topaco wrote). If the file is transfered from a 3rd party it is a good idea that the 3rd party signs the file and sends you the signature together with their public key - before you decrypt you check the signature against the file you received. – Michael Fehr Sep 17 '20 at 07:35

0 Answers0