Пример #1
0
        //Encrypt Procedure
        public void EncryptFile(string owner, Collection <UserRights> listOfRights, string filePath)
        {
            string fileName;
            string pathToFile;

            TemplateIssuer issuer;
            SafeInformationProtectionKeyHandle     keyhandle;
            SafeInformationProtectionLicenseHandle licenseHandle;

            fileName   = Path.GetFileName(filePath);
            pathToFile = Path.GetDirectoryName(filePath);

            issuer = new TemplateIssuer(null, owner, true);

            licenseHandle = SafeNativeMethods.IpcCreateLicenseFromScratch(issuer);

            SafeNativeMethods.IpcSetLicenseOwner(licenseHandle, owner);

            SafeNativeMethods.IpcSetLicenseUserRightsList(licenseHandle, listOfRights);

            byte[] license = SafeNativeMethods.IpcSerializeLicense(licenseHandle, 0, true, false, true, null, out keyhandle);

            Collection <UserRights> rights = SafeNativeMethods.IpcGetSerializedLicenseUserRightsList(license, keyhandle);

            SafeFileApiNativeMethods.IpcfEncryptFile(filePath, licenseHandle, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, true, false, true, null, pathToFile);
        }
Пример #2
0
        private void DecryptButton_Click(object sender, EventArgs e)
        {
            var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filepathBox.Text.Trim());

            if (checkEncryptionStatus.ToString().ToLower().Contains("encrypted"))
            {
                DialogResult isEncrypted = MessageBox.Show("此檔案已加密 \n 點選確定來解密");
                if (isEncrypted == DialogResult.OK)
                {
                    try
                    {
                        string       decryptedFilePath = SafeFileApiNativeMethods.IpcfDecryptFile(filepathBox.Text.Trim(), IPCF_DF_FLAG_DEFAULT, false, false, false, IntPtr.Zero, null, null, null);
                        DialogResult result            = MessageBox.Show("檔案解密到: \n " + decryptedFilePath);
                    }
                    catch (Exception ex)
                    {
                        DialogResult error = MessageBox.Show("Error: " + ex);
                        if (error == DialogResult.OK)
                        {
                            Application.Exit();
                        }
                    }
                }
            }
            else if (checkEncryptionStatus.ToString().ToLower().Contains("decrypted"))
            {
                MessageBox.Show("此檔案已無加密");
            }
        }
 static void DecryptFile(string filePath)
 {
     try
     {
         SafeFileApiNativeMethods.IpcfDecryptFile(
             inputFile: filePath,
             flags: SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_OPEN_AS_RMS_AWARE,
             suppressUI: true,
             offline: false,
             hasUserConsent: true,
             parentWindow: IntPtr.Zero,
             symmKey: null,
             outputDirectory: null);
         Console.ForegroundColor = ConsoleColor.Green;
         Console.WriteLine("File: {0} has been decrypted successfully", filePath);
         Console.ResetColor();
     }
     catch (InformationProtectionException e)
     {
         Console.ForegroundColor = ConsoleColor.Red;
         Console.WriteLine("Error occured while decrtypting file");
         Console.WriteLine(e.ToString());
         Console.ResetColor();
     }
 }
Пример #4
0
        private void btn_fileinfo_Click(object sender, EventArgs e)
        {
            string content = "";

            file_label.Text = "";
            var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filepathBox.Text.Trim());

            try
            {
                if (checkEncryptionStatus.ToString().ToLower().Contains("encrypted"))
                {
                    file_label.Text += "此檔案已加密";

                    ReadEncryptedContent(filepathBox.Text.Trim(), out content);
                    clear_log();
                    log.AppendText(content);
                }
                else
                {
                    file_label.Text += "此檔案尚未加密,可點選加密進行加密";
                    clear_log();
                }
            }
            catch
            {
                DialogResult error = MessageBox.Show("Error ");
            }
        }
