// ------------------------------ OnOpen ------------------------------ /// <summary> /// Handles the user "File | Open" menu operation.</summary> private void OnOpen(object target, ExecutedRoutedEventArgs args) { // Create a "File Open" dialog positioned to the // "Content\" folder containing the sample fixed document. WinForms.OpenFileDialog dialog = new WinForms.OpenFileDialog(); dialog.InitialDirectory = GetContentFolder(); dialog.CheckFileExists = true; dialog.Filter = "XPS Document files (*.xps)|*.xps"; // Show the "File Open" dialog. If the user picks a file and // clicks "OK", load and display the specified XPS document. if (dialog.ShowDialog() == true) { CloseDocument(); // Close current document if open. _xpsFile = dialog.FileName; // Save the path and file name. // Check to see if the document is encrypted. // If encrypted, use OpenEncryptedDocument(). if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(_xpsFile)) OpenEncryptedDocument(_xpsFile); // Otherwise open as a normal document. else OpenDocument(_xpsFile); } }// end:OnOpen()
// Token: 0x06006CC3 RID: 27843 RVA: 0x001F4BD9 File Offset: 0x001F2DD9 internal EncryptedPackageFilter(EncryptedPackageEnvelope encryptedPackage) { if (encryptedPackage == null) { throw new ArgumentNullException("encryptedPackage"); } this._filter = new IndexingFilterMarshaler(new CorePropertiesFilter(encryptedPackage.PackageProperties)); }
/// <summary> /// <see cref="MS.Internal.Documents.Application.IDocumentController"/> /// </summary> bool IDocumentController.Rebind(Document document) { RightsDocument doc = (RightsDocument)document; // see class remarks on why this is ok Stream ciphered = doc.Dependency.Source; Stream clear = ciphered; if (doc.IsRebindNeeded) { if (doc.SourcePackage != null) { CloseEnvelope(doc.SourcePackage); doc.SourcePackage = null; } EncryptedPackageEnvelope envelope = null; PackageProperties properties = null; bool isSourceProtected = doc.IsSourceProtected(); if (isSourceProtected) { envelope = OpenEnvelopeOnStream(ciphered); doc.SourcePackage = envelope; properties = new SuppressedProperties(envelope); } DocumentProperties.Current.SetRightsManagedProperties(properties); DocumentRightsManagementManager.Current.SetEncryptedPackage(envelope); if (isSourceProtected) { clear = DocumentRightsManagementManager.Current.DecryptPackage(); if (clear != null) { clear = new RightsManagementSuppressedStream( clear, DocumentRightsManagementManager.Current.HasPermissionToEdit); // Reset the position of the stream since GetPackageStream will // create a package and move the stream pointer somewhere else clear.Position = 0; } else { Trace.SafeWrite( Trace.Rights, "You do not have rights for the current document."); return(false); } } doc.SourceProxy.Target = clear; } return(true); }
// Token: 0x06006CA8 RID: 27816 RVA: 0x001F41B4 File Offset: 0x001F23B4 void IPersistFile.Load(string pszFileName, int dwMode) { if (pszFileName == null || pszFileName == string.Empty) { throw new ArgumentException(SR.Get("FileNameNullOrEmpty"), "pszFileName"); } STGM_FLAGS stgm_FLAGS = (STGM_FLAGS)(dwMode & 4096); if (stgm_FLAGS == STGM_FLAGS.CREATE) { throw new ArgumentException(SR.Get("FilterLoadInvalidModeFlag"), "dwMode"); } FileMode fileMode = FileMode.Open; stgm_FLAGS = (STGM_FLAGS)(dwMode & 3); if (stgm_FLAGS == STGM_FLAGS.READ || stgm_FLAGS == STGM_FLAGS.READWRITE) { FileAccess fileAccess = FileAccess.Read; FileShare fileSharing = FileShare.ReadWrite; Invariant.Assert(this._package == null || this._encryptedPackage == null); this.ReleaseResources(); this._filter = null; this._xpsFileName = null; bool flag = EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(pszFileName); try { this._packageStream = XpsFilter.FileToStream(pszFileName, fileMode, fileAccess, fileSharing, 1048576L); if (flag) { this._encryptedPackage = EncryptedPackageEnvelope.Open(this._packageStream); this._filter = new EncryptedPackageFilter(this._encryptedPackage); } else { this._package = Package.Open(this._packageStream); this._filter = new PackageFilter(this._package); } } catch (IOException ex) { throw new COMException(ex.Message, -2147215613); } catch (FileFormatException ex2) { throw new COMException(ex2.Message, -2147215604); } finally { if (this._filter == null) { this.ReleaseResources(); } } this._xpsFileName = pszFileName; return; } throw new ArgumentException(SR.Get("FilterLoadInvalidModeFlag"), "dwMode"); }
//-------------------------------------------------------------------------- // IDisposable Members //-------------------------------------------------------------------------- /// <summary> /// <see cref="MS.Internal.Documents.Application.Document"/> /// </summary> protected override void Dispose(bool disposing) { try { if (disposing) { // our base is StreamDocument, as these packages support // the stream we want our base to release them first ReleaseStreams(); // The only code that actually requires this assert are the // calls to Close. Regardless I've put the assert around the // whole block since the rest of the code under it is almost // all just checking packages for null or setting them to null. // This is much cleaner than having three separate asserts (and // three more try/finally blocks) for each Close call. try { if (DestinationPackage != null) { if (DestinationPackage == SourcePackage) { SourcePackage = null; } DestinationPackage.Close(); DestinationPackage = null; } } finally { try { if (WorkspacePackage != null) { WorkspacePackage.Close(); WorkspacePackage = null; } } finally { if (SourcePackage != null) { SourcePackage.Close(); SourcePackage = null; } } } } } finally { base.Dispose(disposing); } }
/// <summary> /// Returns true when the source stream is an encrypted package envelope. /// </summary> internal bool IsSourceProtected() { if (SourcePackage != null) { return(true); } Stream sourceStream = this.Dependency.Source; return(EncryptedPackageEnvelope.IsEncryptedPackageEnvelope( sourceStream)); }
void IPersistStream.Load(MS.Internal.Interop.IStream stream) { // Check argument. if (stream == null) { throw new ArgumentNullException("stream"); } // Only one of _package and _encryptedPackage can be non-null at a time. Invariant.Assert(_package == null || _encryptedPackage == null); // If there has been a previous call to Load, reinitialize everything. // Note closing a closed stream does not cause any exception. ReleaseResources(); _filter = null; _xpsFileName = null; try { _packageStream = new UnsafeIndexingFilterStream(stream); // different filter for encrypted package if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(_packageStream)) { // Open the encrypted package. _encryptedPackage = EncryptedPackageEnvelope.Open(_packageStream); _filter = new EncryptedPackageFilter(_encryptedPackage); } else { // Open the package. _package = Package.Open(_packageStream); _filter = new PackageFilter(_package); } } catch (IOException ex) { throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_ACCESS); } catch (Exception ex) { throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_UNKNOWNFORMAT); } finally { // clean-up if we failed if (_filter == null) { ReleaseResources(); } } }
//-------------------------------------------------------------------------- // Internal Methods //-------------------------------------------------------------------------- /// <summary> /// Returns true when the destination stream is an encrypted package envelope. /// </summary> internal bool IsDestinationProtected() { if (DestinationPackage != null) { return(true); } Stream destinationStream = this.Dependency.Destination; return(EncryptedPackageEnvelope.IsEncryptedPackageEnvelope( destinationStream)); }
/// <summary> /// Retrieves and creates a rights management suppressed stream around the /// decrypted stream from a given encrypted package envelope. The stream /// returned should not be handed out to untrusted code. /// </summary> /// <param name="envelope">The envelope to decrypt and suppress</param> /// <param name="allowWrite">True if editing the suppressed stream should /// be allowed</param> /// <returns>The new demand-suppressed stream</returns> /// <remarks> /// This function exists to centralize the asserts needed to use encrypted /// package envelopes. /// </remarks> private static Stream DecryptEnvelopeAndSuppressStream( EncryptedPackageEnvelope envelope, bool allowWrite) { Stream clear = null; clear = envelope.GetPackageStream(); clear = new RightsManagementSuppressedStream(clear, allowWrite); // Reset the position of the stream since GetPackageStream will // create a package and move the stream pointer somewhere else clear.Position = 0; return(clear); }
/// <summary> /// Constructor. /// </summary> /// <param name="encryptedPackage">EncryptedPackageEnvelope to filter on</param> internal EncryptedPackageFilter(EncryptedPackageEnvelope encryptedPackage) { if (encryptedPackage == null) { throw new ArgumentNullException("encryptedPackage"); } // // Since CorePropertiesFilter is implemented as // a managed filter (supports IManagedFilter interface), // IndexingFilterMarshaler is used to get IFilter interface out of it. // _filter = new IndexingFilterMarshaler( new CorePropertiesFilter( encryptedPackage.PackageProperties )); }
void IPersistStream.Load(IStream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } Invariant.Assert(this._package == null || this._encryptedPackage == null); this.ReleaseResources(); this._filter = null; this._xpsFileName = null; try { this._packageStream = new UnsafeIndexingFilterStream(stream); if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(this._packageStream)) { this._encryptedPackage = EncryptedPackageEnvelope.Open(this._packageStream); this._filter = new EncryptedPackageFilter(this._encryptedPackage); } else { this._package = Package.Open(this._packageStream); this._filter = new PackageFilter(this._package); } } catch (IOException ex) { throw new COMException(ex.Message, -2147215613); } catch (Exception ex2) { throw new COMException(ex2.Message, -2147215604); } finally { if (this._filter == null) { this.ReleaseResources(); } } }
}// end:OnOpen() // --------------------------- OpenDocument --------------------------- /// <summary> /// Loads and displays a given XPS document file.</summary> /// <param name="filename"> /// The path and file name of the XPS /// document to load and display.</param> /// <returns> /// true if the document loads successfully; otherwise false.</returns> public bool OpenDocument(string xpsFile) { // Check to see if the document is encrypted. // If encrypted, use OpenEncryptedDocument(). if (EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(xpsFile)) return OpenEncryptedDocument(xpsFile); // Document is not encrypted, open normally. ShowStatus("Opening '" + Filename(xpsFile) + "'"); _packageUri = new Uri(xpsFile, UriKind.Absolute); try { _xpsDocument = new XpsDocument(xpsFile, FileAccess.Read); } catch (System.IO.FileFormatException ex) { MessageBox.Show(xpsFile + "\n\nThe file " + "is not a valid XPS document.\n\n" + "Exception: " + ex.Message + "\n\n" + ex.GetType().ToString() + "\n\n" + ex.StackTrace, "Invalid File Format", MessageBoxButton.OK, MessageBoxImage.Error); return false; } // Get the document's PackageStore into which // new user annotations will be added and saved. _xpsPackage = PackageStore.GetPackage(_packageUri); if ((_xpsPackage == null) || (_xpsDocument == null)) { MessageBox.Show("Unable to get Package from file."); return false; } // Get the FixedDocumentSequence from the open document. FixedDocumentSequence fds = _xpsDocument.GetFixedDocumentSequence(); if (fds == null) { MessageBox.Show(xpsFile + "\n\nThe document package within " + "the specified file does not contain a " + "FixedDocumentSequence.", "Package Error"); return false; } // Load the FixedDocumentSequence to the DocumentViewer control. DocViewer.Document = fds; // Enable document menu controls. menuFileClose.IsEnabled = true; menuFilePrint.IsEnabled = true; menuViewIncreaseZoom.IsEnabled = true; menuViewDecreaseZoom.IsEnabled = true; // Give the DocumentViewer focus. docViewer.Focus(); this.Title = "RightsManagedPackageViewer SDK Sample - " + Filename(xpsFile); return true; }// end:OpenDocument()
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()
//-------------------------------------------------------------------------- // Constructors //-------------------------------------------------------------------------- internal SuppressedProperties(EncryptedPackageEnvelope envelope) { _target = envelope.PackageProperties; }
/// <summary> /// <see cref="MS.Internal.Documents.Application.IDocumentController"/> /// </summary> bool IDocumentController.SavePreperation(Document document) { bool handled = false; RightsDocument doc = (RightsDocument)document; // see class remarks on why this is ok Stream ciphered = doc.Dependency.Destination; Stream clear = ciphered; // We protect the actual decrypted content (if necessary) using the // RightsManagementSuppressedStream that prevents callers from writing // to it. This still allows us to save an acquired use license back to // the package even if the user does not have the permissions to modify // the document itself. It also means that there is no need to check if // the user has permission to save before starting the operation. // If we are encrypted and the destination stream is identical to the // source stream, there is no need to create a new envelope. Instead we // can simply open the envelope on the destination stream, which // already contains the complete encrypted envelope that was the source // file. // // It doesn't actually matter to this class why the flag was set, but // we know the destination is identical to the source in two situations: // 1) The source and the destination are the same file, and since the // publish license didn't change there is no need to write to a // temporary file first // 2) The destination file was copied directly from the source file. if (doc.IsDestinationProtected() && doc.IsDestinationIdenticalToSource) { // we can't reuse protections because EncryptedPackage caches the // original permissions for the stream (if we re-open the package r/w // the Encrypted package will still be r/o) doc.DestinationPackage = OpenEnvelopeOnStream( doc.Dependency.Destination); doc.DestinationPackage.RightsManagementInformation.CryptoProvider = doc.SourcePackage.RightsManagementInformation.CryptoProvider; clear = DecryptEnvelopeAndSuppressStream( doc.DestinationPackage, DocumentRightsManagementManager.Current.HasPermissionToEdit); doc.DestinationProxy = new StreamProxy(clear); // save the use license in case the user acquired one _provider.Value.SaveUseLicense(doc.DestinationPackage); handled = true; Trace.SafeWrite( Trace.Rights, "Reused CryptoProvider as underlying stream is the same."); } else // we are not protected and/or the RM protections have changed { bool canEdit = DocumentRightsManagementManager.Current.HasPermissionToEdit; // canEdit should always be true here - either the document is not // protected, or the protections have been changed. In the latter // case, the user has to have Owner permissions to change the // protections, and that of course includes Edit permissions. Invariant.Assert( canEdit, "Cannot save with changes if Edit permission was not granted."); EncryptedPackageEnvelope encryptedPackage = _provider.Value.EncryptPackage(ciphered); // the destination is intended to be encrypted when a non-null // value is returned if (encryptedPackage != null) { clear = DecryptEnvelopeAndSuppressStream( encryptedPackage, canEdit); doc.DestinationPackage = encryptedPackage; } Trace.SafeWriteIf( encryptedPackage == null, Trace.Rights, "Destination package is unprotected."); doc.DestinationProxy = new StreamProxy(clear); // If the destination file is not identical to the source file, we // need to copy the (possibly decrypted) source stream to the // destination here. if (!doc.IsDestinationIdenticalToSource) { StreamHelper.CopyStream(doc.Source, doc.Destination); doc.DestinationProxy.Flush(); Trace.SafeWrite( Trace.Rights, "Copied Source contents to Destination."); } handled = true; } return(handled); }
/// <summary> /// Close the EncryptedPackageEnvelope passed in as an argument. /// </summary> /// <param name="envelope">The envelope to close</param> /// <remarks> /// This function exists to centralize the asserts needed to use encrypted /// package envelopes. /// </remarks> private static void CloseEnvelope(EncryptedPackageEnvelope envelope) { envelope.Close(); }
//-------------------------------------------------------------------------- // Private Methods //-------------------------------------------------------------------------- /// <summary> /// Opens an EncryptedPackageEnvelope on a given stream. /// </summary> /// <param name="ciphered">The encrypted stream</param> /// <returns>An EncryptedPackageEnvelope on the stream</returns> /// <remarks> /// This function exists to centralize the asserts needed to use encrypted /// package envelopes. /// </remarks> private static EncryptedPackageEnvelope OpenEnvelopeOnStream(Stream ciphered) { return(EncryptedPackageEnvelope.Open(ciphered)); }
//-------------------------------------------------------------------------- // IDocumentController Members //-------------------------------------------------------------------------- /// <summary> /// <see cref="MS.Internal.Documents.Application.IDocumentController"/> /// </summary> bool IDocumentController.EnableEdit(Document document) { RightsDocument doc = (RightsDocument)document; // see class remarks on why this is ok Stream ciphered = doc.Dependency.Workspace; Stream clear = ciphered; bool canEdit = DocumentRightsManagementManager.Current.HasPermissionToEdit; EncryptedPackageEnvelope encryptedPackage = null; // If editing the document is allowed (i.e. the document is either // not RM protected, or the user has permission to edit it), create // a temporary editing file if (canEdit) { try { encryptedPackage = _provider.Value.EncryptPackage(ciphered); if (encryptedPackage != null) { clear = DecryptEnvelopeAndSuppressStream( encryptedPackage, canEdit); doc.WorkspacePackage = encryptedPackage; } } catch (RightsManagementException exception) { RightsManagementErrorHandler.HandleOrRethrowException( RightsManagementOperation.Other, exception); // Bail out return(true); } if (encryptedPackage != null) { Trace.SafeWrite( Trace.Rights, "Editing package is RM protected."); } else { Trace.SafeWrite( Trace.Rights, "Editing package is unprotected."); } doc.WorkspaceProxy = new StreamProxy(clear); } else { Trace.SafeWrite( Trace.Rights, "Did not create editing package because user does not have permission to edit."); } return(canEdit); }
}// 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()
/// <summary> /// Opens the specified file with the specified mode.. /// This can return any of the STG_E_* error codes, along /// with S_OK, E_OUTOFMEMORY, and E_FAIL. /// </summary> /// <param name="pszFileName"> /// A zero-terminated string containing the absolute path of the file to open. /// </param> /// <param name="dwMode">The mode in which to open pszFileName. </param> void IPersistFile.Load(string pszFileName, int dwMode) { FileMode fileMode; FileAccess fileAccess; FileShare fileSharing; // Check argument. if (pszFileName == null || pszFileName == String.Empty) { throw new ArgumentException(SR.Get(SRID.FileNameNullOrEmpty), "pszFileName"); } // Convert mode information in flag. switch ((STGM_FLAGS)(dwMode & (int)STGM_FLAGS.MODE)) { case STGM_FLAGS.CREATE: throw new ArgumentException(SR.Get(SRID.FilterLoadInvalidModeFlag), "dwMode"); default: fileMode = FileMode.Open; break; } // Convert access flag. switch ((STGM_FLAGS)(dwMode & (int)STGM_FLAGS.ACCESS)) { case STGM_FLAGS.READ: case STGM_FLAGS.READWRITE: fileAccess = FileAccess.Read; break; default: throw new ArgumentException(SR.Get(SRID.FilterLoadInvalidModeFlag), "dwMode"); } // Sharing flags are ignored. Since managed filters do not have the equivalent // of a destructor to release locks on files as soon as they get disposed of from // unmanaged code, the option taken is not to lock at all while filtering. // (See call to FileToStream further down.) fileSharing = FileShare.ReadWrite; // Only one of _package and _encryptedPackage can be non-null at a time. Invariant.Assert(_package == null || _encryptedPackage == null); // If there has been a previous call to Load, reinitialize everything. // Note closing a closed stream does not cause any exception. ReleaseResources(); _filter = null; _xpsFileName = null; bool encrypted = EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(pszFileName); try { // opens to MemoryStream or just returns FileStream if file exceeds _maxMemoryStreamBuffer _packageStream = FileToStream(pszFileName, fileMode, fileAccess, fileSharing, _maxMemoryStreamBuffer); if (encrypted) { // Open the encrypted package. _encryptedPackage = EncryptedPackageEnvelope.Open(_packageStream); _filter = new EncryptedPackageFilter(_encryptedPackage); } else { // Open the package. _package = Package.Open(_packageStream); _filter = new PackageFilter(_package); } } catch (IOException ex) { throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_ACCESS); } catch (FileFormatException ex) { throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_UNKNOWNFORMAT); } finally { // failure? if (_filter == null) { // clean up ReleaseResources(); } } _xpsFileName = pszFileName; }
}// 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()
/// <summary> /// <see cref="MS.Internal.Documents.Application.IDocumentController"/> /// </summary> bool IDocumentController.Open(Document document) { RightsDocument doc = (RightsDocument)document; // see class remarks on why this is ok Stream ciphered = doc.Dependency.Source; Stream clear = ciphered; bool isSourceProtected = doc.IsSourceProtected(); if (isSourceProtected) { // Do not catch exceptions here - there can be no mitigation EncryptedPackageEnvelope envelope = OpenEnvelopeOnStream(ciphered); PackageProperties properties = new SuppressedProperties(envelope); doc.SourcePackage = envelope; DocumentProperties.Current.SetRightsManagedProperties(properties); } RightsManagementProvider provider = new RightsManagementProvider(doc.SourcePackage); _provider.Value = provider; try { DocumentRightsManagementManager.Initialize(provider); DocumentRightsManagementManager.Current.PublishLicenseChange += new EventHandler(delegate(object sender, EventArgs args) { Trace.SafeWrite( Trace.Rights, "Disabling file copy for current document."); doc.IsFileCopySafe = false; DocumentManager.CreateDefault().EnableEdit(null); }); if (isSourceProtected) { clear = DocumentRightsManagementManager.Current.DecryptPackage(); if (clear != null) { clear = new RightsManagementSuppressedStream( clear, DocumentRightsManagementManager.Current.HasPermissionToEdit); // Reset the position of the stream since GetPackageStream will // create a package and move the stream pointer somewhere else clear.Position = 0; } else { Trace.SafeWrite( Trace.Rights, "You do not have rights for the current document."); return(false); } } } catch { // If anything failed here, we cannot use the provider any longer, // so we can dispose it provider.Dispose(); _provider.Value = null; throw; } if (clear != null) { doc.SourceProxy = new StreamProxy(clear); } else { // If decryption failed, we can no longer do anything with the // provider instance or the current RM manager provider.Dispose(); _provider.Value = null; } return(true); }