private void btnSignXML_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtXmlFile.Text))
            {
                // files validation
                MessageBox.Show("The XML file was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtCert.Text))
            {
                // files validation
                MessageBox.Show("The Signing Certificate was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtCertPass.Text))
            {
                // certificate password validation
                MessageBox.Show("Signing Certificate password was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtKeyCert.Text))
            {
                // files validation
                MessageBox.Show("Encryption Certificate was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // load XML file content
                byte[] xmlContent = File.ReadAllBytes(txtXmlFile.Text);
                string senderGIIN = Path.GetFileNameWithoutExtension(txtXmlFile.Text);
                string filePath   = Path.GetDirectoryName(txtXmlFile.Text);

                // perform sign
                byte[] envelopingSignature = XmlManager.Sign(XmlSignatureType.Enveloping, xmlContent, txtCert.Text, txtCertPass.Text);

                string envelopingFileName = txtXmlFile.Text.Replace(".xml", "_Payload.xml");
                string zipFileName        = envelopingFileName.Replace(".xml", ".zip");

                // save enveloping version to disk
                File.WriteAllBytes(envelopingFileName, envelopingSignature);

                // add enveloping signature to ZIP file
                ZipManager.CreateArchive(envelopingFileName, zipFileName);

                // generate AES key (32 bytes) & default initialization vector (empty)
                byte[] aesEncryptionKey    = AesManager.GenerateRandomKey(AesManager.KeySize / 8);
                byte[] aesEncryptionVector = AesManager.GenerateRandomKey(16, radECB.Checked);

                // encrypt file & save to disk
                string encryptedFileName     = zipFileName.Replace(".zip", "");
                string encryptedHCTAFileName = zipFileName.Replace(".zip", "");
                string payloadFileName       = encryptedFileName;
                AesManager.EncryptFile(zipFileName, encryptedFileName, aesEncryptionKey, aesEncryptionVector, radECB.Checked);


                // encrypt key with public key of certificate & save to disk
                encryptedFileName = Path.GetDirectoryName(zipFileName) + "\\000000.00000.TA.840_Key";
                AesManager.EncryptAesKey(aesEncryptionKey, aesEncryptionVector, txtKeyCert.Text, txtKeyCertPassword.Text, encryptedFileName, radECB.Checked);
                //For Model1 Option2 Only, encrypt the AES Key with the HCTA Public Key
                if (chkM1O2.Checked)
                {
                    encryptedHCTAFileName = Path.GetDirectoryName(zipFileName) + "\\000000.00000.TA." + txtHCTACode.Text + "_Key";
                    AesManager.EncryptAesKey(aesEncryptionKey, aesEncryptionVector, txtHCTACert.Text, txtHCTACertPassword.Text, encryptedHCTAFileName, radECB.Checked);
                }

                // cleanup
                envelopingSignature = null;
                aesEncryptionKey    = aesEncryptionVector = null;

                //Start creating XML metadata
                XmlWriter writer = null;
                string    fileCreationDateTime = "";
                fileCreationDateTime = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ");

                DateTime uDat = new DateTime();
                uDat = DateTime.UtcNow;
                string senderFile = uDat.ToString("yyyyMMddTHHmmssfffZ") + "_" + senderGIIN;

                try
                {
                    // Create an XmlWriterSettings object with the correct options.
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent             = true;
                    settings.IndentChars        = ("\t");
                    settings.OmitXmlDeclaration = false;
                    settings.NewLineHandling    = NewLineHandling.Replace;
                    settings.CloseOutput        = true;

                    string metadataFileName = filePath + "\\" + senderGIIN + "_Metadata.xml";

                    // Create the XmlWriter object and write some content.
                    writer = XmlWriter.Create(metadataFileName, settings);
                    writer.WriteStartElement("FATCAIDESSenderFileMetadata", "urn:fatca:idessenderfilemetadata");
                    writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                    writer.WriteStartElement("FATCAEntitySenderId");
                    writer.WriteString(senderGIIN);
                    writer.WriteEndElement();
                    writer.WriteStartElement("FATCAEntityReceiverId");
                    writer.WriteString("000000.00000.TA.840");
                    writer.WriteEndElement();
                    writer.WriteStartElement("FATCAEntCommunicationTypeCd");
                    writer.WriteString("RPT");
                    writer.WriteEndElement();
                    writer.WriteStartElement("SenderFileId");
                    writer.WriteString(senderFile);
                    writer.WriteEndElement();
                    writer.WriteStartElement("FileFormatCd");
                    writer.WriteString("XML");
                    writer.WriteEndElement();
                    writer.WriteStartElement("BinaryEncodingSchemeCd");
                    writer.WriteString("NONE");
                    writer.WriteEndElement();
                    writer.WriteStartElement("FileCreateTs");
                    writer.WriteString(fileCreationDateTime);
                    writer.WriteEndElement();
                    writer.WriteStartElement("TaxYear");
                    writer.WriteString(cmbTaxYear.SelectedItem.ToString());
                    writer.WriteEndElement();
                    writer.WriteStartElement("FileRevisionInd");
                    writer.WriteString("false");
                    writer.WriteEndElement();
                    //Close the XmlTextWriter.
                    writer.WriteEndDocument();
                    writer.Close();
                    writer.Flush();


                    //Add the metadata, payload, and key files to the final zip package
                    // add enveloping signature to ZIP file
                    ZipManager.CreateArchive(metadataFileName, filePath + "\\" + senderFile + ".zip");
                    ZipManager.UpdateArchive(encryptedFileName, filePath + "\\" + senderFile + ".zip");
                    ZipManager.UpdateArchive(payloadFileName, filePath + "\\" + senderFile + ".zip");
                    //Add the HCTA Key file for a M1O2 packet
                    if (chkM1O2.Checked)
                    {
                        ZipManager.UpdateArchive(encryptedHCTAFileName, filePath + "\\" + senderFile + ".zip");
                    }

                    // success
                    MessageBox.Show("XML Signing and Encryption process is complete!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
            }
        }
Esempio n. 2
0
        private void btnSignXML_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtXmlFile.Text))
            {
                // files validation
                MessageBox.Show("The XML file was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtCert.Text))
            {
                // files validation
                MessageBox.Show("The Signing Certificate was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtCertPass.Text))
            {
                // certificate password validation
                MessageBox.Show("Signing Certificate password was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(txtKeyCert.Text))
            {
                // files validation
                MessageBox.Show("Encryption Certificate was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (chkSchemaValidation.Checked == true && string.IsNullOrWhiteSpace(txtSchemaFolder.Text))
            {
                // files validation
                MessageBox.Show("Schema Validation selected but Schema Folder was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //this will be used as a holder for processed files if a folder is being sent
            string processedFolder = "";

            try
            {
                //if we are sending a folder, we will load up the files into an array to process
                //otherwise, we will just load our file in the array
                string[] filesToProcess;
                if (chkSendFolder.Checked == false)
                {
                    filesToProcess    = new string[1];
                    filesToProcess[0] = txtXmlFile.Text;
                }
                else
                {
                    // Load all XML files in the folder into an array
                    filesToProcess  = Directory.GetFiles(txtXmlFile.Text, "*.xml", SearchOption.TopDirectoryOnly);
                    processedFolder = txtXmlFile.Text + "\\Processed";

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

                //This will loop through all files in the array
                //This will be one file or it could be a set of files in a folder
                string currentFileToProcess = "";
                foreach (string fileName in filesToProcess)
                {
                    currentFileToProcess = fileName;
                    //if the file we are processing has an underscore we will split it off for logging
                    //this should only happen for bulk sending from a folder
                    if (currentFileToProcess.Contains("_"))
                    {
                        string[] filePart = fileName.Split('_');
                        currentFileToProcess = txtXmlFile.Text + "\\" + filePart[1];
                        //Rename the file so we can process it
                        File.Move(fileName, currentFileToProcess);
                    }

                    // perform the schema validation if we have the checkbox checked for it
                    if (chkSchemaValidation.Checked)
                    {
                        string validationError = XmlManager.CheckSchema(currentFileToProcess, txtSchemaFolder.Text);
                        if (validationError != "")
                        {
                            // Show schema validation error(s)
                            MessageBox.Show("Schema Validation Error:\r\n" + validationError, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }

                    // load XML file content
                    byte[] xmlContent    = File.ReadAllBytes(currentFileToProcess);
                    string senderGIIN    = Path.GetFileNameWithoutExtension(currentFileToProcess);
                    string filePath      = Path.GetDirectoryName(currentFileToProcess);
                    string fileExtension = Path.GetExtension(currentFileToProcess.ToUpper()).Replace(".", "");
                    bool   isXML         = true;

                    if (fileExtension != "XML")
                    {
                        isXML = false;
                    }

                    // perform signature
                    byte[] envelopingSignature;
                    string envelopingFileName = "";

                    //if the file is XML we will use the enveloping digital signature for the XML
                    if (isXML == true)
                    {
                        envelopingSignature = XmlManager.Sign(XmlSignatureType.Enveloping, xmlContent, txtCert.Text, txtCertPass.Text, filePath);
                        envelopingFileName  = currentFileToProcess.Replace(".xml", "_Payload.xml");
                    }
                    //if the file is NOT XML, we will convert the file data to base64 and put in XML and sign it
                    else
                    {
                        envelopingSignature = XmlManager.Sign(XmlSignatureType.NonXML, xmlContent, txtCert.Text, txtCertPass.Text, filePath);
                        envelopingFileName  = currentFileToProcess.ToUpper().Replace(".PDF", "_Payload.xml");
                    }

                    string zipFileName = envelopingFileName.Replace(".xml", ".zip");

                    // save enveloping version to disk
                    File.WriteAllBytes(envelopingFileName, envelopingSignature);

                    // add enveloping signature to ZIP file
                    ZipManager.CreateArchive(envelopingFileName, zipFileName);

                    // generate AES key (32 bytes) & default initialization vector (empty)
                    byte[] aesEncryptionKey    = AesManager.GenerateRandomKey(AesManager.KeySize / 8);
                    byte[] aesEncryptionVector = AesManager.GenerateRandomKey(16, radECB.Checked);

                    // encrypt file & save to disk
                    string encryptedFileName     = zipFileName.Replace(".zip", "");
                    string encryptedHCTAFileName = zipFileName.Replace(".zip", "");
                    string payloadFileName       = encryptedFileName + "";
                    AesManager.EncryptFile(zipFileName, encryptedFileName, aesEncryptionKey, aesEncryptionVector, radECB.Checked);

                    // encrypt key with public key of certificate & save to disk
                    encryptedFileName = Path.GetDirectoryName(zipFileName) + "\\000000.00000.TA.840_Key";;
                    AesManager.EncryptAesKey(aesEncryptionKey, aesEncryptionVector, txtKeyCert.Text, txtKeyCertPassword.Text, encryptedFileName, radECB.Checked);
                    //For Model1 Option2 Only, encrypt the AES Key with the HCTA Public Key
                    if (chkM1O2.Checked)
                    {
                        encryptedHCTAFileName = Path.GetDirectoryName(zipFileName) + "\\000000.00000.TA." + txtHCTACode.Text + "_Key";
                        AesManager.EncryptAesKey(aesEncryptionKey, aesEncryptionVector, txtHCTACert.Text, txtHCTACertPassword.Text, encryptedHCTAFileName, radECB.Checked);
                    }

                    // cleanup
                    envelopingSignature = null;
                    aesEncryptionKey    = aesEncryptionVector = null;



                    try
                    {
                        DateTime uDat = new DateTime();
                        uDat = DateTime.UtcNow;
                        string senderFile       = uDat.ToString("yyyyMMddTHHmmssfffZ") + "_" + senderGIIN;
                        string metadataFileName = filePath + "\\" + senderGIIN + "_Metadata.xml";
                        XmlManager.CreateMetadataFile(metadataFileName, fileExtension, isXML, cmbTaxYear.SelectedItem.ToString(), senderGIIN, senderFile);

                        //Check the signature to make sure it is valid, this requires the KeyInfo to be present
                        //This is controlled using the checkbox on the form
                        //This should be commented out or not selected if not using the KeyInfo in the XmlManager class
                        if (chkSignatureValidation.Checked)
                        {
                            bool result = XmlManager.CheckSignature(envelopingFileName);
                            if (result == false)
                            {
                                MessageBox.Show("Signature is not valid!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }
                        }

                        //Add the metadata, payload, and key files to the final zip package
                        // add enveloping signature to ZIP file
                        ZipManager.CreateArchive(metadataFileName, filePath + "\\" + senderFile + ".zip");
                        ZipManager.UpdateArchive(encryptedFileName, filePath + "\\" + senderFile + ".zip");
                        ZipManager.UpdateArchive(payloadFileName, filePath + "\\" + senderFile + ".zip");
                        //Add the HCTA Key file for a M1O2 packet
                        if (chkM1O2.Checked)
                        {
                            ZipManager.UpdateArchive(encryptedHCTAFileName, filePath + "\\" + senderFile + ".zip");
                        }



                        if (chkAutoSendSFTP.Checked == true)
                        {
                            SessionOptions currentSFTPSession = SFTPManager.CreateSFTPSession(cmbSFTPServers.SelectedItem.ToString(), username.Text, password.Text);
                            string         sftpUpName         = filePath + "\\" + senderFile + ".zip";
                            string         transferResult     = SFTPManager.UploadFile(currentSFTPSession, sftpUpName);
                            //This can be commented out if there is no desire to see an upload confirmation
                            MessageBox.Show(transferResult, Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                            //write to log
                            string path = @"simplelog.csv";
                            // This text is added only once to the file.
                            string lineToLog = fileName + "," + currentFileToProcess + "," + senderFile + ",IDESTRANSID,NOTIFICATIONID,NULL,ERRORCOUNT";
                            if (!File.Exists(path))
                            {
                                // Create a file to write to.
                                using (StreamWriter sw = File.CreateText(path))
                                {
                                    sw.WriteLine(lineToLog);
                                }
                            }
                            else
                            {
                                // This text is always added, making the file longer over time
                                // if it is not deleted.
                                using (StreamWriter sw = File.AppendText(path))
                                {
                                    sw.WriteLine(lineToLog);
                                }
                            }
                        }
                        if (chkSendFolder.Checked == true)
                        {
                            //Move the file to a processed folder so we can move on to the next
                            //This is only used when sending an entire folder
                            File.Move(currentFileToProcess, processedFolder + "\\" + Path.GetFileName(fileName));
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.DisplayException(Text);
                        return;
                    }
                    finally
                    {
                    }
                }
                // success
                MessageBox.Show("XML Signing and Encryption process is complete!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
            }
        }