Exemplo n.º 1
0
        public static void Decrypt(string encryptedMessage, string secretKeyPath, string publicKeyPath, bool gui = false, string privatePassWord = "")
        {
            string plainTextExtracted;

            if (privatePassWord == "")
            {
                if (!gui)
                {
                    Console.Write("Please enter the passphrase of the chosen private key: ");
                    privatePassWord = Console.ReadLine();
                }
                else
                {
                    privatePassWord = Prompt.ShowDialog("Enter the password of the chosen secret key", "Password entry", false, false, false);
                }
            }


            // create an instance of the library
            PGPLib pgp = new PGPLib();

            // decrypt and verify
            try
            {
                SignatureCheckResult signatureCheck =
                    pgp.DecryptAndVerifyString(encryptedMessage,
                                               new FileInfo(secretKeyPath), //secret key path
                                               privatePassWord,             //this is the password of the secret key
                                               new FileInfo(publicKeyPath),
                                               out string plainTextExtract);
                plainTextExtracted = plainTextExtract;

                // print the results
                if (signatureCheck == SignatureCheckResult.SignatureVerified)
                {
                    Console.WriteLine("Signature OK");
                    if (gui)
                    {
                        MessageBox.Show("Signature OK");
                    }
                }
                else if (signatureCheck == SignatureCheckResult.SignatureBroken)
                {
                    Console.WriteLine("Signature of the message is either broken or forged");
                    if (gui)
                    {
                        MessageBox.Show("Signature of the message is either broken or forged");
                    }
                }
                else if (signatureCheck == SignatureCheckResult.PublicKeyNotMatching)
                {
                    Console.WriteLine("The provided public key doesn't match the signature");
                    if (gui)
                    {
                        MessageBox.Show("The provided public key doesn't match the signature");
                    }
                }
                else if (signatureCheck == SignatureCheckResult.NoSignatureFound)
                {
                    Console.WriteLine("This message is not digitally signed");
                    if (gui)
                    {
                        MessageBox.Show("This message is not digitally signed");
                    }
                }


                if (!gui)
                {
                    Console.WriteLine("Extracted message: \n" + plainTextExtracted);
                }
                else
                {
                    SimpleReportViewer.ShowDialog(plainTextExtracted, "Decrypted data", Program.genericGUIForm);
                }
            }
            catch (Exception e)
            {
                if (e is DidiSoft.Pgp.Exceptions.WrongPrivateKeyException)
                {
                    Console.WriteLine("The chosen private key is either not a private key or not suited to decrypt this message.");
                    if (gui)
                    {
                        MessageBox.Show("The chosen private key is either not a private key or not suited to decrypt this message.");
                    }
                    //The supplied private key source is not a private key at all
                }
                else if (e is DidiSoft.Pgp.Exceptions.WrongPasswordException)
                {
                    Console.WriteLine("The entered passphrase is incorrect, please try again.");
                    if (!gui)
                    {
                        Decrypt(encryptedMessage, secretKeyPath, publicKeyPath);
                    }
                    else
                    {
                        MessageBox.Show("The entered passphrase is incorrect, please try again.");
                    }
                }
                else if (e is DidiSoft.Pgp.Exceptions.WrongPublicKeyException)
                {
                    if (!gui)
                    {
                        Console.WriteLine("The chosen public key is either not a public key or not suited to verify this message.");
                    }
                    else
                    {
                        MessageBox.Show("The chosen public key is either not a public key or not suited to verify this message.");
                    }
                }
                else if (e is DidiSoft.Pgp.Exceptions.KeyIsExpiredException)
                {
                    Console.WriteLine("The public key you want to encrypt for is expired and cannot be used.");
                    if (gui)
                    {
                        MessageBox.Show("The public key you want to encrypt for is expired and cannot be used.");
                    }
                    //Can be worked around by setting UseExpiredKeys to true
                }
                else if (e is DidiSoft.Pgp.Exceptions.KeyIsRevokedException)
                {
                    Console.WriteLine("The public key you want to encrypt for appears to be revoked and cannot be used.");
                    if (gui)
                    {
                        MessageBox.Show("The public key you want to encrypt for appears to be revoked and cannot be used.");
                    }
                    //Can be worked around by setting UseRevokedKeys to true
                }
                else if (e is DidiSoft.Pgp.Exceptions.NonPGPDataException)
                {
                    Console.WriteLine("The data you want to decrypt is not encrypted with PGP.");
                    if (gui)
                    {
                        MessageBox.Show("The data you want to decrypt is not encrypted with PGP.");
                    }
                    //Can be worked around by setting UseRevokedKeys to true
                }
                else if (e is IOException)
                {
                    Console.WriteLine("IO Exception has occured, decrypting of unencrypted data is not possible.");
                    if (gui)
                    {
                        MessageBox.Show("IO Exception has occured, decrypting of unencrypted data is not possible.");
                    }
                    //Can be worked around by setting UseRevokedKeys to true
                }
                else
                {
                    throw new ApplicationException("Something unexpected went wrong, contact support and explain your actions in detail and chronological order.");
                }
            }
        }
