繁体   English   中英

密码保护Open XML Wordprocessing文档

[英]Password protect Open XML Wordprocessing Document

我需要在Open XML Wordprocessing文档中添加基本的密码保护。 我可以使用COM接口,当我要处理大量文档时,这慢; 或者我可以将数据直接放在<w:settings> <w:documentProtection>下的docx文件中,这非常快。 但是,查看对密码进行加密的要求似乎需要花费数小时的编程时间。 有人编码过该算法吗? 我在用C#编码。

这是完整的代码段。 它为您提供了一个命令行实用程序,用于锁定和解锁Word文件(解锁文件-我认为-也将删除密码保护,尽管我没有尝试过)。

您需要OpenXML Format SDK 2.0来运行它,可以在这里找到: http : //www.microsoft.com/downloads/details.aspx? FamilyId=C6E744E5-36E9-45F5-8D8C-331DF206E0D0&displaylang=en,以及对DocumentFormat.OpenXml的引用在您的项目中。

using System;
using System.Xml.Linq;

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace LockDoc
{
    /// <summary>
    /// Manipulates modification permissions of an OpenXML document.
    /// </summary>
    class Program
    {
        /// <summary>
        /// Locks/Unlocks an OpenXML document.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: lockdoc lock|unlock filename.docx");
                return;
            }

            bool isLock = false;
            if (args[0].Equals("lock", StringComparison.OrdinalIgnoreCase))
            {
                isLock = true;
            }
            else if (!args[0].Equals("unlock", StringComparison.OrdinalIgnoreCase))
            {
                Console.Error.WriteLine("Wrong action!");
                return;
            }

            WordprocessingDocument doc = WordprocessingDocument.Open(args[1], true);
            doc.ExtendedFilePropertiesPart.Properties.DocumentSecurity =
                new DocumentFormat.OpenXml.ExtendedProperties.DocumentSecurity
                (isLock ? "8" : "0");
            doc.ExtendedFilePropertiesPart.Properties.Save();

            DocumentProtection dp =
                doc.MainDocumentPart.DocumentSettingsPart
                .Settings.ChildElements.First<DocumentProtection>();
            if (dp != null)
            {
                dp.Remove();
            }

            if (isLock)
            {
                dp = new DocumentProtection();
                dp.Edit = DocumentProtectionValues.Comments;
                dp.Enforcement = DocumentFormat.OpenXml.Wordprocessing.BooleanValues.One;

                doc.MainDocumentPart.DocumentSettingsPart.Settings.AppendChild(dp);
            }

            doc.MainDocumentPart.DocumentSettingsPart.Settings.Save();

            doc.Close();
        }
    }
}

我有一些类似于@Brij的东西,希望获得用于密码哈希的算法。 随后,我在MSDN论坛上发现了一些不完整的代码,还发现Word 2007密码保护非常容易解决。 因此,到目前为止,我只是随机添加一个哈希和盐,因此包括我在内的任何人都不知道实际的密码。 这足以防止意外更改。 鉴于不可能阻止有意更改,我将不做任何更安全的更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM