コード例 #1
0
    static void Main(string[] args)
    {
        string plainText = "plain text";
        string password  = "******";
        string encrypted = AesManager.EncryptToBase64(plainText, password);

        Console.WriteLine(AesManager.DecryptFromBase64(encrypted, password));
        Console.ReadLine();
    }
コード例 #2
0
ファイル: AesManagerTest.cs プロジェクト: vector-man/nUpdate
        public void CanEncryptAndDecrypt()
        {
            const string password = "******";

            byte[] encrypted = AesManager.Encrypt(password, "testKey", "testIV");
            var    decrypted = AesManager.Decrypt(encrypted, "testKey", "testIV");

            Assert.IsTrue(decrypted.ConvertToUnsecureString() == password);
        }
コード例 #3
0
        public byte[] Decrypt(int appId, byte[] bytes)
        {
            var appInfo = _appInfoDataAccess.GetModelWithCache(appId);

            if (appInfo == null)
            {
                throw new InvalidOperationException("Decryption failed");
            }

            return(AesManager.Decrypt(bytes, appInfo.AppKey, appInfo.AppSecret));
        }
コード例 #4
0
        public UpdateProject OpenProject(string projectPath)
        {
            UpdateProject project;

            try
            {
                project = UpdateProject.LoadProject(projectPath);
            }
            catch (Exception ex)
            {
                Popup.ShowPopup(this, SystemIcons.Error, "Error while reading the project.", ex,
                                PopupButtons.Ok);
                return(null);
            }

            if (!project.SaveCredentials)
            {
                var credentialsDialog = new CredentialsDialog();
                if (credentialsDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        _ftpPassword =
                            AesManager.Decrypt(Convert.FromBase64String(project.FtpPassword),
                                               credentialsDialog.Password.Trim(), credentialsDialog.Username.Trim());

                        if (project.Proxy != null)
                        {
                            _proxyPassword =
                                AesManager.Decrypt(Convert.FromBase64String(project.ProxyPassword),
                                                   credentialsDialog.Password.Trim(), credentialsDialog.Username.Trim());
                        }

                        if (project.UseStatistics)
                        {
                            _sqlPassword =
                                AesManager.Decrypt(Convert.FromBase64String(project.SqlPassword),
                                                   credentialsDialog.Password.Trim(), credentialsDialog.Username.Trim());
                        }
                    }
                    catch (CryptographicException)
                    {
                        Popup.ShowPopup(this, SystemIcons.Error, "Invalid credentials.",
                                        "The entered credentials are invalid.", PopupButtons.Ok);
                        return(null);
                    }
                }
コード例 #5
0
        public ActionResult Decrypt(NotificationsViewModel notification)
        {
            if (ModelState.IsValid)
            {
                // Paths for each file that we are going to store on disk
                string mainDirectory         = Server.MapPath("~/App_Data/Decrypt/");
                string certificatesDirectory = Server.MapPath("~/App_Data/Certificates/");
                string subDir                    = DateTime.UtcNow.ToString("yyyyMMddTHHmmssfff") + "\\";
                string decryptedDirectory        = Path.Combine(mainDirectory, subDir);
                string encryptedNotificationPath = Path.Combine(decryptedDirectory, notification.EncryptedNotification.FileName);
                string senderCertificatePath     = Path.Combine(certificatesDirectory, "sender.pfx");

                //Create subdirectory
                Directory.CreateDirectory(decryptedDirectory);

                // Save the files to disk
                notification.EncryptedNotification.SaveAs(encryptedNotificationPath);

                // Read certificate
                byte[] senderCertificate;
                using (Stream inputStream = notification.SenderCertificate.InputStream)
                {
                    MemoryStream memoryStream = inputStream as MemoryStream;
                    if (memoryStream == null)
                    {
                        memoryStream = new MemoryStream();
                        inputStream.CopyTo(memoryStream);
                    }
                    senderCertificate = memoryStream.ToArray();
                }

                string zipFolder = "";
                try
                {
                    //Deflate the zip archive
                    zipFolder = ZipManager.ExtractArchive(encryptedNotificationPath, decryptedDirectory);
                }
                catch (Exception e)
                {
                    ViewBag.Message = e.Message;
                    return(View("~/Views/Shared/Info.cshtml"));
                }

                //Decrypt the Payload
                string decryptedNotificationPath = "";
                try
                {
                    decryptedNotificationPath = AesManager.DecryptNotification(zipFolder, senderCertificate, notification.SenderCertPassword, false);
                }
                catch (Exception e)
                {
                    ViewBag.Message = e.Message;
                    return(View("~/Views/Shared/Info.cshtml"));
                }

                ViewBag.DecryptedNotificationPath = decryptedNotificationPath;
                ViewBag.DecryptedNotificationXML  = System.IO.File.ReadAllText(decryptedNotificationPath);
                return(View("~/Views/Notifications/Download.cshtml"));
            }
            else
            {
                return(View(notification));
            }
        }
コード例 #6
0
        private void continueButton_Click(object sender, EventArgs e)
        {
            if (_sender == generalTabPage)
            {
                if (!ValidationManager.Validate(generalPanel))
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.",
                                    "All fields need to have a value.", PopupButtons.Ok);
                    return;
                }

                if (!_generalTabPassed)
                {
                    _projectConfiguration =
                        ProjectConfiguration.Load().ToList();
                    if (_projectConfiguration != null)
                    {
                        if (_projectConfiguration.Any(item => item.Name == nameTextBox.Text))
                        {
                            Popup.ShowPopup(this, SystemIcons.Error, "The project is already existing.",
                                            String.Format(
                                                "The project \"{0}\" is already existing.",
                                                nameTextBox.Text), PopupButtons.Ok);
                            return;
                        }
                    }
                    else
                    {
                        _projectConfiguration = new List <ProjectConfiguration>();
                    }
                }

                if (!Uri.IsWellFormedUriString(updateUrlTextBox.Text, UriKind.Absolute))
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Invalid adress.", "The given Update-URL is invalid.",
                                    PopupButtons.Ok);
                    return;
                }

                if (!Path.IsPathRooted(localPathTextBox.Text))
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.",
                                    "The given local path for the project is invalid.", PopupButtons.Ok);
                    return;
                }

                try
                {
                    Path.GetFullPath(localPathTextBox.Text);
                }
                catch
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Invalid path.",
                                    "The given local path for the project is invalid.", PopupButtons.Ok);
                    return;
                }

                _sender            = ftpTabPage;
                backButton.Enabled = true;
                informationCategoriesTabControl.SelectedTab = ftpTabPage;
            }
            else if (_sender == ftpTabPage)
            {
                if (!ValidationManager.Validate(ftpPanel) || String.IsNullOrEmpty(ftpPasswordTextBox.Text))
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.",
                                    "All fields need to have a value.", PopupButtons.Ok);
                    return;
                }

                _ftp.Host      = ftpHostTextBox.Text;
                _ftp.Port      = int.Parse(ftpPortTextBox.Text);
                _ftp.Username  = ftpUserTextBox.Text;
                _ftp.Directory = ftpDirectoryTextBox.Text;

                var ftpPassword = new SecureString();
                foreach (var c in ftpPasswordTextBox.Text)
                {
                    ftpPassword.AppendChar(c);
                }
                _ftp.Password = ftpPassword; // Same instance that FtpManager will automatically dispose

                _ftp.UsePassiveMode = ftpModeComboBox.SelectedIndex == 0;
                _ftp.Protocol       = (FtpSecurityProtocol)ftpProtocolComboBox.SelectedIndex;

                if (!backButton.Enabled) // If the back-button was disabled, enabled it again
                {
                    backButton.Enabled = true;
                }

                _sender = statisticsServerTabPage;
                informationCategoriesTabControl.SelectedTab = statisticsServerTabPage;
            }
            else if (_sender == statisticsServerTabPage)
            {
                if (useStatisticsServerRadioButton.Checked)
                {
                    if (SqlDatabaseName == null || String.IsNullOrWhiteSpace(sqlPasswordTextBox.Text))
                    {
                        Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.",
                                        "All fields need to have a value.", PopupButtons.Ok);
                        return;
                    }
                }

                _sender = proxyTabPage;
                informationCategoriesTabControl.SelectedTab = proxyTabPage;
            }
            else if (_sender == proxyTabPage)
            {
                if (useProxyRadioButton.Checked)
                {
                    if (!ValidationManager.ValidateTabPage(proxyTabPage) && !String.IsNullOrEmpty(proxyUserTextBox.Text) &&
                        !String.IsNullOrEmpty(proxyPasswordTextBox.Text))
                    {
                        Popup.ShowPopup(this, SystemIcons.Error, "Missing information found.",
                                        "All fields need to have a value.", PopupButtons.Ok);
                        return;
                    }
                }

                try
                {
                    using (File.Create(localPathTextBox.Text))
                    {
                    }
                    _projectFileCreated = true;
                }
                catch (IOException ex)
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Failed to create project file.", ex, PopupButtons.Ok);
                    Close();
                }

                var usePassive = ftpModeComboBox.SelectedIndex == 0;

                WebProxy proxy         = null;
                string   proxyUsername = null;
                string   proxyPassword = null;
                if (!String.IsNullOrEmpty(proxyHostTextBox.Text))
                {
                    proxy = new WebProxy(proxyHostTextBox.Text);
                    if (!String.IsNullOrEmpty(proxyUserTextBox.Text) &&
                        !String.IsNullOrEmpty(proxyPasswordTextBox.Text))
                    {
                        proxyUsername = proxyUserTextBox.Text;
                        if (!saveCredentialsCheckBox.Checked)
                        {
                            proxyPassword = Convert.ToBase64String(AesManager.Encrypt(proxyPasswordTextBox.Text,
                                                                                      ftpPasswordTextBox.Text,
                                                                                      ftpUserTextBox.Text));
                        }
                        else
                        {
                            proxyPassword =
                                Convert.ToBase64String(AesManager.Encrypt(proxyPasswordTextBox.Text,
                                                                          Program.AesKeyPassword,
                                                                          Program.AesIvPassword));
                        }
                    }
                }

                string sqlPassword = null;
                if (useStatisticsServerRadioButton.Checked)
                {
                    if (!saveCredentialsCheckBox.Checked)
                    {
                        sqlPassword = Convert.ToBase64String(AesManager.Encrypt(sqlPasswordTextBox.Text,
                                                                                ftpPasswordTextBox.Text,
                                                                                ftpUserTextBox.Text));
                    }
                    else
                    {
                        sqlPassword =
                            Convert.ToBase64String(AesManager.Encrypt(sqlPasswordTextBox.Text, Program.AesKeyPassword,
                                                                      Program.AesIvPassword));
                    }
                }

                Settings.Default.ApplicationID += 1;
                Settings.Default.Save();
                Settings.Default.Reload();

                string ftpPassword;
                if (!saveCredentialsCheckBox.Checked)
                {
                    ftpPassword = Convert.ToBase64String(AesManager.Encrypt(ftpPasswordTextBox.Text,
                                                                            ftpPasswordTextBox.Text,
                                                                            ftpUserTextBox.Text));
                }
                else
                {
                    ftpPassword =
                        Convert.ToBase64String(AesManager.Encrypt(ftpPasswordTextBox.Text, Program.AesKeyPassword,
                                                                  Program.AesIvPassword));
                }

                // Create a new package...
                var project = new UpdateProject
                {
                    Path                        = localPathTextBox.Text,
                    Name                        = nameTextBox.Text,
                    Guid                        = Guid.NewGuid().ToString(),
                    ApplicationId               = Settings.Default.ApplicationID,
                    UpdateUrl                   = updateUrlTextBox.Text,
                    Packages                    = null,
                    SaveCredentials             = saveCredentialsCheckBox.Checked,
                    FtpHost                     = ftpHostTextBox.Text,
                    FtpPort                     = int.Parse(ftpPortTextBox.Text),
                    FtpUsername                 = ftpUserTextBox.Text,
                    FtpPassword                 = ftpPassword,
                    FtpDirectory                = ftpDirectoryTextBox.Text,
                    FtpProtocol                 = ftpProtocolComboBox.SelectedIndex,
                    FtpUsePassiveMode           = usePassive,
                    FtpTransferAssemblyFilePath = _ftpAssemblyPath,
                    Proxy                       = proxy,
                    ProxyUsername               = proxyUsername,
                    ProxyPassword               = proxyPassword,
                    UseStatistics               = useStatisticsServerRadioButton.Checked,
                    SqlDatabaseName             = SqlDatabaseName,
                    SqlWebUrl                   = SqlWebUrl,
                    SqlUsername                 = SqlUsername,
                    SqlPassword                 = sqlPassword,
                    PrivateKey                  = PrivateKey,
                    PublicKey                   = PublicKey,
                    Log = null
                };

                try
                {
                    UpdateProject.SaveProject(localPathTextBox.Text, project); // ... and save it
                }
                catch (IOException ex)
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Error while saving the project file.", ex, PopupButtons.Ok);
                    _mustClose = true;
                    Reset();
                }

                try
                {
                    var projectDirectoryPath = Path.Combine(Program.Path, "Projects", nameTextBox.Text);
                    Directory.CreateDirectory(projectDirectoryPath);
                }
                catch (Exception ex)
                {
                    Popup.ShowPopup(this, SystemIcons.Error, "Error while creating the project'S directory.", ex,
                                    PopupButtons.Ok);
                    _mustClose = true;
                    Reset();
                }

                try
                {
                    _projectConfiguration.Add(new ProjectConfiguration(nameTextBox.Text, localPathTextBox.Text));
                    File.WriteAllText(Program.ProjectsConfigFilePath, Serializer.Serialize(_projectConfiguration));
                    _projectConfigurationEdited = true;
                }
                catch (Exception ex)
                {
                    Popup.ShowPopup(this, SystemIcons.Error,
                                    "Error while editing the project confiuration file. Please choose another name for the project.",
                                    ex,
                                    PopupButtons.Ok);
                    _mustClose = true;
                    Reset();
                }

                if (useStatisticsServerRadioButton.Checked)
                {
                    var phpFilePath = Path.Combine(Program.Path, "Projects", nameTextBox.Text, "statistics.php");
                    try
                    {
                        File.WriteAllBytes(phpFilePath, Resources.statistics);

                        var phpFileContent = File.ReadAllText(phpFilePath);
                        phpFileContent = phpFileContent.Replace("_DBURL", SqlWebUrl);
                        phpFileContent = phpFileContent.Replace("_DBUSER", SqlUsername);
                        phpFileContent = phpFileContent.Replace("_DBNAME", SqlDatabaseName);
                        phpFileContent = phpFileContent.Replace("_DBPASS", sqlPasswordTextBox.Text);
                        File.WriteAllText(phpFilePath, phpFileContent);
                        _phpFileCreated = true;
                    }
                    catch (Exception ex)
                    {
                        Popup.ShowPopup(this, SystemIcons.Error, "Failed to initialize the project-files.", ex,
                                        PopupButtons.Ok);
                        _mustClose = true;
                        Reset();
                    }
                }

                _generalTabPassed = true;
                InitializeProject();
            }
        }
