コード例 #1
0
        }// end:OpenContent()


        // ---------------------- OpenEncryptedContent -----------------------
        /// <summary>
        ///   Loads and displays a given encrypted content file.</summary>
        /// <param name="encryptedFile">
        ///   The path and name of the encrypted file to display.</param>
        /// <returns>
        ///   true if the file loads successfully; otherwise false.</returns>
        public bool OpenEncryptedContent(string encryptedFile)
        {
            // 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();
                }

                if (_secureEnv == null)
                {
                    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,
                        //                        _authentication,
                        //                        UserActivationMode.Temporary);
                    }
                    ShowStatus("   Created SecureEnvironment for user:\n       " +
                        _secureEnv.User.Name +
                        " [" + _secureEnv.User.AuthenticationType + "]");
                }

                // If the file is a supported image, show it in the image control.
                try
                {
                    // In this sample a UseLicense is provided with the example
                    // content files.  If the UseLicense for the current user
                    // does not exist, the following steps can be performed to
                    // obtain a UseLicense:
                    //   1. Open the PublishLicense.
                    //   2. Read the PublishLicense XML file to a string.
                    //   3. Create a PublishLicense instance passing the
                    //      PublishLicense string to the constructor.
                    //   4. Pass the PublishLicense to the license server to
                    //      obtain a UseLicense.

                    // Check if there is a UseLicense for the encryptedFile.
                    string useLicenseFile = encryptedFile;
                    if (encryptedFile.EndsWith(".protected"))
                    {   // Remove ".protected" from the file name.
                        useLicenseFile = useLicenseFile.Remove(
                            useLicenseFile.Length - ".protected".Length );
                    }
                    // Append ".UseLicense.xml" as the UseLicense file extension.
                    useLicenseFile = useLicenseFile + ".UseLicense.xml";
                    if (!File.Exists(useLicenseFile))
                    {
                        MessageBox.Show(useLicenseFile + "\n\nUseLicense for '" +
                            Filename(encryptedFile) + "' not found.",
                            "UseLicense Not Found",
                            MessageBoxButton.OK, MessageBoxImage.Error);
                        ShowStatus("   UseLicense not found:\n      '" +
                                    Filename(useLicenseFile) + "'.");
                        return false;
                    }

                    ShowStatus("   Reading UseLicense '" +
                                   Filename(useLicenseFile) + "'.");
                    StreamReader useLicenseStream = File.OpenText(useLicenseFile);
                    string useLicenseString = useLicenseStream.ReadToEnd();
                    UseLicense useLicense = new UseLicense(useLicenseString);

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

                    ShowStatus("   Obtaining BoundGrants.");
                    ReadOnlyCollection<ContentGrant> grants =
                        cryptoProvider.BoundGrants;

                    rightsBlockTitle.Text = "Rights - " + Filename(useLicenseFile);
                    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 (cryptoProvider.CanDecrypt == true)
                        ShowStatus("   Decryption granted.");
                    else
                        ShowStatus("   CANNOT DECRYPT!");

                    ShowStatus("   Decrypting '"+Filename(encryptedFile)+"'.");
                    byte[] imageBuffer;
                    using (Stream cipherTextStream = File.OpenRead(encryptedFile))
                    {
                        byte[] contentLengthByteBuffer = new byte[sizeof(Int32)];
                        // Read the length of the source content file
                        // from the first four bytes of the encrypted file.
                        ReliableRead(cipherTextStream, contentLengthByteBuffer,
                                     0, sizeof(Int32));

                        // Allocate the clearText buffer.
                        int contentLength =
                            BitConverter.ToInt32(contentLengthByteBuffer, 0);
                        imageBuffer = new byte[contentLength];

                        // Allocate the cipherText block.
                        byte[] cipherTextBlock =
                            new byte[cryptoProvider.BlockSize];

                        // decrypt cipherText to clearText block by block.
                        int imageBufferIndex = 0;
                        for ( ; ; )
                        {   // Read cipherText block.
                            int readCount = ReliableRead(
                                                cipherTextStream,
                                                cipherTextBlock, 0,
                                                cryptoProvider.BlockSize);
                            // readCount of zero is end of data.
                            if (readCount == 0)
                                break; // for

                            // Decrypt cipherText to clearText.
                            byte[] clearTextBlock =
                                cryptoProvider.Decrypt(cipherTextBlock);

                            // Copy the clearTextBlock to the imageBuffer.
                            int copySize = Math.Min(clearTextBlock.Length,
                                                contentLength-imageBufferIndex);
                            Array.Copy(clearTextBlock, 0,
                                imageBuffer, imageBufferIndex, copySize);
                            imageBufferIndex += copySize;
                        }
                    }// end:using (Stream cipherTextStream = (close/dispose)

                    ShowStatus("   Displaying decrypted image.");
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = new MemoryStream(imageBuffer);
                    bitmapImage.EndInit();
                    ImageViewer.Source = bitmapImage;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(encryptedFile + "\n\nThe specified file " +
                        "in not a valid unprotected image file.\n\n" +
                        "Exception: " + ex.Message + "\n\n" +
                        ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                        "Invalid File Format",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }// 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;
            }

            return true;
        }// end:OpenEncryptedContent()
コード例 #2
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()