Esempio n. 1
0
        internal void UpdateUnsignedPublishLicense(UnsignedPublishLicense unsignedPublishLicense)
        {
            Invariant.Assert(unsignedPublishLicense != null);

            DateTime timeFrom;
            DateTime timeUntil;
            DistributionPointInfo distributionPointInfo = DistributionPointInfo.ReferralInfo;
            string      distributionPointName;
            string      distributionPointUri;
            ContentUser owner;
            bool        officialFlag;

            GetIssuanceLicenseInfo(out timeFrom,
                                   out timeUntil,
                                   distributionPointInfo,
                                   out distributionPointName,
                                   out distributionPointUri,
                                   out owner,
                                   out officialFlag);

            unsignedPublishLicense.ReferralInfoName = distributionPointName;

            if (distributionPointUri != null)
            {
                unsignedPublishLicense.ReferralInfoUri = new Uri(distributionPointUri);
            }
            else
            {
                unsignedPublishLicense.ReferralInfoUri = null;
            }

            unsignedPublishLicense.Owner = owner;

            // Let's get the validity Iterval information (days) and save it in the license
            uint validityDays = 0;
            int  hr           = SafeNativeMethods.DRMGetIntervalTime(_issuanceLicenseHandle, ref validityDays);

            Errors.ThrowOnErrorCode(hr);
            checked { unsignedPublishLicense.RightValidityIntervalDays = (int)validityDays; }

            // let's get the rights information
            int userIndex = 0;

            while (true) // in this loop we are enumerating users mentioned in the license
            {
                SafeRightsManagementPubHandle userHandle = null;

                // extract the user based on the index
                ContentUser user = GetIssuanceLicenseUser(userIndex, out userHandle);

                if ((user == null) || (userHandle == null))
                {
                    break;
                }

                int rightIndex = 0;
                while (true) // now we can enumerate rights granted to the given user
                {
                    SafeRightsManagementPubHandle rightHandle = null;
                    DateTime validFrom;
                    DateTime validUntil;

                    // extract the right based on the index and the user
                    Nullable <ContentRight> right = GetIssuanceLicenseUserRight
                                                        (userHandle, rightIndex, out rightHandle, out validFrom, out validUntil);

                    // 0 right handle is an indication of the end of the list
                    if (rightHandle == null)
                    {
                        break;
                    }

                    // right == null is an indication of a right that we didn't recognize
                    // we should still continue the enumeration
                    if (right != null)
                    {
                        // Add the grant for the User Right pair here
                        unsignedPublishLicense.Grants.Add(
                            new ContentGrant(user, right.Value, validFrom, validUntil));
                    }

                    rightIndex++;
                }
                userIndex++;
            }

            // let's get the localized name description pairs
            int nameIndex = 0;

            while (true) // in this loop we are enumerating nameDescription pairs mentioned in the license
            {
                int localeId;

                // extract the user based on the index
                LocalizedNameDescriptionPair nameDescription = GetLocalizedNameDescriptionPair(nameIndex,
                                                                                               out localeId);
                if (nameDescription == null)
                {
                    break;
                }

                // Add the name description info to the license
                unsignedPublishLicense.LocalizedNameDescriptionDictionary.Add(localeId, nameDescription);
                nameIndex++;
            }

            // let's get the application specific data
            int appDataIndex = 0;

            while (true) // in this loop we are enumerating nameDescription pairs mentioned in the license
            {
                // extract the user based on the index

                Nullable <KeyValuePair <string, string> > appSpecificDataEntry = GetApplicationSpecificData(appDataIndex);

                if (appSpecificDataEntry == null)
                {
                    break;
                }

                // Add the name description info to the license
                unsignedPublishLicense.ApplicationSpecificDataDictionary.Add(appSpecificDataEntry.Value.Key, appSpecificDataEntry.Value.Value);
                appDataIndex++;
            }

            // Get the revocation Point information, it is optional and can be null
            unsignedPublishLicense.RevocationPoint = GetRevocationPoint();
        }
Esempio n. 2
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()
Esempio n. 3
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()
Esempio n. 4
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()