コード例 #7
0
 public byte[] Decrypt(string key, string iv, byte[] bytes)
 {
     return(AesManager.Decrypt(bytes, key, iv, Encoding.UTF8));
 }
コード例 #8
0
 public string Decrypt(string key, string iv, string value)
 {
     return(AesManager.Decrypt(value, key, iv, Encoding.UTF8));
 }
コード例 #9
0
        public ActionResult Index(EncryptViewModel encryption)
        {
            if (ModelState.IsValid)
            {
                // Paths for each file that we are going to store on disk
                string mainDirectory         = Server.MapPath("~/App_Data/Encrypt/");
                string certificatesDirectory = Server.MapPath("~/App_Data/Certificates/");
                string subDir             = DateTime.UtcNow.ToString("yyyyMMddTHHmmssfff") + "\\";
                string encryptedDirectory = Path.Combine(mainDirectory, subDir);

                string xmlReportPath           = Path.Combine(encryptedDirectory, encryption.Report.FileName);
                string senderCertificatePath   = Path.Combine(certificatesDirectory, "sender.pfx");
                string receiverCertificatePath = Path.Combine(certificatesDirectory, "receiver.cer");
                string hctaCertificatePath     = ""; // Optional

                // Create subdirectory
                Directory.CreateDirectory(encryptedDirectory);

                // Save xml report to the disk
                encryption.Report.SaveAs(xmlReportPath);

                // Read certificates
                byte[] senderCertificate;
                using (Stream inputStream = encryption.SenderCertificate.InputStream)
                {
                    MemoryStream memoryStream = inputStream as MemoryStream;
                    if (memoryStream == null)
                    {
                        memoryStream = new MemoryStream();
                        inputStream.CopyTo(memoryStream);
                    }
                    senderCertificate = memoryStream.ToArray();
                }

                byte[] irsCertificate;
                using (Stream inputStream = encryption.IRSCertificate.InputStream)
                {
                    MemoryStream memoryStream = inputStream as MemoryStream;
                    if (memoryStream == null)
                    {
                        memoryStream = new MemoryStream();
                        inputStream.CopyTo(memoryStream);
                    }
                    irsCertificate = memoryStream.ToArray();
                }

                byte[] hctaCertificate = { };
                if (encryption.Model1Option2)
                {
                    using (Stream inputStream = encryption.HCTACertificate.InputStream)
                    {
                        MemoryStream memoryStream = inputStream as MemoryStream;
                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();
                            inputStream.CopyTo(memoryStream);
                        }
                        hctaCertificate = memoryStream.ToArray();
                    }
                }

                // Perform the schema validation
                //string validationError = XmlManager.CheckSchema(xmlReportPath, "Schemas folder");

                //if (validationError != "")
                //{
                //   return Json(new { StatusCode = HttpStatusCode.InternalServerError, errorMessage = "Schema validation error: " + validationError });
                //}

                // Load XML report content
                byte[] xmlContent    = System.IO.File.ReadAllBytes(xmlReportPath);
                string senderGIIN    = Path.GetFileNameWithoutExtension(encryption.Report.FileName);
                string fileExtension = Path.GetExtension(encryption.Report.FileName.ToUpper()).Replace(".", "");

                // Perform signature
                byte[] signedReport     = XmlManager.Sign(XmlSignatureType.Enveloping, xmlContent, senderCertificate, encryption.SenderCertPassword, xmlReportPath);
                string signedReportPath = xmlReportPath.Replace(".xml", "_Payload.xml");

                string zipPackagePath = signedReportPath.Replace(".xml", ".zip");

                // Save signed xml report to the disk
                System.IO.File.WriteAllBytes(signedReportPath, signedReport);

                // Create the zip archive that will hold the generated files, and add the signed report to it
                ZipManager.CreateArchive(signedReportPath, zipPackagePath);

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

                // Encrypt file and save to disk
                string encryptedFilePath     = zipPackagePath.Replace(".zip", "");
                string encryptedHCTAFilePath = zipPackagePath.Replace(".zip", "");
                string payloadFilePath       = encryptedFilePath + "";
                AesManager.EncryptFile(zipPackagePath, encryptedFilePath, aesEncryptionKey, aesEncryptionVector, false);

                // Encrypt AES key with the public key of the certificate and save to disk
                encryptedFilePath = Path.GetDirectoryName(zipPackagePath) + "\\000000.00000.TA.840_Key";
                AesManager.EncryptAesKey(aesEncryptionKey, aesEncryptionVector, irsCertificate, "yourpasswordhere", encryptedFilePath, false);

                //For Model1 Option2 Only, encrypt the AES Key with the HCTA Public Key
                if (encryption.Model1Option2)
                {
                    encryptedHCTAFilePath = Path.GetDirectoryName(zipPackagePath) + "\\000000.00000.TA." + "901" + "_Key";
                    AesManager.EncryptAesKey(aesEncryptionKey, aesEncryptionVector, hctaCertificate, "", encryptedHCTAFilePath, false);
                }

                // cleanup
                signedReport     = null;
                aesEncryptionKey = aesEncryptionVector = null;

                string packageName = "";
                try
                {
                    DateTime uDat = new DateTime();
                    uDat        = DateTime.UtcNow;
                    packageName = uDat.ToString("yyyyMMddTHHmmssfffZ") + "_" + senderGIIN;
                    string metadataFilePath = Path.Combine(encryptedDirectory, senderGIIN + "_Metadata.xml");
                    XmlManager.CreateMetadataFile(metadataFilePath, fileExtension, true, "2018", senderGIIN, packageName);

                    // Check the signature to make sure it is valid, this requires the KeyInfo to be present
                    bool result = XmlManager.CheckSignature(signedReportPath);
                    if (result == false)
                    {
                        return(Json(new { statusCode = HttpStatusCode.InternalServerError, errorMessage = "The document signature is not valid!" }));
                    }

                    //Add the metadata, payload, and key files to the final zip package
                    // Add signed file to the zip package
                    ZipManager.CreateArchive(metadataFilePath, encryptedDirectory + "\\" + packageName + ".zip");
                    ZipManager.UpdateArchive(encryptedFilePath, encryptedDirectory + "\\" + packageName + ".zip");
                    ZipManager.UpdateArchive(payloadFilePath, encryptedDirectory + "\\" + packageName + ".zip");

                    //Add the HCTA Key file for a Model 1 Option 2 packet
                    if (encryption.Model1Option2)
                    {
                        ZipManager.UpdateArchive(encryptedHCTAFilePath, encryptedDirectory + "\\" + packageName + ".zip");
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }

                encryption.PackagePath = encryptedDirectory + "\\" + packageName + ".zip";

                return(RedirectToAction("Download", new { packagePath = encryptedDirectory + "\\" + packageName + ".zip" }));
            }
            else
            {
                return(View(encryption));
            }
        }