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();
     }
 }
        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
        // 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);
            }
        }
示例#5
0
文件: RMSAPI.cs 项目: LiDamon/ADRMS
 //Decrypt Procedure
 public void DecryptFile(string filePath)
 {
     SafeFileApiNativeMethods.IpcfDecryptFile(filePath, SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT, true, false, true, null);
 }
示例#6
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);
            }
        }
        /// <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);
            }
        }