Пример #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");
            }
        }
        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");
            }
        }
Пример #3
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("此檔案已無加密");
            }
        }
Пример #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 ");
            }
        }
        /// <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);
                    }
                }
            }
        }
Пример #6
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();
                    }
                }
            }
        }
Пример #7
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);
                }
            }
        }
        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();
                    }
                }
            }
        }
Пример #9
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);
            }
        }
Пример #10
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);
            }
        }
Пример #11
0
 public bool IsEncrypted(string filePath)
 {
     return(SafeFileApiNativeMethods.IpcfIsFileEncrypted(filePath));
 }
Пример #12
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);
            }
        }