2014-04-07 68 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文件並且它看起來沒有完全相同)。