示例#1
0
        EncryptedPackageEnvelope(
            string envelopeFileName,
            Stream packageStream,
            PublishLicense publishLicense,
            CryptoProvider cryptoProvider
            )
        {
            if (envelopeFileName == null)
            {
                throw new ArgumentNullException("envelopeFileName");
            }

            if (packageStream == null)
            {
                throw new ArgumentNullException("packageStream");
            }

            ThrowIfRMEncryptionInfoInvalid(publishLicense, cryptoProvider);

            _root = StorageRoot.Open(
                envelopeFileName,
                _defaultFileModeForCreate,
                _defaultFileAccess,
                _defaultFileShare
                );

            InitializeRMForCreate(publishLicense, cryptoProvider);
            EmbedPackage(packageStream);
        }
示例#2
0
        EncryptedPackageEnvelope(
            Stream envelopeStream,
            PublishLicense publishLicense,
            CryptoProvider cryptoProvider
            )
        {
            if (envelopeStream == null)
            {
                throw new ArgumentNullException("envelopeStream");
            }

            ThrowIfRMEncryptionInfoInvalid(publishLicense, cryptoProvider);

            _root = StorageRoot.CreateOnStream(envelopeStream, _defaultFileModeForCreate);

            //
            // CreateOnStream opens the stream for read access if it's readable, and for
            // read/write access if it's writable. We're going to need it to be writable,
            // so check that it is.
            //
            if (_root.OpenAccess != FileAccess.ReadWrite)
            {
                throw new NotSupportedException(SR.StreamNeedsReadWriteAccess);
            }

            InitializeRMForCreate(publishLicense, cryptoProvider);
            EmbedPackage(null);
        }
示例#3
0
 Create(
     Stream envelopeStream,
     PublishLicense publishLicense,
     CryptoProvider cryptoProvider
     )
 {
     return(new EncryptedPackageEnvelope(envelopeStream, publishLicense, cryptoProvider));
 }
示例#4
0
 Create(
     string envelopeFileName,
     PublishLicense publishLicense,
     CryptoProvider cryptoProvider
     )
 {
     return(new EncryptedPackageEnvelope(envelopeFileName, publishLicense, cryptoProvider));
 }
示例#5
0
        InitializeRMForCreate(
            PublishLicense publishLicense,
            CryptoProvider cryptoProvider
            )
        {
            //
            // Define a data space consisting of a single transform, namely the
            // RightsManagementEncryptionTransform.
            //
            DataSpaceManager dsm = _root.GetDataSpaceManager();

            dsm.DefineTransform(
                RightsManagementEncryptionTransform.ClassTransformIdentifier,
                EncryptionTransformName
                );

            string[] transformStack = new string[1];
            transformStack[0] = EncryptionTransformName;
            _dataSpaceName    = DataspaceLabelRMEncryptionNoCompression;
            dsm.DefineDataSpace(transformStack, _dataSpaceName);

            //
            // The call to DefineTransform created a RightsManagementEncryptionTransform
            // object. Obtain this object from the DataSpaceManager, and wrap it in a
            // RightsManagementInformation object. This makes the RM information in the
            // compound file available to the application (through the RightsManagementInformation
            // property), without exposing to the application the implementation detail
            // that there -is- such a thing as a "transform".
            //
            RightsManagementEncryptionTransform rmet =
                dsm.GetTransformFromName(EncryptionTransformName) as RightsManagementEncryptionTransform;

            //
            // We just defined this transform, so it must exist.
            //
            Debug.Assert(
                rmet != null,
                "RightsManagementEncryptionTransform not found"
                );

            _rmi = new RightsManagementInformation(rmet);

            //
            // Prepare the transform object for use.
            //
            rmet.SavePublishLicense(publishLicense);
            rmet.CryptoProvider = cryptoProvider;

            //
            // The transform object is now ready for use. When the data space manager
            // queries the transform's IsReady property, it will return true. So there
            // is no need to sign up for the TransformInitializationEvent.
            //
        }