Пример #5
0
        // Does not work
        static void EncryptFile(string filePath)
        {
            try
            {
                var templates = GetTemplates();
                var template  = templates[0];

                SafeFileApiNativeMethods.IpcfEncryptFile(
                    inputFile: filePath,
                    templateId: template.TemplateId,
                    flags: SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT,
                    suppressUI: true,
                    offline: false,
                    hasUserConsent: true,
                    parentForm: null,
                    symmKey: null,
                    outputDirectory: null);
            }
            catch (InformationProtectionException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine();
                Console.WriteLine("Error occured while encrtypting file");
                Console.WriteLine(e.ToString());
                Console.ResetColor();
            }
        }
        private void DecryptButton_Click(object sender, EventArgs e)
        {
            var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filepathBox.Text.Trim());

            if (checkEncryptionStatus.ToString().ToLower().Contains("encrypted"))
            {
                DialogResult isEncrypted = MessageBox.Show("Selected file is already Protected \n Please press OK to Unprotect");
                if (isEncrypted == DialogResult.OK)
                {
                    try
                    {
                        string       decryptedFilePath = SafeFileApiNativeMethods.IpcfDecryptFile(filepathBox.Text.Trim(), IPCF_DF_FLAG_DEFAULT, false, false, false, IntPtr.Zero, null, null, null);
                        DialogResult result            = MessageBox.Show("File has been Unprotected and is at the following location \n " + decryptedFilePath);
                    }
                    catch (Exception ex)
                    {
                        DialogResult error = MessageBox.Show("Error: " + ex);
                        if (error == DialogResult.OK)
                        {
                            Application.Exit();
                        }
                    }
                }
            }
            else if (checkEncryptionStatus.ToString().ToLower().Contains("decrypted"))
            {
                MessageBox.Show("The selected file is already Unprotected");
            }
        }
Пример #7
0
        /// <summary>
        /// Publishes content using MSIPC 2.x APIs
        /// </summary>
        /// <param name="rmsContent">rmsContent instance</param>
        public void PublishContent(RmsContent rmsContent)
        {
            Debug.Assert(rmsContent.RmsContentState == RmsContentState.Original);

            //bootstrap incase current machine was not bootstrapped
            SafeNativeMethods.IpcGetTemplateList(null,
                                                 false,
                                                 true,
                                                 false,
                                                 true,
                                                 null,
                                                 null,
                                                 this.symmetricKey);

            Stream sinkStream = rmsContent.SinkStream;

            string outputFilePath = SafeFileApiNativeMethods.IpcfEncryptFileStream(rmsContent.SourceStream,
                                                                                   rmsContent.OriginalFileNameWithExtension,
                                                                                   rmsContent.RmsTemplateId,
                                                                                   SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_KEY_NO_PERSIST_DISK,
                                                                                   true,
                                                                                   false,
                                                                                   true,
                                                                                   null,
                                                                                   this.symmetricKey,
                                                                                   ref sinkStream);

            rmsContent.PublishedFileNameWithExtension = Path.GetFileName(outputFilePath);

            rmsContent.SinkStream = sinkStream;
        }
Пример #8
0
        /// <summary>
        /// Handle File Watch Engine events for state changes and failures.
        /// </summary>
        private void fileWatchEngine_EngineEvent(object sender, EngineEventArgs e)
        {
            if (e.NotificationType == EngineNotificationType.Watching ||
                e.NotificationType == EngineNotificationType.Suspended)
            {
                this.Invoke(new AppendToLog(doAppendToLog), "** " + e.NotificationType.ToString() + "\r\n");
            }
            else if (e.NotificationType == EngineNotificationType.Processing)
            {
                this.Invoke(new AppendToLog(doAppendToLog), e.NotificationType.ToString() + ": " + e.FullPath + "...");

                if (currentProtectionPolicy != null &&
                    SafeFileApiNativeMethods.IpcfIsFileEncrypted(e.FullPath) == SafeFileApiNativeMethods.FileEncryptedStatus.IPCF_FILE_STATUS_DECRYPTED)
                {
                    SafeFileApiNativeMethods.IpcfEncryptFile(e.FullPath,
                                                             currentProtectionPolicy.TemplateId,
                                                             SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT,
                                                             true,
                                                             false,
                                                             true,
                                                             this);
                }

                this.Invoke(new AppendToLog(doAppendToLog), "Protected!\r\n");
            }
            else
            {
                this.Invoke(new AppendToLog(doAppendToLog), e.NotificationType.ToString() + "\r\n");
            }
        }
