Exemplo n.º 1
0
        public void SignAssembly_NewLocationWithPdb_Should_Succeed()
        {
            var tempDir = Path.Combine(TestAssemblyDirectory, Guid.NewGuid().ToString("N"));

            Directory.CreateDirectory(tempDir);
            var outDir = Path.Combine(tempDir, "out");

            Directory.CreateDirectory(outDir);
            try
            {
                string sourceAssemblyPath = Path.Combine(tempDir, "Brutal.Dev.StrongNameSigner.TestAssembly.A.dll");
                File.Copy(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.A.dll"), sourceAssemblyPath);
                File.Copy(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.A.pdb"), Path.Combine(tempDir, "Brutal.Dev.StrongNameSigner.TestAssembly.A.pdb"));

                SigningHelper.SignAssembly(sourceAssemblyPath, null, outDir);
                string outAssembly = Path.Combine(outDir, Path.GetFileName(sourceAssemblyPath));
                Assert.IsTrue(File.Exists(outAssembly));
                Assert.IsTrue(File.Exists(Path.ChangeExtension(outAssembly, ".pdb")));
                var info = SigningHelper.GetAssemblyInfo(outAssembly);
                Assert.IsTrue(info.IsSigned);
            }
            finally
            {
                Directory.Delete(tempDir, true);
            }
        }
Exemplo n.º 2
0
        private void ListViewAssembliesDragDrop(object sender, DragEventArgs e)
        {
            var data = e.Data.GetData(DataFormats.FileDrop) as IEnumerable <string>;

            if (data != null)
            {
                var assemblies = data.Where(d => (Path.GetExtension(d).Equals(".exe", StringComparison.OrdinalIgnoreCase) ||
                                                  Path.GetExtension(d).Equals(".dll", StringComparison.OrdinalIgnoreCase)) &&
                                            File.Exists(d)).ToList();

                // Add all files in directories.
                var directories = data.Where(d => Directory.Exists(d) && File.GetAttributes(d).HasFlag(FileAttributes.Directory)).ToList();
                directories.ForEach(d => assemblies.AddRange(Directory.GetFiles(d, "*.exe", SearchOption.AllDirectories)));
                directories.ForEach(d => assemblies.AddRange(Directory.GetFiles(d, "*.dll", SearchOption.AllDirectories)));

                foreach (var assembly in assemblies)
                {
                    try
                    {
                        AddAssemblyToList(SigningHelper.GetAssemblyInfo(assembly));
                    }
                    catch (BadImageFormatException)
                    {
                        MessageBox.Show(string.Format(CultureInfo.CurrentCulture, "Could not get assembly info for '{0}'. This may not be a .NET assembly.", assembly), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }

                ResizeColumnWidths();

                buttonSign.Enabled = listViewAssemblies.Items.Count > 0;
            }
        }
Exemplo n.º 3
0
        private static bool TrySignPackagePart(PackagePart packagePart, string keyPath, string keyPassword, bool signedPackage)
        {
            if (packagePart.Uri.ToString().EndsWith(".exe") ||
                packagePart.Uri.ToString().EndsWith(".dll"))
            {
                string tempPath = Path.GetTempFileName();
                try
                {
                    using (var stream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        packagePart.GetStream().CopyTo(stream);
                    }

                    if (!SigningHelper.GetAssemblyInfo(tempPath).IsSigned)
                    {
                        signedPackage = true;

                        SigningHelper.SignAssembly(tempPath, keyPath ?? string.Empty, Path.GetDirectoryName(tempPath), keyPassword ?? string.Empty);

                        using (var stream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Read))
                        {
                            stream.CopyTo(packagePart.GetStream(FileMode.Create, FileAccess.Write));
                        }
                    }
                }
                finally
                {
                    File.Delete(tempPath);
                }
            }
            return(signedPackage);
        }
Exemplo n.º 4
0
        private static bool FixSingleAssemblyReference(string assemblyPath, string referencePath, string keyFile, string keyFilePassword, params string[] probingPaths)
        {
            try
            {
                PrintMessage(null, LogLevel.Verbose);
                PrintMessage(string.Format("Fixing references to '{1}' in '{0}'...", assemblyPath, referencePath), LogLevel.Verbose);

                if (SigningHelper.FixAssemblyReference(assemblyPath, referencePath, keyFile, keyFilePassword, probingPaths))
                {
                    PrintMessageColor(string.Format("References to '{1}' in '{0}' were fixed successfully.", assemblyPath, referencePath), LogLevel.Changes, ConsoleColor.Green);

                    return(true);
                }
                else
                {
                    PrintMessage("No assembly references to fix...", LogLevel.Verbose);
                }
            }
            catch (BadImageFormatException bife)
            {
                PrintMessageColor(string.Format("Warning: {0}", bife.Message), LogLevel.Silent, ConsoleColor.Yellow);
            }
            catch (Exception ex)
            {
                PrintMessageColor(string.Format("Error: {0}", ex.Message), LogLevel.Silent, ConsoleColor.Red);
            }

            return(false);
        }
Exemplo n.º 5
0
        public void GetAssemblyInfo_Detects_Correct_Version_40_Assembly()
        {
            var info = SigningHelper.GetAssemblyInfo(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET40.exe"));

            info.IsManagedAssembly.ShouldBe(true);
            info.DotNetVersion.ShouldBe("4.0.30319");
        }
Exemplo n.º 6
0
        private static AssemblyInfo SignSingleAssembly(string assemblyPath, string keyPath, string outputDirectory, string password, params string[] probingPaths)
        {
            try
            {
                PrintMessage(null, LogLevel.Verbose);
                PrintMessage(string.Format("Strong-name signing '{0}'...", assemblyPath), LogLevel.Verbose);

                var oldInfo = SigningHelper.GetAssemblyInfo(assemblyPath);
                var newInfo = SigningHelper.SignAssembly(assemblyPath, keyPath, outputDirectory, password, probingPaths);

                if (!oldInfo.IsSigned && newInfo.IsSigned)
                {
                    PrintMessageColor(string.Format("'{0}' was strong-name signed successfully.", newInfo.FilePath), LogLevel.Changes, ConsoleColor.Green);

                    return(newInfo);
                }
                else
                {
                    PrintMessage("Already strong-name signed...", LogLevel.Verbose);
                }
            }
            catch (BadImageFormatException bife)
            {
                PrintMessageColor(string.Format("Warning: {0}", bife.Message), LogLevel.Silent, ConsoleColor.Yellow);
            }
            catch (Exception ex)
            {
                PrintMessageColor(string.Format("Error: {0}", ex.Message), LogLevel.Silent, ConsoleColor.Red);
            }

            return(null);
        }
Exemplo n.º 7
0
        public void GetAssemblyInfo_Detects_Signed_40_Assembly()
        {
            var info = SigningHelper.GetAssemblyInfo(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET40-Signed.exe"));

            info.IsSigned.ShouldBe(true);
            info.IsAnyCpu.ShouldBe(true);
        }
Exemplo n.º 8
0
        private static bool RemoveInvalidFriendAssemblyReferences(string assemblyPath, string keyFile, string keyFilePassword, params string[] probingPaths)
        {
            try
            {
                PrintMessage(null, LogLevel.Verbose);
                PrintMessage(string.Format("Removing invalid friend references from '{0}'...", assemblyPath), LogLevel.Verbose);

                if (SigningHelper.RemoveInvalidFriendAssemblies(assemblyPath, keyFile, keyFilePassword, probingPaths))
                {
                    PrintMessageColor(string.Format("Invalid friend assemblies removed successfully from '{0}'.", assemblyPath), LogLevel.Changes, ConsoleColor.Green);

                    return(true);
                }
                else
                {
                    PrintMessage("No friend references to fix...", LogLevel.Verbose);
                }
            }
            catch (BadImageFormatException bife)
            {
                PrintMessageColor(string.Format("Warning: {0}", bife.Message), LogLevel.Silent, ConsoleColor.Yellow);
            }
            catch (Exception ex)
            {
                PrintMessageColor(string.Format("Error: {0}", ex.Message), LogLevel.Silent, ConsoleColor.Red);
            }

            return(false);
        }
 public void FixAssemblyReference_Should_Fix_InternalsVisbileTo()
 {
     // Sign assembly A.
     SigningHelper.SignAssembly(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.A.dll"), null, Path.Combine(TestAssemblyDirectory, "IVT"));
     // Copy unsigned assembly B and just fix the references (has none but will fix InternalsVisibleTo).
     File.Copy(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.B.dll"), Path.Combine(TestAssemblyDirectory, "IVT", "Brutal.Dev.StrongNameSigner.TestAssembly.B.dll"), true);
     SigningHelper.FixAssemblyReference(Path.Combine(TestAssemblyDirectory, "IVT", "Brutal.Dev.StrongNameSigner.TestAssembly.A.dll"), Path.Combine(TestAssemblyDirectory, "IVT", "Brutal.Dev.StrongNameSigner.TestAssembly.B.dll")).ShouldBe(true);
 }
Exemplo n.º 10
0
        /// <summary>
        /// Async send the request to the server
        /// </summary>
        /// <returns>Async</returns>
        public async Task <string> SendAsync(DimeloRequest request)
        {
            // only create HttpClient once for performance
            if (_client == null)
            {
                _client = new HttpClient();
            }

            // creating the request
            StringContent content;

            try
            {
                // construct the json content first
                string json = request.GetJson();
                content = new StringContent(json, Encoding.UTF8, MEDIATYPE_JSON);

                // compute the signature
                string signature = SigningHelper.Sign(_accessToken, json);

                // set the necessary header(s)
                _client.DefaultRequestHeaders.Clear();
                _client.DefaultRequestHeaders.Add(SIGNATURE_ATTRIBUTE, signature);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Error setting the request to send", ex);
            }

            // send the request
            HttpResponseMessage response = null;

            try
            {
                response = await _client.PostAsync(_endpointUrl, content);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Error sending the request to {_endpointUrl}", ex);
            }

            // handle the response
            try
            {
                string responseContent = await response.Content.ReadAsStringAsync();

                // unsuccesful statuscodes are thrown as exception
                if (!response.IsSuccessStatusCode)
                {
                    throw new HttpRequestException($"Sending the request return HTTP status code {(int)response.StatusCode} {response.StatusCode} {responseContent}");
                }
                return(responseContent);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Error processing the response", ex);
            }
        }
Exemplo n.º 11
0
        public void GetAssemblyInfo_Detects_Obfuscated_Assembly()
        {
            var info = SigningHelper.GetAssemblyInfo(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET40-Obfuscated.exe")); info.IsSigned.ShouldBe(false);

            info.IsAnyCpu.ShouldBe(true);
            info.Is32BitOnly.ShouldBe(false);
            info.Is32BitPreferred.ShouldBe(false);
            info.Is64BitOnly.ShouldBe(false);
        }
Exemplo n.º 12
0
        public ActionResult Logout(FormCollection collection)
        {
            ViewBag.Message = "Logout effettuato";

            string dataBaseInBase64 = collection[0].ToString();

            if (String.IsNullOrEmpty(dataBaseInBase64))
            {
                Log.Error("Si è verificato un errore");

                return(View("Error"));
            }

            byte[] data = System.Convert.FromBase64String(dataBaseInBase64);

            string base64DecodedASCII = System.Text.Encoding.UTF8.GetString(data);

            Log.Debug(base64DecodedASCII);

            XmlDocument xml = new XmlDocument();

            xml.PreserveWhitespace = true;
            xml.LoadXml(base64DecodedASCII);

            if (SigningHelper.VerifySignature(xml, Log))
            {
                Dictionary <string, string> userInfo = new Dictionary <string, string>();

                using (StringReader sr = new StringReader(base64DecodedASCII))
                {
                    string result = sr.ReadToEnd();

                    int start = result.LastIndexOf("<saml2p:SessionIndex>");

                    int end = result.LastIndexOf("</saml2p:SessionIndex>");

                    string sessionId = result.Substring(start + 22, end - start - 22);

                    //usare Id di sessione per invalidare la sessione

                    HttpContext CurrentContext = System.Web.HttpContext.Current;
                    HttpCookie  requestCookie  = new HttpCookie("SPID_AUTHENTICATION");
                    requestCookie.Expires = DateTime.Now.AddMinutes(20);
                    requestCookie.Value   = "false";
                    CurrentContext.Response.Cookies.Add(requestCookie);

                    Session["AppUser"] = null;

                    return(View());
                }
            }
            else
            {
                return(View("Error"));
            }
        }
Exemplo n.º 13
0
        public void SignAssembly_Should_Reassemble_NET_20_x86_Assembly_Correctly()
        {
            var info = SigningHelper.SignAssembly(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET20-x86.exe"), string.Empty, Path.Combine(TestAssemblyDirectory, "Signed"));

            info.DotNetVersion.ShouldBe("2.0.50727");
            info.IsAnyCpu.ShouldBe(false);
            info.Is32BitOnly.ShouldBe(true);
            info.Is64BitOnly.ShouldBe(false);
            info.IsSigned.ShouldBe(true);
        }
Exemplo n.º 14
0
        public string GetSamlTokenFromCertificate(ServerDto serverDto, X509Certificate2 cert, RSACryptoServiceProvider rsaKey)
        {
            var soapString = XmlResourceHelper.GetResourceXml("Vmware.Tools.RestSsoAdminSnapIn.Service.xml.SamlTokenByCertificate.xml");

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            string signed  = "";
            var    dt      = DateTime.Now;
            var    dtStart = TimeZoneInfo.ConvertTimeToUtc(dt);
            var    dtEnd   = dtStart.AddMinutes(10);
            string format  = "yyyy-MM-ddTHH:mm:ss.fffZ";

            var    certString = Convert.ToBase64String(cert.RawData);
            string dtStartStr = dtStart.ToString(format);
            string dtEndStr   = dtEnd.ToString(format);

            soapString = string.Format(soapString, dtStartStr, dtEndStr, certString, dtStartStr, dtEndStr);
            signed     = SigningHelper.SignXmlFile(soapString, rsaKey);

            string xml2 = XmlResourceHelper.GetResourceXml("Vmware.Tools.RestSsoAdminSnapIn.Service.xml.SamlTokenByCertificate2.xml");

            xml2 = string.Format(xml2, dtStartStr, dtEndStr, certString, signed, dtStartStr, dtEndStr);

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.LoadXml(xml2);

            soapString = doc.InnerXml;
            var customHeaders = new Dictionary <string, string>();

            customHeaders.Add("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue");
            var headers       = ServiceHelper.AddHeaders("text/xml");
            var url           = serverDto.Url;
            var requestConfig = new RequestSettings
            {
                Method = HttpMethod.Post,
            };
            var token = _webRequestManager.GetResponse(url, requestConfig, headers, customHeaders, soapString);

            XmlDocument doc2 = new XmlDocument();

            doc2.PreserveWhitespace = false;
            doc2.LoadXml(token);
            var node = doc2.GetElementsByTagName("saml2:Assertion")[0];

            if (node != null)
            {
                return(node.OuterXml);
            }
            else
            {
                throw new Exception(token);
            }
        }
Exemplo n.º 15
0
        public void SignAssembly_Public_API_Test()
        {
            var info = SigningHelper.SignAssembly(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET20.exe"), string.Empty, Path.Combine(TestAssemblyDirectory, "Signed"));

            info.ShouldNotBe(null);
            info.DotNetVersion.ShouldBe("2.0.50727");
            info.Is32BitOnly.ShouldBe(false);
            info.Is32BitPreferred.ShouldBe(false);
            info.Is64BitOnly.ShouldBe(false);
            info.IsAnyCpu.ShouldBe(true);
            info.IsSigned.ShouldBe(true);
        }
Exemplo n.º 16
0
        private void ButtonAddClick(object sender, EventArgs e)
        {
            if (CommonOpenFileDialog.IsPlatformSupported)
            {
                using (CommonOpenFileDialog dialog = new CommonOpenFileDialog())
                {
                    dialog.Title            = openFileDialogAssembly.Title;
                    dialog.DefaultExtension = openFileDialogAssembly.DefaultExt;
                    dialog.Filters.Add(new CommonFileDialogFilter("Assembly files", "*.exe;*.dll"));
                    dialog.EnsurePathExists = true;
                    dialog.EnsureValidNames = true;
                    dialog.IsFolderPicker   = false;
                    dialog.Multiselect      = true;

                    if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                    {
                        foreach (var file in dialog.FileNames)
                        {
                            try
                            {
                                AddAssemblyToList(SigningHelper.GetAssemblyInfo(file));
                            }
                            catch (BadImageFormatException)
                            {
                                MessageBox.Show(string.Format(CultureInfo.CurrentCulture, "Could not get assembly info for '{0}'. This may not be a .NET assembly.", file), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                    }
                }
            }
            else
            {
                if (openFileDialogAssembly.ShowDialog() == DialogResult.OK)
                {
                    foreach (var file in openFileDialogAssembly.FileNames)
                    {
                        try
                        {
                            AddAssemblyToList(SigningHelper.GetAssemblyInfo(file));
                        }
                        catch (BadImageFormatException)
                        {
                            MessageBox.Show(string.Format(CultureInfo.CurrentCulture, "Could not get assembly info for '{0}'. This may not be a .NET assembly.", file), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }

            ResizeColumnWidths();

            buttonSign.Enabled = listViewAssemblies.Items.Count > 0;
        }
Exemplo n.º 17
0
        public string GetSamlTokenFromToken(ServerDto serverDto, string tokenXML, X509Certificate2 cert, RSACryptoServiceProvider rsaKey)
        {
            var soapString = XmlResourceHelper.GetResourceXml("Vmware.Tools.RestSsoAdminSnapIn.Service.xml.SamlTokenByToken.xml");

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            string signed  = "";
            var    dt      = DateTime.Now;
            var    dtStart = TimeZoneInfo.ConvertTimeToUtc(dt);
            var    dtEnd   = dtStart.AddMinutes(10);
            string format  = "yyyy-MM-ddTHH:mm:ss.fffZ";

            var xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(tokenXML);
            var samlAssertion = xmlDoc.GetElementsByTagName("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion");

            var    certString = Convert.ToBase64String(cert.RawData);
            string dtStartStr = dtStart.ToString(format);
            string dtEndStr   = dtEnd.ToString(format);

            soapString = string.Format(soapString, dtStartStr, dtEndStr, certString, samlAssertion[0].OuterXml, dtStartStr, dtEndStr);

            //var rsaKey = PrivateKeyHelper.DecodeRSAPrivateKey(Convert.FromBase64String(keyString));
            //var rsaKey =  (RSACryptoServiceProvider)cert.PrivateKey;
            signed = SigningHelper.SignXmlFile(soapString, rsaKey);

            string xml2 = XmlResourceHelper.GetResourceXml("Vmware.Tools.RestSsoAdminSnapIn.Service.xml.SamlTokenByToken2.xml");

            xml2 = string.Format(xml2, dtStartStr, dtEndStr, certString, samlAssertion[0].OuterXml, signed, dtStartStr, dtEndStr);

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.LoadXml(xml2);

            soapString = doc.InnerXml;
            var customHeaders = new Dictionary <string, string>();

            customHeaders.Add("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue");
            var headers       = ServiceHelper.AddHeaders("text/xml");
            var url           = serverDto.Url;
            var requestConfig = new RequestSettings
            {
                Method = HttpMethod.Post,
            };
            var response = _webRequestManager.GetResponse(url, requestConfig, headers, customHeaders, soapString);

            return(response);
        }
Exemplo n.º 18
0
        public AccessToken CreateToken(User user, List <OperationClaim> operationClaims)
        {
            _accessTokenExpiration = DateTime.Now.AddMinutes(_tokenOptions.AccessTokenExpiration);
            var securityKey        = SecurityKeyHelper.CreateSecurityKey(_tokenOptions.SecurityKey);
            var signingCredentials = SigningHelper.CreateSigningCredentials(securityKey);
            var jwt = CreateJwtSecurityToken(_tokenOptions, user, signingCredentials, operationClaims);
            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            var token = jwtSecurityTokenHandler.WriteToken(jwt);

            return(new AccessToken
            {
                Token = token,
                Expiration = _accessTokenExpiration
            });
        }
Exemplo n.º 19
0
        public void SignAssembly_InPlaceWithoutPdb_Should_Succeed()
        {
            var tempDir = Path.Combine(TestAssemblyDirectory, Guid.NewGuid().ToString("N"));

            Directory.CreateDirectory(tempDir);
            try
            {
                string targetAssemblyPath = Path.Combine(tempDir, "Brutal.Dev.StrongNameSigner.TestAssembly.A.dll");
                File.Copy(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.A.dll"), targetAssemblyPath);

                SigningHelper.SignAssembly(targetAssemblyPath);
                var info = SigningHelper.GetAssemblyInfo(targetAssemblyPath);
                Assert.IsTrue(info.IsSigned);
            }
            finally
            {
                Directory.Delete(tempDir, true);
            }
        }
Exemplo n.º 20
0
        private static bool SignSingleAssembly(string assemblyPath, string keyPath, string outputDirectory)
        {
            try
            {
                C.WriteLine();
                C.WriteLine("Strong-name signing {0}...", assemblyPath);

                var info = SigningHelper.GetAssemblyInfo(assemblyPath);
                if (!info.IsSigned)
                {
                    info = SigningHelper.SignAssembly(assemblyPath, keyPath, outputDirectory);

                    C.ForegroundColor = ConsoleColor.Green;
                    C.WriteLine("{0} was strong-name signed successfully!", info.FilePath);
                    C.ResetColor();

                    return(true);
                }
                else
                {
                    C.WriteLine("Already strong-name signed...");
                }
            }
            catch (BadImageFormatException bife)
            {
                C.ForegroundColor = ConsoleColor.Yellow;
                C.WriteLine("Warning: {0}", bife.Message);
                C.ResetColor();
            }
            catch (Exception ex)
            {
                C.ForegroundColor = ConsoleColor.Red;
                C.WriteLine("Error: {0}", ex.Message);
                C.ResetColor();
            }

            return(false);
        }
Exemplo n.º 21
0
        private void pbStep2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            Config         cfg             = new Config();
            String         path            = cfg.Get(Config.ANSWER_SHEET_IMG_PATH, "");

            if (path != "")
            {
                openFileDialog1.InitialDirectory = path;
            }
            openFileDialog1.Title            = "Chọn danh sách ảnh bài thi";
            openFileDialog1.CheckFileExists  = true;
            openFileDialog1.CheckPathExists  = true;
            openFileDialog1.Filter           = "dat Files (*.dat)|*.dat";
            openFileDialog1.DefaultExt       = "dat";
            openFileDialog1.FilterIndex      = 2;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.ReadOnlyChecked  = true;
            openFileDialog1.ShowReadOnly     = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filePath   = openFileDialog1.FileName;
                byte[] imageBytes = File.ReadAllBytes(filePath);
                if (SigningHelper.VerifyImages(imageBytes))
                {
                    List <Bitmap> imgs = SigningHelper.GetImagesFromEncryptedBytes(imageBytes);
                    bgImageProcessing.RunWorkerAsync(imgs);
                    processProgressBar.Visible           = true;
                    lbProcessProgressDescription.Visible = true;
                }
                else
                {
                    MessageBox.Show("File ảnh bài thi bị lỗi!!");
                }
            }
        }
Exemplo n.º 22
0
        private static bool FixSingleAssemblyReference(string assemblyPath, string referencePath)
        {
            try
            {
                C.WriteLine();
                C.WriteLine("Fixing references to '{1}' in '{0}'...", assemblyPath, referencePath);

                var info = SigningHelper.GetAssemblyInfo(assemblyPath);
                if (SigningHelper.FixAssemblyReference(assemblyPath, referencePath))
                {
                    C.ForegroundColor = ConsoleColor.Green;
                    C.WriteLine("References were fixed successfully!");
                    C.ResetColor();

                    return(true);
                }
                else
                {
                    C.WriteLine("Nothing to fix...");
                }
            }
            catch (BadImageFormatException bife)
            {
                C.ForegroundColor = ConsoleColor.Yellow;
                C.WriteLine("Warning: {0}", bife.Message);
                C.ResetColor();
            }
            catch (Exception ex)
            {
                C.ForegroundColor = ConsoleColor.Red;
                C.WriteLine("Error: {0}", ex.Message);
                C.ResetColor();
            }

            return(false);
        }
Exemplo n.º 23
0
 public void OneTimeSetUp()
 {
     TestingApiKey = SigningHelper.GetApiKey();
 }
Exemplo n.º 24
0
        /// <summary>
        /// GetPostSamlResponse - Returns a Base64 Encoded String with the SamlResponse in it.
        /// </summary>
        /// <param name="recipient">Recipient</param>
        /// <param name="issuer">Issuer</param>
        /// <param name="domain">Domain</param>
        /// <param name="subject">Subject</param>
        /// <param name="storeLocation">Certificate Store Location</param>
        /// <param name="storeName">Certificate Store Name</param>
        /// <param name="findType">Certificate Find Type</param>
        /// <param name="certLocation">Certificate Location</param>
        /// <param name="findValue">Certificate Find Value</param>
        /// <param name="certFile">Certificate File (used instead of the above Certificate Parameters)</param>
        /// <param name="certPassword">Certificate Password (used instead of the above Certificate Parameters)</param>
        /// <param name="attributes">A list of attributes to pass</param>
        /// <param name="signatureType">Whether to sign Response or Assertion</param>
        /// <returns>A base64Encoded string with a SAML response.</returns>
        public static string GetPostSamlResponse(string recipient, string issuer, string domain, string subject,
                                                 StoreLocation storeLocation, StoreName storeName, X509FindType findType, string certFile, string certPassword, object findValue,
                                                 Dictionary <string, string> attributes, SigningHelper.SignatureType signatureType)
        {
            ResponseType response = new ResponseType();

            // Response Main Area
            response.ID           = "_" + Guid.NewGuid().ToString();
            response.Destination  = recipient;
            response.Version      = "2.0";
            response.IssueInstant = System.DateTime.UtcNow;

            NameIDType issuerForResponse = new NameIDType();

            issuerForResponse.Value = issuer.Trim();

            response.Issuer = issuerForResponse;

            StatusType status = new StatusType();

            status.StatusCode       = new StatusCodeType();
            status.StatusCode.Value = "urn:oasis:names:tc:SAML:2.0:status:Success";

            response.Status = status;

            XmlSerializer responseSerializer =
                new XmlSerializer(response.GetType());

            StringWriter      stringWriter = new StringWriter();
            XmlWriterSettings settings     = new XmlWriterSettings();

            settings.OmitXmlDeclaration = true;
            settings.Indent             = true;
            settings.Encoding           = Encoding.UTF8;

            XmlWriter responseWriter = XmlTextWriter.Create(stringWriter, settings);

            string samlString = string.Empty;



            AssertionType assertionType = SamlHelper.CreateSamlAssertion(
                issuer.Trim(), recipient.Trim(), domain.Trim(), subject.Trim(), attributes);

            response.Items = new AssertionType[] { assertionType };

            responseSerializer.Serialize(responseWriter, response);
            responseWriter.Close();

            samlString = stringWriter.ToString();

            samlString = samlString.Replace("SubjectConfirmationData",
                                            string.Format("SubjectConfirmationData NotOnOrAfter=\"{0:o}\" Recipient=\"{1}\"",
                                                          DateTime.UtcNow.AddMinutes(5), recipient));

            stringWriter.Close();

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(samlString);
            X509Certificate2 cert = null;

            if (System.IO.File.Exists(certFile))
            {
                cert = new X509Certificate2(certFile, certPassword);
            }
            else
            {
                X509Store store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection coll = store.Certificates.Find(findType, findValue, true);
                if (coll.Count < 1)
                {
                    throw new ArgumentException("Unable to locate certificate");
                }
                cert = coll[0];
                store.Close();
            }

            XmlElement signature =
                SigningHelper.SignDoc(doc, cert, "ID",
                                      (signatureType == SigningHelper.SignatureType.Response || signatureType == SigningHelper.SignatureType.TestVU475445) ? response.ID : assertionType.ID);

            doc.DocumentElement.InsertBefore(signature,
                                             doc.DocumentElement.ChildNodes[1]);

            if (SamlHelper.Logger.IsDebugEnabled)
            {
                SamlHelper.Logger.DebugFormat(
                    "Saml Assertion before encoding = {0}",
                    doc.OuterXml.ToString());
            }

            string responseStr = doc.OuterXml;

            // 2018Ma06 Special Post-signature Maniuplation postsignature to inject comment into subject.
            if (signatureType == SigningHelper.SignatureType.TestVU475445)
            {
                string sub        = subject.Trim();
                int    half       = sub.Length / 2;
                string firstHalf  = sub.Substring(0, half);
                string secondHalf = sub.Substring(half);
                responseStr = responseStr.Replace(sub, firstHalf + "<!--VU475445-->" + secondHalf);
                int breaker = 1;
            }


            byte[] base64EncodedBytes =
                Encoding.UTF8.GetBytes(responseStr);

            string returnValue = System.Convert.ToBase64String(
                base64EncodedBytes);

            return(returnValue);
        }
Exemplo n.º 25
0
 public void SignAssembly_Public_API_Invalid_Path_Should_Throw_Exception()
 {
     SigningHelper.SignAssembly(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET20.doesnotexist"));
 }
Exemplo n.º 26
0
 public void SignAssembly_Public_API_Invalid_Key_Path_Should_Throw_Exception_For_Missing_File()
 {
     SigningHelper.SignAssembly(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET20.exe"), "C:\\KeyFileThatDoesNotExist.snk");
 }
Exemplo n.º 27
0
 public void SignAssembly_Public_API_Password_Protected_Key_Path_Should_Work_With_Correct_Password()
 {
     SigningHelper.SignAssembly(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET20.exe"), Path.Combine(TestAssemblyDirectory, "PasswordTest.pfx"), Path.Combine(TestAssemblyDirectory, "Signed"), "password123");
 }
Exemplo n.º 28
0
 public void SignAssembly_Public_API_Password_Protected_Key_Path_Should_Throw_Exception_When_Wrong_Password_Provided()
 {
     SigningHelper.SignAssembly(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET20.exe"), Path.Combine(TestAssemblyDirectory, "PasswordTest.pfx"), Path.Combine(TestAssemblyDirectory, "Signed"), "oops");
 }
 public void OneTimeSetUp()
 {
     GoogleSigned.AssignAllServices(SigningHelper.GetApiKey());
 }
Exemplo n.º 30
0
 public void SignAssembly_Public_API_Invalid_Key_Path_Should_Throw_Exception_For_Missing_Directory()
 {
     Assert.Throws <DirectoryNotFoundException>(() => SigningHelper.SignAssembly(Path.Combine(TestAssemblyDirectory, "Brutal.Dev.StrongNameSigner.TestAssembly.NET40.exe"), "C:\\DoesNotExist\\KeyFile.snk"));
 }