示例#6
0
        private void ThrowIfRMEncryptionInfoInvalid(
            PublishLicense publishLicense,
            CryptoProvider cryptoProvider)
        {
            if (publishLicense == null)
            {
                throw new ArgumentNullException("publishLicense");
            }

            if (cryptoProvider == null)
            {
                throw new ArgumentNullException("cryptoProvider");
            }
        }
示例#7
0
        }// end:OnPublish()

        // ------------------------ PublishRMContent --------------------------
        /// <summary>
        ///   Writes an encrypted righted managed content file.</summary>
        /// <param name="contentFile">
        ///   The path and filename of the source content file.</param>
        /// <param name="xrmlFile">
        ///   The path and filename of the XrML rights management file.</param>
        /// <param name="encryptedFile">
        ///   The path and filename for writing the RM encrypted content.</param>
        /// <returns>
        ///   true if the encrypted package is written successfully;
        ///   otherwise false.</returns>
        public bool PublishRMContent(
            string contentFile, string xrmlFile, string encryptedFile)
        {
            string xrmlString;

            // Extract individual filenames without the path.
            string contentFilename   = FilenameOnly(contentFile);
            string xrmlFilename      = FilenameOnly(xrmlFile);
            string encryptedFilename = FilenameOnly(encryptedFile);

            try
            {
                //<SnippetRmContPubUnsLic>
                WriteStatus("   Reading '" + xrmlFilename + "' permissions.");
                try
                {
                    StreamReader sr = File.OpenText(xrmlFile);
                    xrmlString = sr.ReadToEnd();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("ERROR: '"+xrmlFilename+"' open failed.\n"+
                        "Exception: " + ex.Message, "XrML File Error",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                WriteStatus("   Building UnsignedPublishLicense");
                WriteStatus("       from '" + xrmlFilename + "'.");
                UnsignedPublishLicense unsignedLicense =
                    new UnsignedPublishLicense(xrmlString);
                ContentUser author = unsignedLicense.Owner;
                //</SnippetRmContPubUnsLic>

                WriteStatus("   Building secure environment.");
                try
                {
                    //<SnippetRmContPubSecEnv>
                    string applicationManifest = "<manifest></manifest>";
                    if (File.Exists("rpc.xml"))
                    {
                        StreamReader manifestReader = File.OpenText("rpc.xml");
                        applicationManifest = manifestReader.ReadToEnd();
                    }

                    if (_secureEnv == null)
                    {
                        if (SecureEnvironment.IsUserActivated(new ContentUser(
                                    _currentUserId, AuthenticationType.Windows)))
                        {
                            _secureEnv = SecureEnvironment.Create(
                                applicationManifest, new ContentUser(
                                    _currentUserId, AuthenticationType.Windows));
                        }
                        else
                        {
                            _secureEnv = SecureEnvironment.Create(
                                applicationManifest,
                                AuthenticationType.Windows,
                                UserActivationMode.Permanent);
                        }
                    }
                    //</SnippetRmContPubSecEnv>
                }
                catch (RightsManagementException ex)
                {
                    MessageBox.Show("ERROR: Failed to build secure environment.\n" +
                        "Exception: " + ex.Message + "\n\n" +
                        ex.FailureCode.ToString() + "\n\n" + ex.StackTrace,
                        "Rights Management Exception",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                // If using Windows authentication and the Xrml owner name
                // does not match the current log-in name, show error message
                if ((author.AuthenticationType == AuthenticationType.Windows)
                    && (author.Name != _currentUserId))
                {
                    MessageBox.Show("ERROR: The current user name does not " +
                        "match the UnsignedPublishLicense owner.\n" +
                        "Please check the owner <NAME> element contained in '" +
                        xrmlFilename + "'\n\n" +
                        "Current user log-in ID: " + _currentUserId + "\n" +
                        "XrML UnsignedPublishLicense owner name: " + author.Name,
                        "Incorrect Authentication Name",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                   return false;
                }

                WriteStatus("   Signing the UnsignedPublishLicense\n" +
                            "       to create a signed PublishLicense.");
                UseLicense authorsUseLicense;
                PublishLicense publishLicense =
                    unsignedLicense.Sign(_secureEnv, out authorsUseLicense);

                // Save an XML version of the UseLicense.
                WriteStatus("   Saving UseLicense");
                string useLicenseFilepath = contentFile + ".UseLicense.xml";
                WriteStatus("       '" + FilenameOnly(useLicenseFilepath) + "'.");
                FileStream useStream =
                    new FileStream(useLicenseFilepath, FileMode.Create);
                StreamWriter useWriter =
                    new StreamWriter(useStream, System.Text.Encoding.ASCII);
                useWriter.WriteLine(authorsUseLicense.ToString());
                useWriter.Close();
                useStream.Close();

                // Save an XML version of the signed PublishLicense.
                WriteStatus("   Saving signed PublishLicense");
                string pubLicenseFilepath = contentFile + ".PublishLicense.xml";
                WriteStatus("       '" + FilenameOnly(pubLicenseFilepath) + "'.");
                FileStream pubStream =
                    new FileStream(pubLicenseFilepath, FileMode.Create);
                StreamWriter pubWriter =
                    new StreamWriter(pubStream, System.Text.Encoding.ASCII);
                pubWriter.WriteLine(publishLicense.ToString());
                pubWriter.Close();
                pubStream.Close();

                //<SnippetRmContPubEncrypt>
                WriteStatus("   Binding the author's UseLicense and");
                WriteStatus("       obtaining the CryptoProvider.");
                using (CryptoProvider cryptoProvider =
                            authorsUseLicense.Bind(_secureEnv))
                {
                    WriteStatus("   Writing encrypted content.");
                    using (Stream clearTextStream =
                                File.OpenRead(contentFile) )
                    {
                        using (Stream cryptoTextStream =
                                    File.OpenWrite(encryptedFile))
                        {
                            // Write the length of the source content file
                            // as the first four bytes of the encrypted file.
                            cryptoTextStream.Write(
                                BitConverter.GetBytes(clearTextStream.Length),
                                0, sizeof(Int32));

                            // Allocate clearText buffer.
                            byte[] clearTextBlock =
                                new byte[cryptoProvider.BlockSize];

                            // Encrypt clearText to cryptoText block by block.
                            for(;;)
                            {   // Read clearText block.
                                int readCount = ReliableRead(
                                                    clearTextStream,
                                                    clearTextBlock, 0 ,
                                                    cryptoProvider.BlockSize);
                                // readCount of zero is end of data.
                                if (readCount == 0)  break; // for

                                // Encrypt clearText to cryptoText.
                                byte[] cryptoTextBlock =
                                    cryptoProvider.Encrypt(clearTextBlock);

                                // Write cryptoText block.
                                cryptoTextStream.Write(cryptoTextBlock, 0,
                                                       cryptoTextBlock.Length);
                            }
                            WriteStatus("   Closing '" + encryptedFilename + "'.");
                        }// end:using (Stream cryptoTextStream =
                    }// end:using (Stream clearTextStream =
                }// end:using (CryptoProvider cryptoProvider =
                WriteStatus("   Done - Content encryption complete.");
                //</SnippetRmContPubEncrypt>
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                    ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                    "Runtime Exception",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            WritePrompt("See the RightsManagedContentViewer sample for " +
                "details on how to access rights managed content.");
            return true;
        }// end:PublishRMContent()
示例#8
0
        }// end:OnPublish()

        // ------------------------ PublishRMPackage --------------------------
        /// <summary>
        ///   Writes an encrypted righted managed package.</summary>
        /// <param name="packageFilepath">
        ///   The path and filename of the source document package.</param>
        /// <param name="filename">
        ///   The path and filename of the XrML rights management file.</param>
        /// <param name="encryptedFilepath">
        ///   The path and filename for writing the RM encrypted package.</param>
        /// <returns>
        ///   true if the encrypted package is written successfully;
        ///   otherwise false.</returns>
        public bool PublishRMPackage(
            string packageFile, string xrmlFile, string encryptedFile)
        {
            string xrmlString;

            // Extract individual filenames without the path.
            string packageFilename = packageFile.Remove(0,
                                                        packageFile.LastIndexOf('\\') + 1);
            string xrmlFilename = xrmlFile.Remove(0,
                                                  xrmlFile.LastIndexOf('\\') + 1);
            string encryptedFilename = encryptedFile.Remove(0,
                                                            encryptedFile.LastIndexOf('\\') + 1);

            try
            {
                WriteStatus("   Reading '" + xrmlFilename + "' permissions.");
                try
                {
                    StreamReader sr = File.OpenText(xrmlFile);
                    xrmlString = sr.ReadToEnd();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("ERROR: '" + xrmlFilename + "' open failed.\n" +
                                    "Exception: " + ex.Message, "XrML File Error",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    return(false);
                }

                WriteStatus("   Building UnsignedPublishLicense");
                WriteStatus("       from '" + xrmlFilename + "'.");
                UnsignedPublishLicense unsignedLicense =
                    new UnsignedPublishLicense(xrmlString);
                ContentUser author = unsignedLicense.Owner;

                //<SnippetRmPkgPubGrants>
                // The XRML template <RANGETIME> and <INTERVALTIME> elements are
                // ignored by the UnsignedPublishLicense(xrmlString) constructor.
                // To specify these values for the license, the ContentGrant
                // ValidFrom and ValidUntil properties must be explicitly set.
                // The following code sample demonstrates how to set the
                // ContentGrant properties for ValidFrom and ValidUntil.

                // Create a copy of the original XRML template ContentGrants
                // set by the UnsignedPublishLicense(xrmlString) constructor.
                ICollection <ContentGrant> tmpGrants = new List <ContentGrant>();
                foreach (ContentGrant grant in unsignedLicense.Grants)
                {
                    tmpGrants.Add(grant);
                }

                // Erase all original UnsignedPublishLicense ContentGrants.
                unsignedLicense.Grants.Clear();

                // Add each original grant back to the UnsignedPublishLicense
                // with appropriate ValidFrom and ValidUntil date/time values.
                foreach (ContentGrant grant in tmpGrants)
                {
                    unsignedLicense.Grants.Add(new ContentGrant(
                                                   grant.User, grant.Right,
                                                   DateTime.MinValue,   // set ValidFrom as appropriate
                                                   DateTime.MaxValue)); // set ValidUntil as appropriate
                }
                //</SnippetRmPkgPubGrants>

                WriteStatus("   Building secure environment.");
                try
                {
                    string applicationManifest = "<manifest></manifest>";
                    if (File.Exists("rpc.xml"))
                    {
                        StreamReader manifestReader = File.OpenText("rpc.xml");
                        applicationManifest = manifestReader.ReadToEnd();
                    }

                    if (_secureEnv == null)
                    {
                        if (SecureEnvironment.IsUserActivated(new ContentUser(
                                                                  _currentUserId, AuthenticationType.Windows)))
                        {
                            _secureEnv = SecureEnvironment.Create(
                                applicationManifest, new ContentUser(
                                    _currentUserId, AuthenticationType.Windows));
                        }
                        else
                        {
                            _secureEnv = SecureEnvironment.Create(
                                applicationManifest,
                                AuthenticationType.Windows,
                                UserActivationMode.Permanent);
                        }
                    }
                }
                catch (RightsManagementException ex)
                {
                    MessageBox.Show("ERROR: Failed to build secure environment.\n" +
                                    "Exception: " + ex.Message + "\n\n" +
                                    ex.FailureCode.ToString() + "\n\n" + ex.StackTrace,
                                    "Rights Management Exception",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    return(false);
                }

                // If using Windows authentication and the Xrml owner name
                // does not match the current log-in name, show error message
                if ((author.AuthenticationType == AuthenticationType.Windows) &&
                    (author.Name != _currentUserId))
                {
                    MessageBox.Show("ERROR: The current user name does not " +
                                    "match the UnsignedPublishLicense owner.\n" +
                                    "Please check the owner <NAME> element contained in '" +
                                    xrmlFilename + "'\n\n" +
                                    "Current user log-in ID: " + _currentUserId + "\n" +
                                    "XrML UnsignedPublishLicense owner name: " + author.Name,
                                    "Incorrect Authentication Name",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    return(false);
                }

                WriteStatus("   Signing the UnsignedPublishLicense\n" +
                            "       to build the PublishLicense.");
                UseLicense     authorsUseLicense;
                PublishLicense publishLicense =
                    unsignedLicense.Sign(_secureEnv, out authorsUseLicense);

                WriteStatus("   Binding the author's UseLicense and");
                WriteStatus("       obtaining the CryptoProvider.");
                CryptoProvider cryptoProvider = authorsUseLicense.Bind(_secureEnv);

                WriteStatus("   Creating the EncryptedPackage.");
                Stream packageStream = File.OpenRead(packageFile);
                EncryptedPackageEnvelope ePackage =
                    EncryptedPackageEnvelope.CreateFromPackage(encryptedFile,
                                                               packageStream, publishLicense, cryptoProvider);

                WriteStatus("   Adding an author's UseLicense.");
                RightsManagementInformation rmi =
                    ePackage.RightsManagementInformation;
                rmi.SaveUseLicense(author, authorsUseLicense);

                ePackage.Close();
                WriteStatus("   Done - Package encryption complete.");

                WriteStatus("Verifying package encryption.");
                if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(encryptedFile))
                {
                    WriteStatus("   Confirmed - '" + encryptedFilename +
                                "' is encrypted.");
                }
                else
                {
                    MessageBox.Show("ERROR: '" + encryptedFilename +
                                    "' is NOT ENCRYPTED.", "Encryption Error",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    WriteStatus("ERROR: '" + encryptedFilename +
                                "' is NOT ENCRYPTED.\n");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                                ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                                "Runtime Exception",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            WritePrompt("See the RightsManagedPackageViewer sample for details " +
                        "on how to access the content of a rights managed package.");
            return(true);
        }// end:PublishRMPackage()
示例#9
0
        }// end:OnPublish()


        // ------------------------ PublishRMPackage --------------------------
        /// <summary>
        ///   Writes an encrypted righted managed package.</summary>
        /// <param name="packageFilepath">
        ///   The path and filename of the source document package.</param>
        /// <param name="filename">
        ///   The path and filename of the XrML rights management file.</param>
        /// <param name="encryptedFilepath">
        ///   The path and filename for writing the RM encrypted package.</param>
        /// <returns>
        ///   true if the encrypted package is written successfully;
        ///   otherwise false.</returns>
        public bool PublishRMPackage(
            string packageFile, string xrmlFile, string encryptedFile)
        {
            string xrmlString;

            // Extract individual filenames without the path.
            string packageFilename   = packageFile.Remove( 0,
                                            packageFile.LastIndexOf('\\')+1 );
            string xrmlFilename      = xrmlFile.Remove( 0,
                                            xrmlFile.LastIndexOf('\\')+1 );
            string encryptedFilename = encryptedFile.Remove( 0,
                                            encryptedFile.LastIndexOf('\\')+1 );

            try
            {
                //<SnippetRmPkgPubUnPubLic>
                WriteStatus("   Reading '" + xrmlFilename + "' permissions.");
                try
                {
                    StreamReader sr = File.OpenText(xrmlFile);
                    xrmlString = sr.ReadToEnd();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("ERROR: '"+xrmlFilename+"' open failed.\n"+
                        "Exception: " + ex.Message, "XrML File Error",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                WriteStatus("   Building UnsignedPublishLicense");
                WriteStatus("       from '" + xrmlFilename + "'.");
                UnsignedPublishLicense unsignedLicense =
                    new UnsignedPublishLicense(xrmlString);
                ContentUser author = unsignedLicense.Owner;
                //</SnippetRmPkgPubUnPubLic>

                //<SnippetRmPkgBldSecEnv>
                WriteStatus("   Building secure environment.");
                try
                {
                    //<SnippetRmPkgPubSecEnv>
                    string applicationManifest = "<manifest></manifest>";
                    if (File.Exists("rpc.xml"))
                    {
                        StreamReader manifestReader = File.OpenText("rpc.xml");
                        applicationManifest = manifestReader.ReadToEnd();
                    }

                    if (_secureEnv == null)
                    {
                        if (SecureEnvironment.IsUserActivated(new ContentUser(
                                    _currentUserId, AuthenticationType.Windows)))
                        {
                            _secureEnv = SecureEnvironment.Create(
                                applicationManifest, new ContentUser(
                                    _currentUserId, AuthenticationType.Windows));
                        }
                        else
                        {
                            _secureEnv = SecureEnvironment.Create(
                                applicationManifest,
                                AuthenticationType.Windows,
                                UserActivationMode.Permanent);
                        }
                    }
                    //</SnippetRmPkgPubSecEnv>
                }
                catch (RightsManagementException ex)
                {
                    MessageBox.Show("ERROR: Failed to build secure environment.\n" +
                        "Exception: " + ex.Message + "\n\n" +
                        ex.FailureCode.ToString() + "\n\n" + ex.StackTrace,
                        "Rights Management Exception",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
                //</SnippetRmPkgBldSecEnv>

                // If using Windows authentication and the Xrml owner name
                // does not match the current log-in name, show error message
                if ((author.AuthenticationType == AuthenticationType.Windows)
                    && (author.Name != _currentUserId))
                {
                    MessageBox.Show("ERROR: The current user name does not " +
                        "match the UnsignedPublishLicense owner.\n" +
                        "Please check the owner <NAME> element contained in '" +
                        xrmlFilename + "'\n\n" +
                        "Current user log-in ID: " + _currentUserId + "\n" +
                        "XrML UnsignedPublishLicense owner name: " + author.Name,
                        "Incorrect Authentication Name",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                   return false;
                }

                //<SnippetRmPkgPubEncrypt>
                WriteStatus("   Signing the UnsignedPublishLicense\n" +
                            "       to build the PublishLicense.");
                UseLicense authorsUseLicense;
                PublishLicense publishLicense =
                    unsignedLicense.Sign(_secureEnv, out authorsUseLicense);

                WriteStatus("   Binding the author's UseLicense and");
                WriteStatus("       obtaining the CryptoProvider.");
                CryptoProvider cryptoProvider = authorsUseLicense.Bind(_secureEnv);

                WriteStatus("   Creating the EncryptedPackage.");
                Stream packageStream = File.OpenRead(packageFile);
                EncryptedPackageEnvelope ePackage =
                    EncryptedPackageEnvelope.CreateFromPackage(encryptedFile,
                        packageStream, publishLicense, cryptoProvider);

                WriteStatus("   Adding an author's UseLicense.");
                RightsManagementInformation rmi =
                    ePackage.RightsManagementInformation;
                rmi.SaveUseLicense(author, authorsUseLicense);

                ePackage.Close();
                WriteStatus("   Done - Package encryption complete.");

                WriteStatus("Verifying package encryption.");
                if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(encryptedFile))
                {
                    WriteStatus("   Confirmed - '" + encryptedFilename +
                                "' is encrypted.");
                }
                else
                {
                    MessageBox.Show("ERROR: '" + encryptedFilename +
                        "' is NOT ENCRYPTED.", "Encryption Error",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    WriteStatus("ERROR: '" + encryptedFilename +
                                "' is NOT ENCRYPTED.\n");
                    return false;
                }
                //</SnippetRmPkgPubEncrypt>
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                    ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                    "Runtime Exception",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            WritePrompt("See the RightsManagedPackageViewer sample for details " +
                "on how to access the content of a rights managed package.");
            return true;
        }// end:PublishRMPackage()
示例#10
0
        public bool OpenEncryptedDocument(string xpsFile)
        {
            // Check to see if the document is encrypted.
            // If not encrypted, use OpenDocument().
            if (!EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(xpsFile))
                return OpenDocument(xpsFile);

            ShowStatus("Opening encrypted '" + Filename(xpsFile) + "'");

            // Get the ID of the current user log-in.
            string currentUserId;
            try
                { currentUserId = GetDefaultWindowsUserName(); }
            catch
                { currentUserId = null; }
            if (currentUserId == null)
            {
                MessageBox.Show("No valid user ID available", "Invalid User ID",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                ShowStatus("   No valid user ID available.");
                return false;
            }

            ShowStatus("   Current user ID:  '" + currentUserId + "'");
            ShowStatus("   Using " + _authentication + " authentication.");
            ShowStatus("   Checking rights list for user:\n       " +
                           currentUserId);
            ShowStatus("   Initializing the environment.");

            try
            {
                string applicationManifest = "<manifest></manifest>";
                if (File.Exists("rvc.xml"))
                {
                    ShowStatus("   Reading manifest 'rvc.xml'.");
                    StreamReader manifestReader = File.OpenText("rvc.xml");
                    applicationManifest = manifestReader.ReadToEnd();
                }

                ShowStatus("   Initiating SecureEnvironment as user: \n       " +
                    currentUserId + " [" + _authentication + "]");
                if (SecureEnvironment.IsUserActivated(
                    new ContentUser(currentUserId, _authentication)))
                {
                    ShowStatus("   User is already activated.");
                    _secureEnv = SecureEnvironment.Create(applicationManifest,
                                    new ContentUser(currentUserId, _authentication));
                }
                else // if user is not yet activated.
                {
                    ShowStatus("   User is NOT activated,\n       activating now....");
                    // If using the current Windows user, no credentials are
                    // required and we can use UserActivationMode.Permanent.
                    _secureEnv = SecureEnvironment.Create(applicationManifest,
                                    _authentication, UserActivationMode.Permanent);

                    // If not using the current Windows user, use
                    // UserActivationMode.Temporary to display the Windows
                    // credentials pop-up window.
                    ///_secureEnv = SecureEnvironment.Create(applicationManifest,
                    ///     a_authentication, UserActivationMode.Temporary);
                }
                ShowStatus("   Created SecureEnvironment for user:\n       " +
                    _secureEnv.User.Name +
                    " [" + _secureEnv.User.AuthenticationType + "]");

                ShowStatus("   Opening the encrypted Package.");
                EncryptedPackageEnvelope ePackage =
                    EncryptedPackageEnvelope.Open(xpsFile, FileAccess.ReadWrite);
                RightsManagementInformation rmi =
                    ePackage.RightsManagementInformation;

                ShowStatus("   Looking for an embedded UseLicense for user:\n       " +
                           currentUserId + " [" + _authentication + "]");
                UseLicense useLicense =
                    rmi.LoadUseLicense(
                        new ContentUser(currentUserId, _authentication));

                ReadOnlyCollection<ContentGrant> grants;
                if (useLicense == null)
                {
                    ShowStatus("   No Embedded UseLicense found.\n       " +
                               "Attempting to acqure UseLicnese\n       " +
                               "from the PublishLicense.");
                    PublishLicense pubLicense = rmi.LoadPublishLicense();

                    ShowStatus("   Referral information:");

                    if (pubLicense.ReferralInfoName == null)
                        ShowStatus("       Name: (null)");
                    else
                        ShowStatus("       Name: " + pubLicense.ReferralInfoName);

                    if (pubLicense.ReferralInfoUri == null)
                        ShowStatus("    Uri: (null)");
                    else
                        ShowStatus("    Uri: " +
                            pubLicense.ReferralInfoUri.ToString());

                    useLicense = pubLicense.AcquireUseLicense(_secureEnv);
                    if (useLicense == null)
                    {
                        ShowStatus("   User DOES NOT HAVE RIGHTS\n       " +
                            "to access this document!");
                        return false;
                    }
                }// end:if (useLicense == null)
                ShowStatus("   UseLicense acquired.");

                ShowStatus("   Binding UseLicense with the SecureEnvironment" +
                         "\n       to obtain the CryptoProvider.");
                rmi.CryptoProvider = useLicense.Bind(_secureEnv);

                ShowStatus("   Obtaining BoundGrants.");
                grants = rmi.CryptoProvider.BoundGrants;

                // You can access the Package via GetPackage() at this point.

                rightsBlock.Text = "GRANTS LIST\n-----------\n";
                foreach (ContentGrant grant in grants)
                {
                    rightsBlock.Text += "USER  :"******" [" +
                        grant.User.AuthenticationType + "]\n";
                    rightsBlock.Text += "RIGHT :" + grant.Right.ToString()+"\n";
                    rightsBlock.Text += "    From:  " + grant.ValidFrom + "\n";
                    rightsBlock.Text += "    Until: " + grant.ValidUntil + "\n";
                }

                if (rmi.CryptoProvider.CanDecrypt == true)
                    ShowStatus("   Decryption granted.");
                else
                    ShowStatus("   CANNOT DECRYPT!");

                ShowStatus("   Getting the Package from\n" +
                           "      the EncryptedPackage.");
                _xpsPackage = ePackage.GetPackage();
                if (_xpsPackage == null)
                {
                    MessageBox.Show("Unable to get Package.");
                    return false;
                }

                // Set a PackageStore Uri reference for the encrypted stream.
                // ("sdk://packLocation" is a pseudo URI used by
                //  PackUriHelper.Create to define the parserContext.BaseURI
                //  that XamlReader uses to access the encrypted data stream.)
                Uri packageUri = new Uri(@"sdk://packLocation", UriKind.Absolute);
                // Add the URI package
                PackageStore.AddPackage(packageUri, _xpsPackage);
                // Determine the starting part for the package.
                PackagePart startingPart = GetPackageStartingPart(_xpsPackage);

                // Set the DocViewer.Document property.
                ShowStatus("   Opening in DocumentViewer.");
                ParserContext parserContext = new ParserContext();
                parserContext.BaseUri = PackUriHelper.Create(
                                            packageUri, startingPart.Uri);
                parserContext.XamlTypeMapper = XamlTypeMapper.DefaultMapper;
                DocViewer.Document = XamlReader.Load(
                    startingPart.GetStream(), parserContext)
                        as IDocumentPaginatorSource;

                // Enable document menu controls.
                menuFileClose.IsEnabled = true;
                menuFilePrint.IsEnabled = true;
                menuViewIncreaseZoom.IsEnabled = true;
                menuViewDecreaseZoom.IsEnabled = true;

                // Give the DocumentViewer focus.
                DocViewer.Focus();
            }// end:try
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                    ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                    "Exception",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            this.Title = "RightsManagedPackageViewer SDK Sample - " +
                         Filename(xpsFile) + " (encrypted)";
            return true;
        }// end:OpenEncryptedDocument()
 public static EncryptedPackageEnvelope CreateFromPackage(Stream envelopeStream, Stream packageStream, PublishLicense publishLicense, CryptoProvider cryptoProvider)
 {
     throw new NotImplementedException();
 }
 public static EncryptedPackageEnvelope Create(string envelopeFileName, PublishLicense publishLicense, CryptoProvider cryptoProvider)
 {
     throw new NotImplementedException();
 }
示例#13
0
 public void SavePublishLicense(PublishLicense publishLicense)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Save the publish license to the RM transform's instance data stream.
 /// </summary>
 /// <param name="publishLicense">
 /// The publish licence to be saved. The RM server returns a publish license as a string.
 /// </param>
 /// <remarks>
 /// The stream is rewritten from the beginning, so any existing publish license is
 /// overwritten.
 /// </remarks>
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="publishLicense"/> is null.
 /// </exception>
 /// <exception cref="FileFormatException">
 /// If the existing RM instance data in this file cannot be updated by the current version
 /// of this class.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// If the transform settings are fixed.
 /// </exception>
 public void SavePublishLicense(PublishLicense publishLicense)
 {
     _rmet.SavePublishLicense(publishLicense);
 }