Пример #9
0
        /// <summary>
        /// Protect a file using an Azure Template
        /// </summary>
        /// <param name = "filePath" > input file path</param>
        /// <param name = " symmetricKeyCredential" > key storing the credentials for the service

        public static void ProtectWithTemplate(SymmetricKeyCredential symmetricKeyCredential, string filePath)
        {
            // If you are based outside of the North American geo you need to provide the connection info

            /* Uri IntranetURL = new Uri(ConfigurationManager.AppSettings["LicensingIntranetDistributionPointUrl"]);
             * Uri ExtranetURL = new Uri(ConfigurationManager.AppSettings["LicensingExtranetDistributionPointUrl"]);
             * ConnectionInfo connectionInfo = new ConnectionInfo(ExtranetURL, IntranetURL);
             * Collection<TemplateInfo> templates = SafeNativeMethods.IpcGetTemplateList(connectionInfo, false, true,
             *   false, true, null, null, symmetricKeyCredential); */

            // Gets the available templates for this tenant
            // if you uncomment the prior GetTemplateList call comment this call before you build
            Collection <TemplateInfo> templates = SafeNativeMethods.IpcGetTemplateList(null, false, true,
                                                                                       false, true, null, null, symmetricKeyCredential);

            //Requests tenant template to use for encryption
            Console.WriteLine("Please select the template you would like to use to encrypt the file.");

            //Outputs templates available for selection
            int counter = 0;

            for (int i = 0; i < templates.Count; i++)
            {
                counter++;
                Console.WriteLine(counter + ". " + templates.ElementAt(i).Name + "\n" +
                                  templates.ElementAt(i).Description);
            }

            //Parses template selection
            string input = Console.ReadLine();
            int    templateSelection;
            bool   parseResult = Int32.TryParse(input, out templateSelection);

            //Returns error if no template selection is entered
            if (parseResult)
            {
                //Ensures template value entered is valid
                if (0 < templateSelection && templateSelection <= counter)
                {
                    templateSelection -= templateSelection;

                    // Encrypts the file using the selected template
                    TemplateInfo selectedTemplateInfo = templates.ElementAt(templateSelection);

                    string encryptedFilePath = SafeFileApiNativeMethods.IpcfEncryptFile(filePath,
                                                                                        selectedTemplateInfo.TemplateId,
                                                                                        SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_KEY_NO_PERSIST, true, false, true, null,
                                                                                        symmetricKeyCredential);
                }
                else
                {
                    Console.WriteLine("Please enter a valid template number.");
                }
            }
            else
            {
                Console.WriteLine("Please enter a valid template number.");
            }
        }
        /// <summary>
        /// ProtectFilesInDirectory protects files in a directory location
        /// </summary>
        /// <param name="path"></param>
        public static void ProtectFilesInDirectory(string path)
        {
            //Loads MSIPC.dll
            SafeNativeMethods.IpcInitialize();
            SafeNativeMethods.IpcSetAPIMode(APIMode.Server);
            //Loads credentials for the service principal from App.Config
            SymmetricKeyCredential symmetricKeyCred = new SymmetricKeyCredential();

            symmetricKeyCred.AppPrincipalId = System.Configuration.ConfigurationManager.AppSettings["AppPrincipalId"];
            symmetricKeyCred.Base64Key      = ConfigurationManager.AppSettings["Base64Key"];
            symmetricKeyCred.BposTenantId   = ConfigurationManager.AppSettings["BposTenantId"];

            // if you are outside North America please uncomment this section as it is needed

            /* Uri IntranetURL = new Uri(ConfigurationManager.AppSettings["LicensingIntranetDistributionPointUrl"]);
             * Uri ExtranetURL = new Uri(ConfigurationManager.AppSettings["LicensingExtranetDistributionPointUrl"]);
             * ConnectionInfo connectionInfo = new ConnectionInfo(ExtranetURL, IntranetURL); */

            //Select Encryption Method
            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 choiceEncrypt = Console.ReadLine();

            //string method = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            string[] items = Directory.GetFiles(path);

            foreach (string item in items)
            {
                Console.WriteLine("Checking file: {0}", item);
                var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(item);
                if (checkEncryptionStatus.ToString().ToLower().Contains(alreadyEncrypted))
                {
                    Console.WriteLine("File {0} is already encrypted", item);
                    continue;
                }
                else
                {
                    if (choiceEncrypt == "1")
                    {
                        ProtectWithTemplate(symmetricKeyCred, item);
                    }
                    else if (choiceEncrypt == "2")
                    {
                        //Protect with AdHocPolicy
                        //ProtectWithAdHocPolicy(symmetricKeyCred, Path);
                    }
                }
            }
        }
        public static void ProtectWithTemplate(SymmetricKeyCredential symmetricKeyCredential, string filePath)
        {
            // Gets the available templates for this tenant outside north america please comment this section
            Collection <TemplateInfo> templates = SafeNativeMethods.IpcGetTemplateList(null, false, true,
                                                                                       false, true, null, null, symmetricKeyCredential);

            //Outside North America please uncomment this section to get templates

            /* Collection<TemplateInfo> templates = SafeNativeMethods.IpcGetTemplateList(connectionInfo, false, true,
             *  false, true, null, null, symmetricKeyCredential); */
            //Requests tenant template to use for encryption
            Console.WriteLine("Please select the template you would like to use to encrypt the file.");

            //Outputs templates available for selection
            int counter = 0;

            for (int i = 0; i < templates.Count; i++)
            {
                counter++;
                Console.WriteLine(counter + ". " + templates.ElementAt(i).Name + "\n" +
                                  templates.ElementAt(i).Description);
            }

            //Parses template selection
            string input = Console.ReadLine();
            int    templateSelection;
            bool   parseResult = Int32.TryParse(input, out templateSelection);

            //Returns error if no template selection is entered
            if (parseResult)
            {
                //Ensures template value entered is valid
                if (0 < templateSelection && templateSelection <= counter)
                {
                    templateSelection -= templateSelection;

                    // Encrypts the file using the selected template
                    TemplateInfo selectedTemplateInfo = templates.ElementAt(templateSelection);

                    string encryptedFilePath = SafeFileApiNativeMethods.IpcfEncryptFile(filePath,
                                                                                        selectedTemplateInfo.TemplateId,
                                                                                        SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_KEY_NO_PERSIST, true, false, true, null,
                                                                                        symmetricKeyCredential);
                }
                else
                {
                    Console.WriteLine("Please enter a valid template number.");
                }
            }
            else
            {
                Console.WriteLine("Please enter a valid template number.");
            }
        }
        // tries to parse all document properties, getting authorization if we can, but otherwise
        // gracefully falls back to just getting public properties

        private void collectDocumentProperties(string file)
        {
            byte[] fileLicense;
            SafeInformationProtectionKeyHandle keyHandle;

            fileLicense = SafeFileApiNativeMethods.IpcfGetSerializedLicenseFromFile(file);

            keyHandle = null;

            try
            {
                keyHandle = SafeNativeMethods.IpcGetKey(fileLicense, false, false, true, this);
            }
            catch
            {
            }

            propertyParser = new RmsPropertyParser(fileLicense, keyHandle);
        }
