示例#1
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");
            }
        }
示例#2
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();
            }
        }
示例#3
0
文件: RMSAPI.cs 项目: LiDamon/ADRMS
        //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);
        }
示例#4
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.");
            }
        }
        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.");
            }
        }
示例#6
0
文件: RMSAPI.cs 项目: LiDamon/ADRMS
        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);
        }
示例#7
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();
                    }
                }
            }
        }
 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();
                    }
                }
            }
        }
示例#10
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.");
            }
        }