internal IssuanceLicense( DateTime validFrom, DateTime validUntil, string referralInfoName, Uri referralInfoUri, ContentUser owner, string issuanceLicense, SafeRightsManagementHandle boundLicenseHandle, Guid contentId, ICollection <ContentGrant> grantCollection, IDictionary <int, LocalizedNameDescriptionPair> localizedNameDescriptionDictionary, IDictionary <string, string> applicationSpecificDataDictionary, int rightValidityIntervalDays, RevocationPoint revocationPoint) { Initialize( validFrom, validUntil, referralInfoName, referralInfoUri, owner, issuanceLicense, boundLicenseHandle, contentId, grantCollection, localizedNameDescriptionDictionary, applicationSpecificDataDictionary, rightValidityIntervalDays, revocationPoint); }
private SafeRightsManagementPubHandle GetHandleFromUser(ContentUser user) { SafeRightsManagementPubHandle userHandle = null; int hr; // We need to create Internal Authnetication type Users differently if (user.GenericEquals(ContentUser.AnyoneUser) || user.GenericEquals(ContentUser.OwnerUser)) { // Anyone user hr = SafeNativeMethods.DRMCreateUser( user.Name, // This is an optional UI Name (some applications use this and do not work well when it is missing) user.Name, // that would be string Anyone or Owner ConvertAuthenticationTypeToString(user), // this would be internal out userHandle); } else { // Windws Passport or WindowsPassport authentication type user hr = SafeNativeMethods.DRMCreateUser( user.Name, null, ConvertAuthenticationTypeToString(user), out userHandle); } Errors.ThrowOnErrorCode(hr); Debug.Assert((userHandle != null) && (!userHandle.IsInvalid)); _pubHandlesList.Add(userHandle); return(userHandle); }
public async Task <IActionResult> RemoveAdmin(string id) { ContentUser contentUser = await _userManager.FindByIdAsync(id); if (contentUser != null && contentUser.UserName != "SuperAdmin") { var result = await _userManager.RemoveFromRoleAsync(contentUser, "Admin"); } return(RedirectToAction("Index")); }
public async Task <IActionResult> AddAdmin(string id) { ContentUser contentUser = await _userManager.FindByIdAsync(id); if (contentUser != null) { var result = await _userManager.AddToRoleAsync(contentUser, "Admin"); } return(RedirectToAction("Index")); }
/// <summary> /// Converts Authentication type enumeration into a string that can be accepted by the unmanaged code /// </summary> private string ConvertAuthenticationTypeToString(ContentUser user) { if (user.AuthenticationType == AuthenticationType.WindowsPassport) { return(UnspecifiedAuthenticationType); } else { return(user.AuthenticationType.ToString()); } }
public async Task <IActionResult> SignUp(IdentityCreateViewModel identityCreate, string firstName, string lastName, DateTime birthDate) { if (ModelState.IsValid) { ContentUser contentUser = new ContentUser(); contentUser.UserName = identityCreate.UserName; contentUser.FirstName = firstName; contentUser.LastName = lastName; contentUser.BirthDate = birthDate; var result = await _userManager.CreateAsync(contentUser, identityCreate.Password); if (result.Succeeded) { return(RedirectToAction("Login")); } ViewBag.Msg = "Failed to sign up."; } return(View(identityCreate)); }
public static IHost CreateDatabaseIfNotExist(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <IdentityContentDbContext>(); context.Database.Migrate(); if (!context.Roles.Any()) // are there any roles? If not then this is a new database. { var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); roleManager.CreateAsync(new IdentityRole("Admin")).Wait(); roleManager.CreateAsync(new IdentityRole("Member")).Wait(); var userManager = services.GetRequiredService <UserManager <ContentUser> >(); ContentUser superAdmin = new ContentUser() { UserName = "******" }; userManager.CreateAsync(superAdmin, "India@123456").Wait(); superAdmin = userManager.FindByNameAsync("SuperAdmin").Result; userManager.AddToRoleAsync(superAdmin, "Admin").Wait(); } return(host); } catch (Exception) { throw; } } }
}// 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> /// constructor that buils an issuance license from scratch /// </summary> private void Initialize( DateTime validFrom, DateTime validUntil, string referralInfoName, Uri referralInfoUri, ContentUser owner, string issuanceLicense, SafeRightsManagementHandle boundLicenseHandle, Guid contentId, ICollection <ContentGrant> grantCollection, IDictionary <int, LocalizedNameDescriptionPair> localizedNameDescriptionDictionary, IDictionary <string, string> applicationSpecificDataDictionary, int rightValidityIntervalDays, RevocationPoint revocationPoint) { // according to the unmanaged RM SDK spec only the following scenarios are supported: // 1. This can be called to create an issuance license from a template. // issuanceLicense An unsigned issuance license from // a file or by passing an issuance license // handle into DRMGetIssuanceLicenseTemplate // boundLicenseHandle NULL // // 2. This allows you to reuse rights information (the list follows this table). // issuance license A signed issuance license // boundLicenseHandle Handle to license bound by OWNER or VIEWRIGHTSDATA right // // 3. This creates an issuance license from scratch. It includes no users, rights, metadata, or policies. // issuance license NULL // boundLicenseHandle NULL Debug.Assert(!boundLicenseHandle.IsClosed); // it must be either present or not // closed handle is an indication of some internal error Invariant.Assert((boundLicenseHandle.IsInvalid) || (issuanceLicense != null)); SystemTime validFromSysTime = null; SystemTime validUntilSysTime = null; if ((validFrom != DateTime.MinValue) || (validUntil != DateTime.MaxValue)) { // we need to use non null values if at least one of the time boundaries isn't default // DRM SDK will not enforce date time unless both timeFrom and timeUnti are set validFromSysTime = new SystemTime((DateTime)validFrom); validUntilSysTime = new SystemTime((DateTime)validUntil); } string referralInfoUriStr = null; if (referralInfoUri != null) { referralInfoUriStr = referralInfoUri.ToString(); } // input parameter must be initialized to the invalid handle // attempt to pass in a null throws an exception from the Safe // Handle Marshalling code SafeRightsManagementPubHandle ownerHandle; if (owner != null) { ownerHandle = GetHandleFromUser(owner); } else { ownerHandle = SafeRightsManagementPubHandle.InvalidHandle; } int hr; _issuanceLicenseHandle = null; hr = SafeNativeMethods.DRMCreateIssuanceLicense( validFromSysTime, validUntilSysTime, referralInfoName, referralInfoUriStr, ownerHandle, issuanceLicense, boundLicenseHandle, out _issuanceLicenseHandle); Errors.ThrowOnErrorCode(hr); Invariant.Assert((_issuanceLicenseHandle != null) && (!_issuanceLicenseHandle.IsInvalid)); Debug.Assert(rightValidityIntervalDays >= 0); // our internal code makes the guarantee that is is not negative if (rightValidityIntervalDays > 0) { // If it is 0 we shouldn't override the value as it might be coming from a template SafeNativeMethods.DRMSetIntervalTime(_issuanceLicenseHandle, (uint)rightValidityIntervalDays); } if (grantCollection != null) { foreach (ContentGrant grant in grantCollection) { AddGrant(grant); } } // Set localized name description info if (localizedNameDescriptionDictionary != null) { foreach (KeyValuePair <int, LocalizedNameDescriptionPair> nameDescriptionEntry in localizedNameDescriptionDictionary) { AddNameDescription(nameDescriptionEntry.Key, nameDescriptionEntry.Value); } } // Set application specific data if (applicationSpecificDataDictionary != null) { foreach (KeyValuePair <string, string> applicationSpecificDataEntry in applicationSpecificDataDictionary) { AddApplicationSpecificData(applicationSpecificDataEntry.Key, applicationSpecificDataEntry.Value); } } // set metafata as required if (contentId != null) { hr = SafeNativeMethods.DRMSetMetaData( _issuanceLicenseHandle, contentId.ToString("B"), DefaultContentType, null, null, null, null); Errors.ThrowOnErrorCode(hr); } // set revocation point if required if (revocationPoint != null) { SetRevocationPoint(revocationPoint); } }
private void GetIssuanceLicenseInfo( out DateTime timeFrom, out DateTime timeUntil, DistributionPointInfo distributionPointInfo, out string distributionPointName, out string distributionPointUri, out ContentUser owner, out bool officialFlag) { uint distributionPointNameLength = 0; uint distributionPointUriLength = 0; bool officialFlagTemp = false; SafeRightsManagementPubHandle ownerHandleTemp = null; int hr = SafeNativeMethods.DRMGetIssuanceLicenseInfo( _issuanceLicenseHandle, null, null, (uint)distributionPointInfo, ref distributionPointNameLength, null, ref distributionPointUriLength, null, out ownerHandleTemp, out officialFlagTemp); Errors.ThrowOnErrorCode(hr); if (ownerHandleTemp != null) { // As a result of calling DRMGetIssuanceLicenseInfo twice, // we are getting 2 handles. We are going to dispose the first one // and preserve the second one. ownerHandleTemp.Dispose(); ownerHandleTemp = null; } StringBuilder distributionPointNameTemp = null; // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 if (distributionPointNameLength > 0) { distributionPointNameTemp = new StringBuilder(checked ((int)distributionPointNameLength)); } StringBuilder distributionPointUriTemp = null; // allocate memory as necessary, it seems that Unmanaged libraries really do not like // getting a non null buffer of size 0 if (distributionPointUriLength > 0) { distributionPointUriTemp = new StringBuilder(checked ((int)distributionPointUriLength)); } SystemTime timeFromTemp = new SystemTime(DateTime.Now); SystemTime timeUntilTemp = new SystemTime(DateTime.Now); hr = SafeNativeMethods.DRMGetIssuanceLicenseInfo( _issuanceLicenseHandle, timeFromTemp, timeUntilTemp, (uint)distributionPointInfo, ref distributionPointNameLength, distributionPointNameTemp, ref distributionPointUriLength, distributionPointUriTemp, out ownerHandleTemp, out officialFlagTemp); Errors.ThrowOnErrorCode(hr); timeFrom = timeFromTemp.GetDateTime(DateTime.MinValue); timeUntil = timeUntilTemp.GetDateTime(DateTime.MaxValue); // only if we got some data back we shall try to process it if (distributionPointNameTemp != null) { distributionPointName = distributionPointNameTemp.ToString(); } else { distributionPointName = null; } // only if we got some data back we shall try to process it if (distributionPointUriTemp != null) { distributionPointUri = distributionPointUriTemp.ToString(); } else { distributionPointUri = null; } // if we have owner let's convert it to a user and preserve // handler for further destruction owner = null; if (ownerHandleTemp != null) { _pubHandlesList.Add(ownerHandleTemp); if (!ownerHandleTemp.IsInvalid) { owner = GetUserFromHandle(ownerHandleTemp); } } officialFlag = officialFlagTemp; }
/// <summary> /// Load a use license for the specified user from the RM transform's instance data /// storage in the compound file. /// </summary> /// <param name="userKey"> /// The user whose use license is desired. /// </param> /// <returns> /// The use license for the specified user, or null if the compound file does not /// contain a use license for the specified user. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="userKey"/> is null. /// </exception> /// <exception cref="FileFormatException"> /// If the RM information in this file cannot be read by the current version of /// this class. /// </exception> public UseLicense LoadUseLicense(ContentUser userKey) { return(_rmet.LoadUseLicense(userKey)); }
static private ContentUser GetUserFromHandle(SafeRightsManagementPubHandle userHandle) { uint userNameLength = 0; StringBuilder userName = null; uint userIdLength = 0; StringBuilder userId = null; uint userIdTypeLength = 0; StringBuilder userIdType = null; int hr = SafeNativeMethods.DRMGetUserInfo(userHandle, ref userNameLength, null, ref userIdLength, null, ref userIdTypeLength, null); Errors.ThrowOnErrorCode(hr); if (userNameLength > 0) { // only allocate memory if we got a non-zero size back userName = new StringBuilder(checked ((int)userNameLength)); } if (userIdLength > 0) { // only allocate memory if we got a non-zero size back userId = new StringBuilder(checked ((int)userIdLength)); } if (userIdTypeLength > 0) { // only allocate memory if we got a non-zero size back userIdType = new StringBuilder(checked ((int)userIdTypeLength)); } hr = SafeNativeMethods.DRMGetUserInfo(userHandle, ref userNameLength, userName, ref userIdLength, userId, ref userIdTypeLength, userIdType); Errors.ThrowOnErrorCode(hr); // Convert String Builder values to string values string userNameStr = null; if (userName != null) { userNameStr = userName.ToString(); } string userIdTypeStr = null; if (userIdType != null) { userIdTypeStr = userIdType.ToString().ToUpperInvariant(); } string userIdStr = null; if (userId != null) { userIdStr = userId.ToString().ToUpperInvariant(); } // based on the UserTypeId build appropriate instance of User class if (String.CompareOrdinal(userIdTypeStr, AuthenticationType.Windows.ToString().ToUpperInvariant()) == 0) { return(new ContentUser(userNameStr, AuthenticationType.Windows)); } else if (String.CompareOrdinal(userIdTypeStr, AuthenticationType.Passport.ToString().ToUpperInvariant()) == 0) { return(new ContentUser(userNameStr, AuthenticationType.Passport)); } else if (String.CompareOrdinal(userIdTypeStr, AuthenticationType.Internal.ToString().ToUpperInvariant()) == 0) { // internal anyone user if (ContentUser.CompareToAnyone(userIdStr)) { return(ContentUser.AnyoneUser); } else if (ContentUser.CompareToOwner(userIdStr)) { return(ContentUser.OwnerUser); } } else if (String.CompareOrdinal(userIdTypeStr, UnspecifiedAuthenticationType.ToUpperInvariant()) == 0) { return(new ContentUser(userNameStr, AuthenticationType.WindowsPassport)); } throw new RightsManagementException(RightsManagementFailureCode.InvalidLicense); }
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(); }
/// <summary> /// Save a use license for the specified user into the RM transform's instance data /// storage in the compound file. /// </summary> /// <param name="userKey"> /// The user to whom the use license was issued. /// </param> /// <param name="useLicense"> /// The use license issued to that user. /// </param> /// <remarks> /// Any existing use license for the specified user is removed from the compound /// file before the new use license is saved. /// </remarks> /// <exception cref="ArgumentNullException"> /// If <paramref name="userKey"/> or <paramref name="useLicense"/> is null. /// </exception> /// <exception cref="FileFormatException"> /// If the RM information in this file cannot be written by the current version of /// this class. /// </exception> public void SaveUseLicense(ContentUser userKey, UseLicense useLicense) { _rmet.SaveUseLicense(userKey, useLicense); }
}// 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()
/// <summary> /// Delete the use license for the specified user from the RM transform's instance /// data storage in the compound file. /// </summary> /// <param name="userKey"> /// The user whose use license is to be deleted. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="userKey"/> is null. /// </exception> /// <exception cref="FileFormatException"> /// If the RM information in this file cannot be updated by the current version of /// this class. /// </exception> public void DeleteUseLicense(ContentUser userKey) { _rmet.DeleteUseLicense(userKey); }
}// 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()
public void DeleteUseLicense(ContentUser userKey) { throw new NotImplementedException(); }
/// <summary> /// Creates a RightsManagementUser object from the given ContentUser /// object. /// </summary> /// <param name="user">The ContentUser to copy</param> /// <returns>A RightsManagementUser that has the same properties as the /// user passed in as an argument</returns> internal static RightsManagementUser CreateUser(ContentUser user) { return(new RightsManagementUser( user.Name, user.AuthenticationType)); }
public void SaveUseLicense(ContentUser userKey, UseLicense useLicense) { throw new NotImplementedException(); }
public UseLicense LoadUseLicense(ContentUser userKey) { throw new NotImplementedException(); }