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?