Пример #13
0
        public void EncryptFile(string filePath, string templateId)
        {
            string fileName;
            string pathToFile;

            SafeInformationProtectionKeyHandle     keyhandle;
            SafeInformationProtectionLicenseHandle licenseHandle;

            fileName   = Path.GetFileName(filePath);
            pathToFile = Path.GetDirectoryName(filePath);

            licenseHandle = SafeNativeMethods.IpcCreateLicenseFromTemplateId(templateId);

            byte[] license = SafeNativeMethods.IpcSerializeLicense(licenseHandle, 0, true, false, true, null, out keyhandle);

            Collection <UserRights> rights = SafeNativeMethods.IpcGetSerializedLicenseUserRightsList(license, keyhandle);

            SafeFileApiNativeMethods.IpcfEncryptFile(filePath, licenseHandle, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, false, true, true, null, pathToFile);
        }
Пример #14
0
        private void encryptBtn_Click(object sender, EventArgs e)
        {
            var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filepathBox.Text.Trim());

            if (checkEncryptionStatus.ToString().ToLower().Contains("encrypted"))
            {
                msg = "檔案已被加密 請先解密後再重新加密\n";
                log.AppendText(msg);
                //DialogResult isEncrypted = MessageBox.Show("Selected file is already encrypted \n Please Decrypt the file before encrypting");
                //if (isEncrypted == DialogResult.OK)
                //{
                //    // if you want to decrypt the file before exit then uncomment the following line
                //    //SafeFileApiNativeMethods.IpcfDecryptFile(filepathBox.Text.Trim(), IPCF_DF_FLAG_DEFAULT, false, false, false, IntPtr.Zero, null, null, null);
                //    Application.Exit();
                //}
            }
            else
            {
                try
                {
                    int templateNum = templateListBox.SelectedIndex;
                    //MessageBox.Show(templateNum.ToString());
                    TemplateInfo selectedTemplateInfo = templates.ElementAt(templateNum);
                    var          license           = SafeNativeMethods.IpcCreateLicenseFromTemplateId(selectedTemplateInfo.TemplateId);
                    string       encryptedFilePath = SafeFileApiNativeMethods.IpcfEncryptFile(filepathBox.Text.Trim(), license, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, false, false, true, IntPtr.Zero, null);
                    DialogResult result            = MessageBox.Show("檔案已加密到: " + encryptedFilePath);
                    if (result == DialogResult.OK)
                    {
                        //Application.Exit();
                    }
                }
                catch (Exception ex)
                {
                    DialogResult error = MessageBox.Show("Error: " + ex);
                    if (error == DialogResult.OK)
                    {
                        //Application.Exit();
                    }
                }
            }
        }
