static void ProtectwithAzure(string filePath, SymmetricKeyCredential symmKey1) { try { Collection <TemplateInfo> templates = SafeNativeMethods.IpcGetTemplateList( connectionInfo: null, forceDownload: false, suppressUI: true, offline: false, hasUserConsent: true, parentWindow: IntPtr.Zero, cultureInfo: null, credentialType: symmKey1); Console.WriteLine("Loaded Templates {0}", templates.Count); var template = templates[0]; SafeFileApiNativeMethods.IpcfEncryptFile( inputFile: filePath, templateId: template.TemplateId, flags: SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, suppressUI: true, offline: false, hasUserConsent: true, parentWindow: IntPtr.Zero, symmKey: symmKey1, outputDirectory: null); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("File: {0} has been encrypted successfully", filePath); Console.ResetColor(); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(); Console.WriteLine("Error occured while loading of templates"); Console.WriteLine(e.ToString()); Console.ResetColor(); } }
private RmsContentPublisher(SymmetricKeyCredential _servicePrincipalTuple) { symmetricKey = _servicePrincipalTuple; }
// if you are outside North America please uncomment this section as it is needed /* static Uri IntranetURL = new Uri(ConfigurationManager.AppSettings["LicensingIntranetDistributionPointUrl"]); * static Uri ExtranetURL = new Uri(ConfigurationManager.AppSettings["LicensingExtranetDistributionPointUrl"]); * static ConnectionInfo connectionInfo = new ConnectionInfo(ExtranetURL, IntranetURL); */ static void Main(string[] args) { //Returns error if Main fails to execute correctly try { //Loads MSIPC.dll SafeNativeMethods.IpcInitialize(); SafeNativeMethods.IpcSetAPIMode(APIMode.Server); //SafeNativeMethods.IpcSetStoreName("AzureIpTest"); //Loads credentials for the service principal from App.Config SymmetricKeyCredential symmetricKeyCred = new SymmetricKeyCredential(); symmetricKeyCred.AppPrincipalId = ConfigurationManager.AppSettings["AppPrincipalId"]; symmetricKeyCred.Base64Key = ConfigurationManager.AppSettings["Base64Key"]; symmetricKeyCred.BposTenantId = ConfigurationManager.AppSettings["BposTenantId"]; //Prompts user to choose whether to encrypt using Azure Template or Ad Hoc Policy Console.WriteLine("Please select the desired encryption method (Enter 1 or 2)"); Console.WriteLine("1. Protect via Azure Template \n2. Protect via Ad Hoc Policy"); string method = Console.ReadLine(); //Logic to handle user's encryption choice & invalid input if (method == EncryptionMethod1 || method == EncryptionMethod2) { Console.WriteLine("Please enter the path to the file to be encrypted."); string filePath = Console.ReadLine(); //Returns error if no file path is entered if (filePath.Trim() != "" && File.Exists(filePath)) { //Checks the encryption status of file from the input path var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filePath); if (!checkEncryptionStatus.ToString().ToLower().Contains(alreadyEncrypted)) { if (method == EncryptionMethod1) { //Encrypt a file via Azure Template ProtectWithTemplate(symmetricKeyCred, filePath); } else if (method == EncryptionMethod2) { //Encrypt a file using Ad-Hoc policy ProtectWithAdHocPolicy(symmetricKeyCred, filePath); } } else { Console.WriteLine("The file has already been encrypted."); Console.WriteLine("Would you like to decrypt it (Y/N) ? "); string response = Console.ReadLine(); response = response.Trim().ToLower(); if (response == "y") { try { string decryptedFilePath = SafeFileApiNativeMethods.IpcfDecryptFile(filePath.Trim(), SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT, false, false, false, IntPtr.Zero, symmetricKeyCred, null, null); Console.WriteLine(" The decrypted file is at the following location :" + decryptedFilePath); } catch (Exception dx) { Console.WriteLine("Error:" + dx); Console.WriteLine("Press any key"); string resp = Console.ReadLine(); } } else if (response.Trim().ToLower() == "n") { Console.WriteLine("Program Exiting .... "); System.Environment.Exit(0); } else { System.Environment.Exit(0); } } } else { Console.WriteLine("Please enter a valid file path."); } } else { Console.WriteLine("Invalid Input. Please enter 1, 2, or 3"); } } catch (Exception ex) { Console.WriteLine("An unexpected error occurred : {0}", ex); } }
/// <summary> /// Protect a file using an ad-hoc policy /// </summary> /// <param name = "filePath" > input file path</param> /// <param name = " symmetricKeyCredential" > key storing the credentials for the service public static void ProtectWithAdHocPolicy(SymmetricKeyCredential symmetricKeyCredential, string filePath) { //Requests policy owner Console.WriteLine("Please enter the policy owner's email."); string owner = Console.ReadLine(); //Returns error if no owner email is entered if (owner.Trim() != "") { //Ensures that owner input is a valid email address if (isEmailValid(owner)) { //Requests users to whom rights will be given and add to list Console.WriteLine( "Please enter the email(s) of user(s) you would like to have rights to the file.\n" + "Separate emails with spaces."); string usersWithRights = Console.ReadLine(); //Returns error if no user email is entered if (usersWithRights.Trim() != "") { bool userEmailsAreValid = true; string[] usersWithRightsList = usersWithRights.Split(' '); //Ensures that each user input is a valid email address foreach (string email in usersWithRightsList) { if (!isEmailValid(email)) { userEmailsAreValid = false; Console.WriteLine("Please enter valid user email address(es)."); break; } } if (userEmailsAreValid) { //Requests rights to give to specified users Console.WriteLine("Please select the rights you would like user(s) to have.\n" + "Separate rights with spaces."); //Outputs templates available for selection CommonRights commonRights = new CommonRights(); foreach (var field in commonRights.GetType().GetFields()) { Console.WriteLine("{0}", field.GetValue(commonRights)); } string selectedRights = Console.ReadLine(); //Returns error if no right is entered if (selectedRights.Trim() != "") { string[] selectedRightsList = selectedRights.Split(' '); Collection <string> rightsCollection = new Collection <string>(selectedRightsList); //Creates an ad hoc policy for specified users with specified rights Collection <UserRights> userRights = new Collection <UserRights>(); foreach (string s in usersWithRightsList) { userRights.Add(new UserRights(UserIdType.Email, s, rightsCollection)); } Console.WriteLine("Please enter a name for this policy."); string policyName = Console.ReadLine(); //Returns error if no policy name is entered if (policyName.Trim() != "") { Console.WriteLine("Please enter a description for this policy."); string policyDescription = Console.ReadLine(); //Returns error if no policy description is entered if (policyDescription.Trim() != "") { Console.WriteLine("Please enter a display name for the policy issuer."); string issuerDisplayName = Console.ReadLine(); //Returns error if no issuer display name is entered if (issuerDisplayName.Trim() != "") { // Gets the available issuers of rights policy templates. // The available issuers is a list of RMS servers that this user has already contacted. try { // If you are based outside of the North American geo you need to provide the connection info /* * Collection<TemplateIssuer> templateIssuers = SafeNativeMethods * .IpcGetTemplateIssuerList( * connectionInfo, * true, * false, * false, true, null, symmetricKeyCredential); */ Collection <TemplateIssuer> templateIssuers = SafeNativeMethods .IpcGetTemplateIssuerList( null, true, false, false, true, null, symmetricKeyCredential); // Creates the policy and associates the chosen user rights with it SafeInformationProtectionLicenseHandle handle = SafeNativeMethods.IpcCreateLicenseFromScratch( templateIssuers.ElementAt(0)); SafeNativeMethods.IpcSetLicenseOwner(handle, owner); SafeNativeMethods.IpcSetLicenseUserRightsList(handle, userRights); SafeNativeMethods.IpcSetLicenseDescriptor(handle, new TemplateInfo(null, CultureInfo.CurrentCulture, policyName, policyDescription, issuerDisplayName, false)); //Encrypts the file using the ad hoc policy string encryptedFilePath = SafeFileApiNativeMethods.IpcfEncryptFile( filePath, handle, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_KEY_NO_PERSIST, true, false, true, null, symmetricKeyCredential); } catch (Exception ex) { Console.WriteLine( "Please enter an owner and user(s) that exist in the Azure AD Tenant." + ex); } } else { Console.WriteLine("Please enter a name for the policy issuer."); } } else { Console.WriteLine("Please enter a description for the policy."); } } else { Console.WriteLine("Please enter a name for the policy."); } } else { Console.WriteLine( "Please enter at least one right from the list. Multiple rights must be separated by spaces."); } } } else { Console.WriteLine("Please enter user email address(es). Multiple email addresses must be separated by spaces."); } } else { Console.WriteLine("Please enter a valid owner email."); } } else { Console.WriteLine("Please enter a valid owner email."); } }
static void Main(string[] args) { //Returns error if Main fails to execute correctly try { //Loads MSIPC.dll SafeNativeMethods.IpcInitialize(); SafeNativeMethods.IpcSetAPIMode(APIMode.Server); //Loads credentials for the service principal from App.Config SymmetricKeyCredential symmetricKeyCred = new SymmetricKeyCredential(); symmetricKeyCred.AppPrincipalId = ConfigurationManager.AppSettings["AppPrincipalId"]; symmetricKeyCred.Base64Key = ConfigurationManager.AppSettings["Base64Key"]; symmetricKeyCred.BposTenantId = ConfigurationManager.AppSettings["BposTenantId"]; //Prompts user to choose whether to encrypt using Azure Template or Ad Hoc Policy Console.WriteLine("Please select the desired encryption method (Enter 1 or 2)"); Console.WriteLine("1. Protect via Azure Template \n2. Protect via Ad Hoc Policy"); string method = Console.ReadLine(); //Logic to handle user's encryption choice & invalid input if (method == EncryptionMethod1 || method == EncryptionMethod2) { Console.WriteLine("Please enter the path to the file to be encrypted."); string filePath = Console.ReadLine(); //Returns error if no file path is entered if (filePath.Trim() != "") { //Checks the encryption status of file from the input path var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filePath); if (!checkEncryptionStatus.ToString().ToLower().Contains(alreadyEncrypted)) { if (method == EncryptionMethod1) { //Encrypt a file via Azure Template ProtectWithTemplate(symmetricKeyCred, filePath); } else if (method == EncryptionMethod2) { //Encrypt a file using Ad-Hoc policy ProtectWithAdHocPolicy(symmetricKeyCred, filePath); } } else { Console.WriteLine("The file has already been encrypted."); } } else { Console.WriteLine("Please enter a valid file path."); } } else { Console.WriteLine("Invalid Input. Please enter 1 or 2."); } } catch (Exception ex) { Console.WriteLine("An unexpected error occurred : {0}", ex); } }
// if you are outside North America please uncomment this section as it is needed /* static Uri IntranetURL = new Uri(ConfigurationManager.AppSettings["LicensingIntranetDistributionPointUrl"]); * static Uri ExtranetURL = new Uri(ConfigurationManager.AppSettings["LicensingExtranetDistributionPointUrl"]); * static ConnectionInfo connectionInfo = new ConnectionInfo(ExtranetURL, IntranetURL); */ static void Main(string[] args) { //cria uma instância do leitor de código de barras var barcodeReader = new BarcodeReader(); //carrega o bitmap do código a ser lido para a memória var barcodeBitmap = (Bitmap)Bitmap.FromFile(@"<CAMINHO DO ARQUIVO>sample.png"); //decodifica o código de barras em memória var barcodeResult = barcodeReader.Decode(barcodeBitmap); //saída do resultado para o console Console.WriteLine("================================================================"); Console.WriteLine(".NET Barcode reader + Azure Information Protection by Raposinha"); Console.WriteLine("================================================================"); Console.WriteLine(""); Console.WriteLine("============================================================"); Console.WriteLine("PASSO 1: Obter o conteúdo do código de barras e seu formato"); Console.WriteLine("============================================================"); Console.ReadLine(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(@"Caminho do arquivo a ser decodificado: <CAMINHO DO ARQUIVO>sample.png"); Console.WriteLine($"Código de barras decodificado: {barcodeResult?.Text}"); Console.WriteLine($"Formato do código de barras: {barcodeResult?.BarcodeFormat}"); Console.ReadLine(); Console.ForegroundColor = ConsoleColor.White; barcodeBitmap.Dispose(); //Returns error if Main fails to execute correctly try { //Loads MSIPC.dll SafeNativeMethods.IpcInitialize(); SafeNativeMethods.IpcSetAPIMode(APIMode.Server); //SafeNativeMethods.IpcSetStoreName("AzureIpTest"); //Loads credentials for the service principal from App.Config SymmetricKeyCredential symmetricKeyCred = new SymmetricKeyCredential(); symmetricKeyCred.AppPrincipalId = ConfigurationManager.AppSettings["AppPrincipalId"]; symmetricKeyCred.Base64Key = ConfigurationManager.AppSettings["Base64Key"]; symmetricKeyCred.BposTenantId = ConfigurationManager.AppSettings["BposTenantId"]; //Prompts user to choose whether to encrypt using Azure Template or Ad Hoc Policy Console.WriteLine("============================================================"); Console.WriteLine("PASSO 2: Aplicar a política do Azure Information Protection"); Console.WriteLine("============================================================"); Console.WriteLine(""); Console.WriteLine("Selecione o método de proteção desejado (Digite 1 ou 2):"); Console.WriteLine("1. Proteger via Azure Template \n2. Proteger via Ad Hoc Policy"); string method = Console.ReadLine(); //Logic to handle user's encryption choice & invalid input if (method == EncryptionMethod1 || method == EncryptionMethod2) { Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(@"Caminho do arquivo a ser protegido: <CAMINHO DO ARQUIVO>sample.png"); Console.ForegroundColor = ConsoleColor.White; string filePath = @"<CAMINHO DO ARQUIVO>sample.png"; Console.WriteLine(""); //Console.ReadLine(); //Returns error if no file path is entered if (filePath.Trim() != "" && File.Exists(filePath)) { //Checks the encryption status of file from the input path var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filePath); if (!checkEncryptionStatus.ToString().ToLower().Contains(alreadyEncrypted)) { if (method == EncryptionMethod1) { //Encrypt a file via Azure Template ProtectWithTemplate(symmetricKeyCred, filePath); } else if (method == EncryptionMethod2) { //Encrypt a file using Ad-Hoc policy ProtectWithAdHocPolicy(symmetricKeyCred, filePath); } } else { Console.WriteLine("The file has already been encrypted."); Console.WriteLine("Would you like to decrypt it (Y/N) ? "); string response = Console.ReadLine(); response = response.Trim().ToLower(); if (response == "y") { try { string decryptedFilePath = SafeFileApiNativeMethods.IpcfDecryptFile(filePath.Trim(), SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT, false, false, false, IntPtr.Zero, null, null, null); Console.WriteLine(" The decrypted file is at the following location :" + decryptedFilePath); } catch (Exception dx) { Console.WriteLine("Error:" + dx); } } else if (response.Trim().ToLower() == "n") { Console.WriteLine("Program Exiting .... "); System.Environment.Exit(0); } else { System.Environment.Exit(0); } } } else { Console.WriteLine("Please enter a valid file path."); } } else { Console.WriteLine("Invalid Input. Please enter 1, 2, or 3"); } } catch (Exception ex) { Console.WriteLine("An unexpected error occurred : {0}", ex); } }
/// <summary> /// Load pdf file /// </summary> /// <param name="fileName"></param> /// <returns></returns> private bool LoadFile(string fileName) { bool isrmsProtect = true; byte[] license = null; try { //RMS化PDFファイルから、RMSライセンス情報と、暗号化された本文情報を分割する //RMS署名情報から、RMSサーバー情報を抽出する //RMSサーバーでの認証 //RMSサーバーからRMSライセンスの取得 license = SafeFileApiNativeMethods.IpcfGetSerializedLicenseFromFile(fileName); } catch (Exception ex) { isrmsProtect = false; } if (isrmsProtect) { try { //SymmetricKeyCredential symmkey = new SymmetricKeyCredential(); //symmkey.AppPrincipalId = "0C5BDABD-CF4D-4FBB-BF4A-DD62BCF7E976"; //symmkey.Base64Key = "P@ssw0rd"; //symmkey.BposTenantId = "*****@*****.**"; SymmetricKeyCredential symmkey = null; //RMSライセンスから、復号鍵の抽出 SafeInformationProtectionKeyHandle keyHandle = SafeNativeMethods.IpcGetKey(license, false, false, true, this); //symmkey = (SymmetricKeyCredential)keyHandle; //RMSライセンスから、権利リストの抽出 //Collection<UserRights> userRights = new Collection<UserRights>(); //userRights = SafeNativeMethods.IpcGetSerializedLicenseUserRightsList(license, keyHandle); bool accessGranted = SafeNativeMethods.IpcAccessCheck(keyHandle, "VIEW"); if (accessGranted) { SafeFileApiNativeMethods.IpcfDecryptFile(fileName, SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT, false, false, true, this, symmkey); } //使用権限が正しく設定されていません //ConnectionInfo connectionInfo = SafeNativeMethods.IpcGetSerializedLicenseConnectionInfo(license); //System.Collections.ObjectModel.Collection<TemplateIssuer> templateIssuerList = SafeNativeMethods.IpcGetTemplateIssuerList(connectionInfo, false, false, false, false, this, symmkey); //TemplateIssuer templateIssuer = templateIssuerList[0]; //SafeInformationProtectionLicenseHandle licenseHandle = SafeNativeMethods.IpcCreateLicenseFromScratch(templateIssuer); //SafeFileApiNativeMethods.IpcfEncryptFile(fileName, licenseHandle, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, false, false, false, this, symmkey); //テンプレートは管理者によって作成されていません //TemplateInfo templateInfo = SafeNativeMethods.IpcGetSerializedLicenseDescriptor(license, keyHandle, System.Globalization.CultureInfo.CurrentCulture); //SafeFileApiNativeMethods.IpcfEncryptFile(fileName, templateInfo.TemplateId, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, false, false, true, this, null); } catch (InformationProtectionException ex) { isrmsProtect = false; MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK); } catch (Exception ex) { isrmsProtect = false; } } try { pdfDoc.LoadPDF(fileName); return(true); } catch (System.Security.SecurityException sex) { String password = Interaction.InputBox("Please enter the document password:"******"Document Password", ""); if (password.Equals(string.Empty)) { return(false); } if (pdfDoc != null) { pdfDoc.Dispose(); pdfDoc = null; } pdfDoc = new PDFWrapper(); pdfDoc.UserPassword = password; return(LoadFile(fileName)); } catch (Exception ex) { return(false); } }
/// <summary> /// Used to get the HTTP authorization header /// </summary> /// <returns>Returned a string value containing the auth text value</returns> private string GetAuthorizationHeader() { string authzHeader = null; try { var context = new AuthenticationContext(Properties.FullTenantAddress); var credential = new SymmetricKeyCredential(Properties.IssuingResource, Convert.FromBase64String(Properties.SymmetricKey)); var token = context.AcquireToken(Properties.ServiceRealm, credential); authzHeader = token.CreateAuthorizationHeader(); } catch (Exception ex) { var aex = ex as AALException; throw new ApplicationException(aex.Message); } return authzHeader; }