Please note that not all files have magic numbers to identify the type, and some magic numbers signature are used in several file types.
But nevertheless, if you want to take the extra step in cybersecurity in order to check if files that are being sent to your application really are what they claim or if you want to build whitelisting, this is a great tool.
Added a new function to check whether office files (Excel, Powerpoint, and Word files) are password-encrypted or not. This will be used to validate if these files are being identified as OLE files: /// <summary>
/// Action to check whether a file (Excel, Powerpoint, and Word files) are password-encrypted or not. This will be used to validate if these files are being identified as OLE files.
/// </summary>
/// <param name="ssContent">File to be checked</param>
/// <param name="ssIsFilePasswordProtected"></param>
/// <param name="ssErrorMessage"></param>
public void MssCheckPasswordProtection(byte[] ssContent, out bool ssIsFilePasswordProtected, out string ssErrorMessage) {
ssIsFilePasswordProtected = false;
ssErrorMessage = "";
try
{
// Check for OLE magic number
if (ssContent.Length > 8 &&
ssContent[0] == 0xD0 &&
ssContent[1] == 0xCF &&
ssContent[2] == 0x11 &&
ssContent[3] == 0xE0 &&
ssContent[4] == 0xA1 &&
ssContent[5] == 0xB1 &&
ssContent[6] == 0x1A &&
ssContent[7] == 0xE1)
using (MemoryStream ms = new MemoryStream(ssContent))
CompoundFile cf = new CompoundFile(ms);
// Excel
if (cf.RootStorage.TryGetStream("Workbook", out CFStream excelStream))
byte[] data = excelStream.GetData();
if (data.Length > 0x214)
// Password flag is at offset 0x214 in the stream
ushort flags = BitConverter.ToUInt16(data, 0x214);
if ((flags & 0x0001) != 0)
ssIsFilePasswordProtected = true;
}
// Word
else if (cf.RootStorage.TryGetStream("WordDocument", out CFStream wordStream))
byte[] data = wordStream.GetData();
if (data.Length > 0x200)
// Protection flag at offset 0x0B (sometimes 0x22, varies slightly)
// Simplest reliable method: look for the FEncrypted bit at offset 0x0B in older docs
if ((data[0x0B] & 0x01) != 0)
// PowerPoint
else if (cf.RootStorage.TryGetStream("PowerPoint Document", out CFStream pptStream))
byte[] data = pptStream.GetData();
// Not always reliable, but encrypted PowerPoint often has this header flag
if (data[0x0F] == 0xF0 || data[0x10] == 0x0F)
cf.Close();
catch (Exception ex)
ssErrorMessage = $"Error: {ex.Message}";
} // MssCheckPasswordProtection