Пример #15
0
        private void selectFileBtn_Click(object sender, EventArgs e)
        {
            string content = "";

            using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
            {
                openFileDialog1.Multiselect      = false;
                openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                openFileDialog1.Filter           = "Office Files (*.docx,*.xlsx,*.pptx)|*.docx;*.xlsx;*.pptx|Text Files (*.txt)|*.txt|pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
                openFileDialog1.FilterIndex      = 1;
                openFileDialog1.RestoreDirectory = true;
                openFileDialog1.ShowDialog();
                try
                {
                    if (File.Exists(openFileDialog1.FileName))
                    {
                        filepathBox.Text     = openFileDialog1.FileName;
                        btn_fileinfo.Enabled = true;
                    }

                    var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filepathBox.Text.Trim());
                    if (checkEncryptionStatus.ToString().ToLower().Contains("encrypted"))
                    {
                        file_label.Text += "此檔案已加密";
                        ReadEncryptedContent(filepathBox.Text.Trim(), out content);
                        clear_log();
                        log.AppendText(content);
                    }
                    else
                    {
                        file_label.Text += "此檔案尚未加密,可點選加密進行加密";
                        clear_log();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: selected file has an error" + ex.Message);
                }
            }
        }
 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 void encryptBtn_Click(object sender, EventArgs e)
        {
            var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filepathBox.Text.Trim());

            if (checkEncryptionStatus.ToString().ToLower().Contains("encrypted"))
            {
                DialogResult isEncrypted = MessageBox.Show("Selected file is already encrypted");
                if (isEncrypted == DialogResult.OK)
                {
                    Application.Exit();
                }
            }
            else
            {
                try
                {
                    int templateNum = templateListBox.SelectedIndex;
                    //MessageBox.Show(templateNum.ToString());
                    TemplateInfo selectedTemplateInfo = templates.ElementAt(templateNum);
                    var          license           = SafeNativeMethods.IpcCreateLicenseFromTemplateId(selectedTemplateInfo.TemplateId);
                    string       encryptedFilePath = SafeFileApiNativeMethods.IpcfEncryptFile(filepathBox.Text.Trim(), license, SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_DEFAULT, false, false, true, IntPtr.Zero, null);
                    DialogResult result            = MessageBox.Show("File has been Encrypted and is at the following location: " + encryptedFilePath);
                    if (result == DialogResult.OK)
                    {
                        Application.Exit();
                    }
                }
                catch (Exception ex)
                {
                    DialogResult error = MessageBox.Show("Error: " + ex);
                    if (error == DialogResult.OK)
                    {
                        Application.Exit();
                    }
                }
            }
        }
        /// <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>
        /// Load pdf file by stream
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool LoadFileByStream(string fileName)
        {
            bool   isrmsProtect = true;
            Stream stream       = null;

            byte[] license         = null;
            string rmsUserPassword = string.Empty;


            if (rmsUserpEncrypt)
            {
                try
                {
                    //RMS化PDFファイルから、RMSライセンス情報と、暗号化された本文情報を分割する
                    //RMS署名情報から、RMSサーバー情報を抽出する
                    //RMSサーバーでの認証
                    //RMSサーバーからRMSライセンスの取得
                    license = SafeFileApiNativeMethods.IpcfGetSerializedLicenseFromFile(fileName);
                }
                catch (Exception ex)
                {
                    isrmsProtect = false;
                }
            }

            if (isrmsProtect && rmsUserpEncrypt)
            {
                try
                {
                    rmsUserPassword = GenerateRandom(32);

                    //RMSライセンスから、復号鍵の抽出
                    SafeInformationProtectionKeyHandle keyHandle = SafeNativeMethods.IpcGetKey(license, false, false, true, this);

                    //RMSライセンスから、権利リストの抽出
                    //Collection<UserRights> userRights = new Collection<UserRights>();
                    //userRights = SafeNativeMethods.IpcGetSerializedLicenseUserRightsList(license, keyHandle);

                    bool accessGranted = SafeNativeMethods.IpcAccessCheck(keyHandle, "VIEW");

                    //本文情報を復号鍵で、復号
                    tempFile = GenerateRandom(10);

                    //一時フォルダ作成 add kondo
                    System.IO.Directory.CreateDirectory(Path.GetTempPath() + @"PDFViewer\");

                    tempFile = Path.GetTempPath() + @"PDFViewer\" + tempFile;

                    Stream outPutRmsStream = new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                    stream = new FileStream(fileName, FileMode.Open);
                    if (accessGranted)
                    {
                        SafeFileApiNativeMethods.IpcfDecryptFileStream(stream, fileName,
                                                                       SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT, false,
                                                                       false, false, this, ref outPutRmsStream);
                    }

                    outPutRmsStream.Close();
                    outPutRmsStream.Dispose();

                    PdfReader reader = new PdfReader(tempFile);
                    outPutStream = new FileStream(tempFile + ".tmp", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
                    PdfEncryptor.Encrypt(reader, outPutStream, false, rmsUserPassword, "", 0);

                    rmsUserpEncrypt = false;
                    reader.Close();
                    reader.Dispose();
                    File.Delete(tempFile);
                }
                catch (InformationProtectionException ex)
                {
                    //DirectoryDelete MSIPC
                    DeleteDirectorySelect(true);

                    isrmsProtect = false;
                    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK);
                }
                catch (Exception ex)
                {
                    isrmsProtect = false;
                }
            }


            try
            {
                if (isrmsProtect)
                {
                    pdfDoc.LoadPDF(tempFile + ".tmp");
                }
                else
                {
                    pdfDoc.LoadPDF(fileName);
                }
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                return(true);
            }
            catch (System.Security.SecurityException sex)
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }

                if (pdfDoc != null)
                {
                    pdfDoc.Dispose();
                    pdfDoc = null;
                }
                pdfDoc = new PDFWrapper();

                if (!rmsUserpEncrypt)
                {
                    pdfDoc.UserPassword = rmsUserPassword;
                }
                else
                {
                    String password = Interaction.InputBox("Please enter the document password:"******"Document Password", "");
                    if (password.Equals(string.Empty))
                    {
                        return(false);
                    }
                    pdfDoc.UserPassword = password;
                }

                return(LoadFileByStream(fileName));
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                return(false);
            }
        }
