2014-04-07 66 views
4

我找到了这个答案https://stackoverflow.com/a/14336292/1537195,它提供了检测DOC和XLS文件密码保护的好方法。检测受密码保护的PPT和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文件的方法。无论如何知道这些文件类型需要查看哪些字节?

+0

你是如何管理的? – TechnicalSmile

+0

我试图挖掘我的旧代码,但我想我只是没有弄明白,最终放弃了。对不起:( – silent

+0

为xls(x)文件,使用npoi可能是一个选项?看到这里:http://stackoverflow.com/questions/28604371/how-to-check-if-xlsx-file-is-password-protected -or-not-using-apache-poi -npoi是apache poi的c#端口,在我的其中一个项目中使用它,它可以很好地与xls和xlsx-files一起检查密码,但不知道它们是如何做到的。可能更多的是挖掘他们如何做到这一点:https://svn.apache.org/repos/asf/poi/trunk/ – Dominik

回答

0

我保存的PowerPoint演示文稿为.ppt,并有和没有打开它们需要密码文稿.pptx,在7-Zip的睁开眼睛,并来到了初步结论,即

  • .pptx格式无需密码始终使用标准的.zip文件格式
  • .PPT文件CompoundDocuments
  • 用密码.pptx格式也CompoundDocuments
  • 所有需要密码CompoundDocuments包含名为*加密*
  • 条目

要运行这段代码,您需要安装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文件并且它看起来没有完全相同)。