Exemplo n.º 1
0
        private void btnDecryptZip_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtNotificationZip.Text) || string.IsNullOrWhiteSpace(txtReceiverCert.Text))
            {
                // files validation
                MessageBox.Show("Either the ZIP file or certificate was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string zipFolder = "";

            try
            {
                //Deflate the zip archive
                zipFolder = ZipManager.ExtractArchive(txtNotificationZip.Text, txtNotificationFolder.Text);
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
                return;
            }

            //Decrypt the Payload
            string decryptedPayload = "";

            try
            {
                decryptedPayload = AesManager.DecryptNotification(zipFolder, txtReceiverCert.Text, txtRecKeyPassword.Text, radECB.Checked);
            }
            catch (Exception ex)
            {
                ex.DisplayException("Decryption Failed:" + Text);
                return;
            }

            // success
            MessageBox.Show("Decryption process is complete!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Exemplo n.º 2
0
        /// <summary>
        /// This will decrypt the payload from a downloaded and decompressed notification
        /// </summary>
        /// <param name="xmlProcessingFolder">The path to folder that contains the decompressed notification files</param>
        /// <param name="decryptionKey">The key file used to decrypt the AES key</param>
        /// <param name="decryptionPass">The password to the key file above</param>
        /// <param name="isECB">Determines the cipher mode, CBC or ECB</param>
        /// <returns>the file path to the decrypted payload file</returns>
        public static string DecryptNotification(string xmlProcessingFolder, string decryptionKey, string decryptionPass, bool isECB)
        {
            // select encrypted key file
            string encryptedKeyFile     = "";
            string encryptedPayloadFile = "";
            string metadataFile         = "";

            string[] keyFiles      = Directory.GetFiles(xmlProcessingFolder, "*_Key", SearchOption.TopDirectoryOnly);
            string[] payloadFiles  = Directory.GetFiles(xmlProcessingFolder, "*_Payload", SearchOption.TopDirectoryOnly);
            string[] metadataFiles = Directory.GetFiles(xmlProcessingFolder, "*_Metadata*", SearchOption.TopDirectoryOnly);

            if (keyFiles.Length == 0)
            {
                // key file validation
                throw new Exception("There was no file found containing the encrypted AES key!");
            }
            if (payloadFiles.Length == 0)
            {
                // key file validation
                throw new Exception("There was no file found containing the encrypted Payload!");
            }
            if (metadataFiles.Length == 0)
            {
                // key file validation
                throw new Exception("There was no file found containing the Metadata!");
            }

            encryptedKeyFile     = keyFiles[0];
            encryptedPayloadFile = payloadFiles[0];
            metadataFile         = metadataFiles[0];

            //Check the metadata and see what we have
            string metadataContentType = XmlManager.CheckMetadataType(metadataFile);

            byte[] encryptedAesKey  = null;
            byte[] decryptedAesKey  = null;
            byte[] aesVector        = null;
            string decryptedPayload = "";

            // load encrypted AES key
            encryptedAesKey = File.ReadAllBytes(encryptedKeyFile);

            // decrypt AES key & generate default (empty) initialization vector
            decryptedAesKey = AesManager.DecryptAesKey(encryptedAesKey, decryptionKey, decryptionPass);
            aesVector       = AesManager.GenerateRandomKey(16, true);
            if (isECB != true)
            {
                aesVector       = decryptedAesKey.Skip(32).Take(16).ToArray();
                decryptedAesKey = decryptedAesKey.Take(32).ToArray();
            }

            // decrypt encrypted ZIP file using decrypted AES key
            string decryptedFileName = encryptedPayloadFile.Replace("_Payload", "_Payload_decrypted.zip");

            AesManager.DecryptFile(encryptedPayloadFile, decryptedFileName, decryptedAesKey, aesVector, isECB);

            //Deflate the decrypted zip archive
            ZipManager.ExtractArchive(decryptedFileName, xmlProcessingFolder, true);
            decryptedPayload = decryptedFileName.Replace("_Payload_decrypted.zip", "_Payload.xml");

            //If the metadata is something other than XML, read the wrapper and rebuild the non-XML file
            if (metadataContentType != "XML")
            {
                //Some non-XML files may not have _Payload in the file name, if not remove it
                if (!File.Exists(decryptedPayload))
                {
                    decryptedPayload = decryptedPayload.Replace("_Payload.xml", ".xml");
                }

                //This will give us the base64 encoded data from the XML file
                string encodedData = XmlManager.ExtractXMLImageData(decryptedPayload);

                //We will convert the base64 data back to bytes
                byte[] binaryData;
                string decodedPayload = decryptedPayload.Replace(".xml", "." + metadataContentType);
                binaryData = System.Convert.FromBase64String(encodedData);

                //We can write the bytes back to rebuild the file
                FileStream decodedFile;
                decodedFile = new FileStream(decodedPayload, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                decodedFile.Write(binaryData, 0, binaryData.Length);
                decodedFile.Close();
            }

            return(decryptedPayload);
        }
        private void btnDecryptZip_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtNotificationZip.Text) || string.IsNullOrWhiteSpace(txtReceiverCert.Text))
            {
                // files validation
                MessageBox.Show("Either the ZIP file or certificate was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string zipFolder = "";

            try
            {
                //Deflate the zip archive
                zipFolder = ZipManager.ExtractArchive(txtNotificationZip.Text, txtNotificationFolder.Text);
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
                return;
            }
            // select encrypted key file
            string encryptedKeyFile     = "";
            string encryptedPayloadFile = "";

            string[] keyFiles     = Directory.GetFiles(zipFolder, "*_Key", SearchOption.TopDirectoryOnly);
            string[] payloadFiles = Directory.GetFiles(zipFolder, "*_Payload", SearchOption.TopDirectoryOnly);

            if (keyFiles.Length == 0)
            {
                // key file validation
                MessageBox.Show("There was no file found containing the encrypted AES key!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (payloadFiles.Length == 0)
            {
                // key file validation
                MessageBox.Show("There was no file found containing the encrypted Payload!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            encryptedKeyFile     = keyFiles[0];
            encryptedPayloadFile = payloadFiles[0];



            byte[] encryptedAesKey = null;
            byte[] decryptedAesKey = null;
            byte[] aesVector       = null;

            try
            {
                // load encrypted AES key
                encryptedAesKey = File.ReadAllBytes(encryptedKeyFile);

                // decrypt AES key & generate default (empty) initialization vector
                decryptedAesKey = AesManager.DecryptAesKey(encryptedAesKey, txtReceiverCert.Text, txtRecKeyPassword.Text);
                aesVector       = AesManager.GenerateRandomKey(16, true);
                if (radECB.Checked != true)
                {
                    aesVector       = decryptedAesKey.Skip(32).Take(16).ToArray();
                    decryptedAesKey = decryptedAesKey.Take(32).ToArray();
                }

                // decrypt encrypted ZIP file using decrypted AES key
                string decryptedFileName = encryptedPayloadFile.Replace("_Payload", "_Payload_decrypted.zip");
                AesManager.DecryptFile(encryptedPayloadFile, decryptedFileName, decryptedAesKey, aesVector, radECB.Checked);


                //Deflate the decrypted zip archive
                ZipManager.ExtractArchive(decryptedFileName, decryptedFileName, false);


                // success
                MessageBox.Show("Notification decryption process is complete!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
            }
            finally
            {
                if (encryptedAesKey != null)
                {
                    encryptedAesKey = null;
                }

                if (decryptedAesKey != null)
                {
                    decryptedAesKey = null;
                }

                if (aesVector != null)
                {
                    aesVector = null;
                }
            }
        }
Exemplo n.º 4
0
        private void btnCheckNotification_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtDecryptKey.Text))
            {
                // files validation
                MessageBox.Show("The Receiver's key for decryption must be set!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Char delimiter = ',';
            Dictionary <string, string> transmissions = new Dictionary <string, string>();

            try
            {   // Open the text file using a stream reader.
                using (StreamReader sr = new StreamReader("simplelog.csv"))
                {
                    while (sr.Peek() >= 0)
                    {
                        String   line         = sr.ReadLine();
                        string[] strLineArray = line.Split(delimiter);

                        //if there is no notification id, we will store the file name
                        if (strLineArray[4] == "NOTIFICATIONID")
                        {
                            transmissions.Add(strLineArray[2], line);
                        }
                        else
                        // otherwise, we store the notification id, and we can ignore this file if it is in the inbox
                        {
                            transmissions.Add(strLineArray[4], line);
                        }
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
                return;
            }

            //Connect to the Inbox and see if there are any files
            try
            {
                // Setup session options
                SessionOptions currentSFTPSession = SFTPManager.CreateSFTPSession(cmbSFTPServers.SelectedItem.ToString(), username.Text, password.Text);
                SFTPManager.DownloadInbox(currentSFTPSession, transmissions, txtDownFolder.Text);
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
                return;
            }

            //loop through the files we have downloaded and process them
            //these files will be matched to our log file to see if we have any matches

            string[] filesToProcess;
            string   xmlProcessedFolder          = "";
            string   xmlProcessingFolder         = "";
            string   xmlProcessedUnmatchedFolder = "";
            string   destinationFolder           = "";

            // Load all XML files in the folder into the array
            filesToProcess              = Directory.GetFiles(txtDownFolder.Text, "*.zip", SearchOption.TopDirectoryOnly);
            xmlProcessedFolder          = txtDownFolder.Text + "\\Processed";
            xmlProcessingFolder         = txtDownFolder.Text + "\\Processing";
            xmlProcessedUnmatchedFolder = txtDownFolder.Text + "\\Processed\\Unmatched";

            //if the processedFolder doesn't exist, create it
            if (!Directory.Exists(xmlProcessedFolder))
            {
                Directory.CreateDirectory(xmlProcessedFolder);
            }
            //if the processedUnmatchedFolder doesn't exist, create it
            if (!Directory.Exists(xmlProcessedUnmatchedFolder))
            {
                Directory.CreateDirectory(xmlProcessedUnmatchedFolder);
            }
            //if the processingFolder doesn't exist, create it
            if (!Directory.Exists(xmlProcessingFolder))
            {
                Directory.CreateDirectory(xmlProcessingFolder);
            }

            //loop through the downloaded files
            int matchCounter   = 0;
            int unmatchCounter = 0;

            foreach (string fileName in filesToProcess)
            {
                try
                {
                    //clean out the processing folder, the current file will be unzipped into it
                    DirectoryInfo dir = new DirectoryInfo(xmlProcessingFolder);
                    foreach (FileInfo fi in dir.GetFiles())
                    {
                        fi.Delete();
                    }
                    //Deflate the zip archive
                    ZipManager.ExtractArchive(fileName, xmlProcessingFolder, false);
                }
                catch (Exception ex)
                {
                    ex.DisplayException(Text);
                    return;
                }

                string decryptedPayload = "";
                try
                {
                    decryptedPayload = AesManager.DecryptNotification(xmlProcessingFolder, txtDecryptKey.Text, txtDecryptPassword.Text, radECB.Checked);
                }
                catch (Exception ex)
                {
                    ex.DisplayException("Decryption Failed:" + Text);
                    return;
                }

                //take a look at the decrypted payload and see if this notification matches anything we are looking for
                string[] notificationID       = new string[3];
                string   notificationFileName = Path.GetFileNameWithoutExtension(fileName);
                bool     isFileMatched        = false;

                //This will return three values
                //0 Ides Transmission ID
                //1 Sender FIle Id
                //2 Return Code
                notificationID = XmlManager.CheckNotification(decryptedPayload);

                //Check our log file dictionary and see if we can find a match
                if (transmissions.ContainsKey(notificationID[1]) == true)
                {
                    isFileMatched = true;

                    //we will add a new record to reflect the updated information and remove the old record
                    //make sure the filename is in our transmissions and return the current log data for it
                    string currentNotificationData = "";
                    transmissions.TryGetValue(notificationID[1], out currentNotificationData);

                    //update the current notification Data before we add the new record
                    //we will take fields from the decrypted notification and insert it back in
                    currentNotificationData = currentNotificationData.Replace("NOTIFICATIONID", Path.GetFileName(fileName));
                    currentNotificationData = currentNotificationData.Replace("IDESTRANSID", notificationID[0]);
                    currentNotificationData = currentNotificationData.Replace("NULL", notificationID[2]);
                    currentNotificationData = currentNotificationData.Replace("ERRORCOUNT", notificationID[3]);

                    //add new record with updated information
                    transmissions.Add(Path.GetFileName(fileName), string.Join(",", currentNotificationData));

                    //we can remove the old record now
                    transmissions.Remove(notificationID[1]);

                    //we will write the current transmissions back into the log file so we keep it updated with the latest information
                    //write to log
                    string filePath = @"simplelog.csv";
                    using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
                    {
                        using (TextWriter tw = new StreamWriter(fs))

                            foreach (KeyValuePair <string, string> kvp in transmissions)
                            {
                                tw.WriteLine(string.Format("{0}", kvp.Value));
                            }
                    }
                    //processing of the file is complete
                }
                //the decrypted files will be moved to the Processed folder for safekeeping
                //if no match is found, it moves to the Unmatched subfolder
                DirectoryInfo dirProcessing = new DirectoryInfo(xmlProcessingFolder);
                if (isFileMatched == true)
                {
                    destinationFolder = xmlProcessedFolder;
                    if (!Directory.Exists(xmlProcessedFolder + "\\" + notificationFileName))
                    {
                        Directory.CreateDirectory(xmlProcessedFolder + "\\" + notificationFileName);
                    }
                    matchCounter = matchCounter + 1;
                }
                else
                {
                    destinationFolder = xmlProcessedUnmatchedFolder;
                    //if this non-matching file has already been pulled, remove the old and replace with the new
                    if (Directory.Exists(xmlProcessedUnmatchedFolder + "\\" + notificationFileName))
                    {
                        //clean out the folder, it will get the current decrypted contents
                        DirectoryInfo dir = new DirectoryInfo(xmlProcessedUnmatchedFolder + "\\" + notificationFileName);
                        foreach (FileInfo fi in dir.GetFiles())
                        {
                            fi.Delete();
                        }
                    }
                    else
                    {
                        Directory.CreateDirectory(xmlProcessedUnmatchedFolder + "\\" + notificationFileName);
                    }
                    unmatchCounter = unmatchCounter + 1;
                }

                //move from the processing folder
                foreach (FileInfo fi in dirProcessing.GetFiles())
                {
                    File.Move(fi.FullName, Path.Combine(destinationFolder, notificationFileName, fi.Name));
                }
                //Rename the file so we can process it
                File.Move(fileName, Path.Combine(destinationFolder, notificationFileName, Path.GetFileName(fileName)));
            }
            MessageBox.Show(matchCounter + " matching files found\n" + unmatchCounter + " non-matching files found");
        }
Exemplo n.º 5
0
        private void btnDecryptZip_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtNotificationZip.Text) || string.IsNullOrWhiteSpace(txtReceiverCert.Text))
            {
                // files validation
                MessageBox.Show("Either the ZIP file or certificate was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string zipFolder = "";

            try
            {
                //Deflate the zip archive
                zipFolder = ZipManager.ExtractArchive(txtNotificationZip.Text, txtNotificationFolder.Text);
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
                return;
            }
            // select encrypted key file
            string encryptedKeyFile     = "";
            string encryptedPayloadFile = "";
            string metadataFile         = "";

            string[] keyFiles      = Directory.GetFiles(zipFolder, "*_Key", SearchOption.TopDirectoryOnly);
            string[] payloadFiles  = Directory.GetFiles(zipFolder, "*_Payload", SearchOption.TopDirectoryOnly);
            string[] metadataFiles = Directory.GetFiles(zipFolder, "*_Metadata*", SearchOption.TopDirectoryOnly);

            if (keyFiles.Length == 0)
            {
                // key file validation
                MessageBox.Show("There was no file found containing the encrypted AES key!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (payloadFiles.Length == 0)
            {
                // key file validation
                MessageBox.Show("There was no file found containing the encrypted Payload!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            encryptedKeyFile     = keyFiles[0];
            encryptedPayloadFile = payloadFiles[0];
            metadataFile         = metadataFiles[0];

            //Check the metadata and see what we have
            string metadataContentType = XmlManager.CheckMetadataType(metadataFile);


            byte[] encryptedAesKey = null;
            byte[] decryptedAesKey = null;
            byte[] aesVector       = null;

            try
            {
                // load encrypted AES key
                encryptedAesKey = File.ReadAllBytes(encryptedKeyFile);

                // decrypt AES key & generate default (empty) initialization vector
                decryptedAesKey = AesManager.DecryptAesKey(encryptedAesKey, txtReceiverCert.Text, txtRecKeyPassword.Text);
                aesVector       = AesManager.GenerateRandomKey(16, true);
                if (radECB.Checked != true)
                {
                    aesVector       = decryptedAesKey.Skip(32).Take(16).ToArray();
                    decryptedAesKey = decryptedAesKey.Take(32).ToArray();
                }

                // decrypt encrypted ZIP file using decrypted AES key
                string decryptedFileName = encryptedPayloadFile.Replace("_Payload", "_Payload_decrypted.zip");
                AesManager.DecryptFile(encryptedPayloadFile, decryptedFileName, decryptedAesKey, aesVector, radECB.Checked);


                //Deflate the decrypted zip archive
                ZipManager.ExtractArchive(decryptedFileName, decryptedFileName, false);
                string decryptedPayload = decryptedFileName.Replace("_Payload_decrypted.zip", "_Payload.xml");
                //If the metadata is something other than XML, read the wrapper and rebuild the non-XML file

                if (metadataContentType != "XML")
                {
                    //Some non-XML files may not have _Payload in the file name, if not remove it
                    if (!File.Exists(decryptedPayload))
                    {
                        decryptedPayload = decryptedPayload.Replace("_Payload.xml", ".xml");
                    }

                    //This will give us the base64 encoded data from the XML file

                    string encodedData = XmlManager.ExtractXMLImageData(decryptedPayload);

                    //We will convert the base64 data back to bytes
                    byte[] binaryData;
                    string decodedPayload = decryptedPayload.Replace(".xml", "." + metadataContentType);
                    binaryData = System.Convert.FromBase64String(encodedData);

                    //We can write the bytes back to rebuild the file
                    FileStream decodedFile;
                    decodedFile = new FileStream(decodedPayload, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                    decodedFile.Write(binaryData, 0, binaryData.Length);
                    decodedFile.Close();
                }

                // success
                MessageBox.Show("Notification decryption process is complete!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
            }
            finally
            {
                if (encryptedAesKey != null)
                {
                    encryptedAesKey = null;
                }

                if (decryptedAesKey != null)
                {
                    decryptedAesKey = null;
                }

                if (aesVector != null)
                {
                    aesVector = null;
                }
            }
        }