Exemplo n.º 2
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Console.WriteLine("Default Public Keys directory exists:" + Directory.Exists(pathKeyPublic));
            Console.WriteLine("Default Private Keys directory exists:" + Directory.Exists(pathKeyPrivate));
            Console.WriteLine("Config.ini exists:" + File.Exists("Config.ini"));

            ConfigFile configData = new ConfigFile();

            configData.WriteAllValuesConsole();

            // The first if checks if the directory entered in the config file exists, the second checks the default location. The else if is there because of the directory location during development.
            if (!Directory.Exists(pathKeyPublic))
            {
                if (Directory.Exists(@"Keys\\Public"))
                {
                    pathKeyPublic = @"Keys\\Public";
                }
                else if (Directory.Exists(@"..\\..\\Keys\\Public"))
                {
                    pathKeyPublic = @"..\\..\\Keys\\Public";
                }
                else
                {
                    pathKeyPublic = @"Keys\\Public";
                }
                Directory.CreateDirectory(pathKeyPublic);
            }
            if (!Directory.Exists(pathKeyPublic + "\\Gemeente") || !Directory.Exists(pathKeyPublic + "\\Politie") || !Directory.Exists(pathKeyPublic + "\\OM") || !Directory.Exists(pathKeyPublic + "\\Reclassering"))
            {
                Directory.CreateDirectory(pathKeyPublic + "\\Gemeente");
                Directory.CreateDirectory(pathKeyPublic + "\\Politie");
                Directory.CreateDirectory(pathKeyPublic + "\\OM");
                Directory.CreateDirectory(pathKeyPublic + "\\Reclassering");
            }

            // The first if checks if the directory entered in the config file exists, the second checks the default location. The else if is there because of the directory location during development.
            if (!Directory.Exists(pathKeyPrivate))
            {
                if (Directory.Exists(@"Keys\\Private"))
                {
                    pathKeyPrivate = @"Keys\\Private";
                }
                else if (Directory.Exists(@"..\\..\\Keys\\Private"))
                {
                    pathKeyPrivate = @"..\\..\\Keys\\Private";
                }
                else
                {
                    pathKeyPrivate = @"Keys\\Private";
                }
                Directory.CreateDirectory(pathKeyPrivate);
            }

            ParseKeyID keyIDPaths = new ParseKeyID(pathKeyPrivate, pathKeyPublic);

            keyIDPaths.WriteLoadedKeyPaths();

            BootConfigurator bootConfigurator = new BootConfigurator();

            if (!existingRoles.Contains(currentRole) || !bootConfigurator.ValidatePortNumberEntry(NetworkPort.ToString()) || NodeName == "" || NodeName == "Unknown")
            {
                Application.Run(bootConfigurator);
            }



            while (NetworkPort == 0)
            {
                Console.Write("Enter network port: ");
                if (int.TryParse(Console.ReadLine(), out int port)) //checks if the given input is a string. If not the user is told to enter a number. No more crashes because you accidently pressed enter.
                {
                    port = Math.Abs(port);                          //can't enter a negative number as a port now
                    if (!portBlacklist.Contains(port))              //checks if the entered port is on the blacklist
                    {
                        NetworkPort = port;
                        break;
                    }
                    Console.Write("Pick a port number that does not match any of the following: ");
                    Console.WriteLine(string.Join <int>(", ", portBlacklist)); //lists all blacklisted ports to the user so he can avoid them.
                    Console.Write("Enter network port: ");
                }
                else
                {
                    Console.WriteLine("A port has to be a number. Try again.");
                }
            }

            if (NodeName == "Unknown" || NodeName == "")
            {
                Console.Write("Enter Node name: ");
                NodeName = Console.ReadLine();
            }

            //Eerst ProjectD.ReadChain() --> Als geen resultaat, dan SetupChain()
            ProjectD.ReadChain();
            if (ProjectD.ChainList == null)
            {
                ProjectD.SetupChain();
            }

            if (NetworkPort > 0)
            {
                ServerInstance = new Server();
                ServerInstance.Initialize();
            }
            if (NodeName != "Unkown")
            {
                Console.WriteLine($"Your node name is: {NodeName}");
            }

            flushMsgAndSend = new FlushBlock(currentRole, ClientInstance); //Place this after the chain, clientinstance and nodename have been initialized.



            genericGUIForm = new FormGenericGUI(keyIDPaths, configData, ClientInstance, ServerInstance);

            Console.WriteLine(currentRole);
            Application.Run(genericGUIForm);

            Console.WriteLine("--------------------------------------");
            Console.WriteLine("1. Setup a connection with a server");
            Console.WriteLine("2. Add unencrypted data to chain");
            Console.WriteLine("3. Display records");
            Console.WriteLine("4. Exit the program");
            Console.WriteLine("5. List all keys in the keys directory");
            Console.WriteLine("7. Decrypt a stored message");
            Console.WriteLine("8. Encrypt a message, multiple recipients supported, encryption key ID's are listed under 5");
            Console.WriteLine("9. Toggle loading from config");
            Console.WriteLine("10. List active connections");
            Console.WriteLine("--------------------------------------");

            int instruction = 0;

            while (instruction != 4)
            {
                switch (instruction)
                {
                case 1:
                    Console.WriteLine("Enter the URL and port of the server:");
                    string serverURL = Console.ReadLine();
                    ClientInstance.Handshake($"{serverURL}/Chain");
                    break;

                case 2:
                    Console.Write("Enter the name(s) of the intended recipient(s): ");
                    string receiverName = Console.ReadLine();
                    string data         = Prompt.ShowDialog("Enter the data", "Data entry");

                    flushMsgAndSend.Flush(receiverName, data);
                    break;

                case 3:
                    Console.WriteLine("Chain");
                    Console.WriteLine(JsonConvert.SerializeObject(ProjectD, Formatting.Indented));
                    break;

                case 5:
                    keyIDPaths.WriteLoadedKeyPaths();
                    break;

                case 7:
                    if (ProjectD.ChainList.Count > 1)     //1 and not 0 because the genesis block counts as one.
                    {
                        int blockNumber = 0;
                        while (blockNumber <= 0)
                        {
                            Console.Write("Enter the number of the block you want to decrypt: ");
                            if (int.TryParse(Console.ReadLine(), out int inputBlockNumber))     //checks if the given input is a string. If not the user is told to enter a number. No more crashes because you accidently pressed enter.
                            {
                                if (inputBlockNumber >= ProjectD.ChainList.Count)
                                {
                                    Console.WriteLine("The number you enter must correspond to an existing block. Try again.");
                                }
                                else
                                {
                                    blockNumber = Math.Abs(inputBlockNumber);
                                }
                            }
                            else
                            {
                                Console.WriteLine("The number of the block has to be a number. Try again.");
                            }
                        }
                        Console.WriteLine("Encrypted data:");

                        string encryptedDataFromChain = ProjectD.ChainList[blockNumber].MessageList[0].Data;
                        Console.WriteLine(encryptedDataFromChain);

                        keyIDPaths.WriteLoadedKeyPaths(false, true);
                        Console.Write("Enter the ID of the private key you want to use to decrypt: ");
                        string privateKeyPathDecrypt = keyIDPaths.ParseAndReturnVerifiedKeyPath();     //the user looks up the private and public key ÏD's with the option 5 menu and then chooses the encryption keys with the ID"s linked to the keys.
                        keyIDPaths.WriteLoadedKeyPaths(true, false);
                        Console.Write("Enter the ID of the public key of the sender: ");
                        string publicKeyPathDecrypt = keyIDPaths.ParseAndReturnVerifiedKeyPath(true);

                        DecryptAndVerifyString.Decrypt(encryptedDataFromChain, privateKeyPathDecrypt, publicKeyPathDecrypt);
                    }
                    else
                    {
                        Console.WriteLine("There are no blocks to decrypt!");
                    }
                    break;

                case 8:

                    Console.WriteLine("Enter the names of the designated recipients");
                    string receiverNamesForImprovedMultiEnc = Console.ReadLine();

                    keyIDPaths.WriteLoadedKeyPaths(false, true);
                    Console.WriteLine("Enter the ID of the private key you want to sign with");
                    string privKeyPath = keyIDPaths.ParseAndReturnVerifiedKeyPath();

                    keyIDPaths.WriteLoadedKeyPaths(true, false);
                    Console.WriteLine("Enter the public key ID's for every recipient");
                    string[] recipientKeyPathsArr = keyIDPaths.BuildVerifiedKeyIdPathArray();

                    string inputData = Prompt.ShowDialog("Enter the data you want to encrypt", "Data entry");

                    string encData = EncryptFileMultipleRecipients.MultiRecipientStringEncrypter(inputData, privKeyPath, recipientKeyPathsArr);
                    Console.WriteLine(encData);

                    flushMsgAndSend.Flush(receiverNamesForImprovedMultiEnc, encData);
                    break;

                case 9:

                    configData.ToggleAutoLoadConfigValues();
                    break;

                case (10):

                    ClientInstance.PingAll();
                    break;
                }
                ProjectD.SaveChainStateToDisk(ProjectD);
                Console.Write("Enter the number of the action you want to execute: ");
                string action = Console.ReadLine();
                if (validActions.Contains(action))
                {
                    instruction = int.Parse(action);
                }
                else
                {
                    Console.WriteLine("Please pick a valid action!");
                    instruction = 0;
                }
            }
            ProjectD.SaveChainStateToDisk(ProjectD);

            ClientInstance.Exit();
        }