我找到了这个答案https://stackoverflow.com/a/14336292/1537195 https://stackoverflow.com/a/14336292/1537195这提供了检测 DOC 和 XLS 文件密码保护的好方法。
//Flagged with password
if (bytes.Skip(0x20c).Take(1).ToArray()[0] == 0x2f) return true; //XLS 2003
if (bytes.Skip(0x214).Take(1).ToArray()[0] == 0x2f) return true; //XLS 2005
if (bytes.Skip(0x20B).Take(1).ToArray()[0] == 0x13) return true; //DOC 2005
然而,它似乎并没有涵盖所有 XLS 文件,我也在寻找一种以相同方式检测 PPT 文件的方法。无论如何知道要查看这些文件类型的哪些字节吗?
我将 PowerPoint 演示文稿另存为 .ppt 和 .pptx(无论是否需要打开密码),在 7-Zip 中打开它们,并得出初步结论:
- 没有密码的 .pptx 文件始终使用标准 .zip 文件格式
- .ppt 文件是复合文档
- 带有密码的 .pptx 文件也是CompoundDocuments
- 所有密码复合文档都包含名为 *Encrypt* 的条目
要运行此代码,您需要安装 NuGet 包 OpenMcdf。这是我能找到的第一个用于阅读CompoundDocuments 的C# 库。
using OpenMcdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace _22916194
{
//http://stackoverflow.com/questions/22916194/detecing-password-protected-ppt-and-xls-documents
class Program
{
static void Main(string[] args)
{
foreach (var file in args.Where(File.Exists))
{
switch (Path.GetExtension(file))
{
case ".ppt":
case ".pptx":
Console.WriteLine($"* {file} " + (HasPassword(file) ? "is " : "isn't ") + "passworded");
Console.WriteLine();
break;
default:
Console.WriteLine($" * Unknown file type: {file}");
break;
}
}
Console.ReadLine();
}
private static bool HasPassword(string file)
{
try
{
using (var compoundFile = new CompoundFile(file))
{
var entryNames = new List<string>();
compoundFile.RootStorage.VisitEntries(e => entryNames.Add(e.Name), false);
//As far as I can see, only passworded files contain an entry with a name containing Encrypt
foreach (var entryName in entryNames)
{
if (entryName.Contains("Encrypt"))
return true;
}
compoundFile.Close();
}
}
catch (CFFileFormatException) {
//This is probably a .zip file (=unprotected .pptx)
return false;
}
return false;
}
}
}
您应该能够扩展此代码以处理其他 Office 格式。顶部的结论应该成立,除了您需要在CompoundDocument中查找一些其他数据而不是包含*Encrypt*的文件名(我快速查看了.doc文件,它的工作原理似乎并不完全相同)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)