Пример #20
0
        // 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);
            }
        }
Пример #21
0
 //Decrypt Procedure
 public void DecryptFile(string filePath)
 {
     SafeFileApiNativeMethods.IpcfDecryptFile(filePath, SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT, true, false, true, null);
 }
Пример #22
0
 public bool IsEncrypted(string filePath)
 {
     return(SafeFileApiNativeMethods.IpcfIsFileEncrypted(filePath));
 }
Пример #23
0
        public bool ReadEncryptedContent(string inputFile, out string encryptContent)
        {
            SafeInformationProtectionKeyHandle _keyHandle = null;
            // RMSServerURL _rmsURLs;
            TemplateInfo            _template;
            Collection <UserRights> _rights;
            Term _term;

            byte[] _license;
            int    i = 1;
            int    j = 1;
            int    days;
            string _info = "";


            _info += "=============== 擷取檔案【" + inputFile.Trim() + "】資訊 ===============\r\n";
            _info += "加密狀態:已加密\r\n";


            _license = SafeFileApiNativeMethods.IpcfGetSerializedLicenseFromFile(inputFile.Trim());                       // 自加密檔案取得憑證資訊

            _keyHandle = SafeNativeMethods.IpcGetKey(_license, false, false, true, this);                                 // // 從憑證中取得加密金鑰之處理指標(非金鑰內容),  只是它的 pointer。
            _info     += "憑證作者: " + SafeNativeMethods.IpcGetSerializedLicenseOwner(_license) + "\r\n";                    // 自加密憑證中 取得憑證擁有者資訊
            _info     += "加密內容 ID: " + SafeNativeMethods.IpcGetSerializedLicenseContentId(_license, _keyHandle) + "\r\n"; // 自加密憑證中取得憑證內容 ID
            _info     += "金鑰(Key)擁有者: " + SafeNativeMethods.IpcGetKeyUserDisplayName(_keyHandle) + "\r\n";                // 取得加密作者資訊
            _term      = SafeNativeMethods.IpcGetSerializedLicenseValidityTime(_license, _keyHandle);                     // 取得此範本的有效期
            if (_term.From.Year != 1601)
            {
                _info += "\t 有效期: 自 " + _term?.From.ToString() + " 開始,可使用" +
                         _term?.Duration.TotalDays.ToString() + " 天\r\n";
            }
            else
            {
                _info += "\t 有效期: 可永久使用。\r\n";
            }

            try
            {
                days = (int)SafeNativeMethods.IpcGetSerializedLicenseIntervalTime(_license, _keyHandle);
            }
            catch
            {
                days = -1;
            }
            _info += "\t 更新頻率:  " + ((days != -1) ? ("每 " + days.ToString() + "天更新") : ("【未設定】")) + "\r\n";

            try
            {
                _template = SafeNativeMethods.IpcGetSerializedLicenseDescriptor(_license, _keyHandle, null); // 得憑證的各項敘述內容
                _info    += "權限原則範本資訊(Template Info):\r\n";
                _info    += "\t 權限資訊來自範本: " + _template.FromTemplate + "\r\n";
                _info    += "\t 範本代號: " + _template.TemplateId + "\r\n";
                _info    += "\t 範本名稱: " + _template.Name + "\r\n";
                _info    += "\t 範本發行者(RMS Server): " + _template.IssuerDisplayName + "\r\n";
                _info    += "\t 範本說明:" + _template.Description + "\r\n";
            }
            catch
            {
                _info += "權限原則範本資訊(Template Info):無 (此檔案由使用者自定之權限原則所加密)\r\n";
            }
            _rights = SafeNativeMethods.IpcGetSerializedLicenseUserRightsList(_license, _keyHandle);     // 取得序列化憑證中的使用者權限內容
            _info  += "\t 權限列表:\r\n\t\t 授權人數:" + _rights.Count.ToString() + " 人\r\n";
            foreach (var u in _rights)
            {
                _info += "\t\t(" + j.ToString() + ") " + u.UserId + "\r\n";

                j++;
                _info += "\t\t 權限:";
                foreach (var r in u.Rights)
                {
                    _info += r + ", ";
                    i++;
                    if (i > 6)
                    {
                        _info += "\r\n\t\t";
                        i      = 1;
                    }
                }
                i      = 1;
                _info  = _info.Substring(0, (_info.Length - 1));
                _info += "\r\n";
            }
            _keyHandle.Dispose();
            _info         += "==================================================\r\n";
            encryptContent = _info;
            return(true);
        }
Пример #24
0
        // 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);
            }
        }
Пример #25
0
        /// <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.");
            }
        }
Пример #26
0
        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);
            }
        }