private CertificateGenerator BuildCertGenerator(string name, string password)
        {
            var generator = new CertificateGenerator(SubscriptionId, ManagementCertificate);

            generator.Create(name, DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)), DateTime.UtcNow.AddYears(2), password);
            return(generator);
        }
        // Requests a certificate to be generated by the Bridge
        // If the certificate requested is for the local machine, for example if
        // server hostname is: foo.bar.com
        // local address is considered to be: 127.0.0.1, localhost, foo, foo.bar.com
        // Then we also install the certificate to the local machine, because it means we are about to run an HTTPS/SSL test against
        // this machine.
        // Otherwise, don't bother installing as the cert is for a remote machine.
        public override ResourceResponse Put(ResourceRequestContext context)
        {
            X509Certificate2 certificate;

            string subject;

            if (!context.Properties.TryGetValue(subjectKeyName, out subject) || string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("When PUTting to this resource, specify an non-empty 'subject'", "context.Properties");
            }

            // There can be multiple subjects, separated by ,
            string[] subjects = subject.Split(',');

            bool isLocal = IsLocalMachineResource(subjects[0]);

            lock (s_certificateResourceLock)
            {
                if (!s_createdCertsBySubject.TryGetValue(subjects[0], out certificate))
                {
                    CertificateGenerator generator = CertificateResourceHelpers.GetCertificateGeneratorInstance(context.BridgeConfiguration);

                    if (isLocal)
                    {
                        // If we're PUTting a cert that refers to a hostname local to the bridge,
                        // return the Local Machine cert that CertificateManager caches and add it to the collection
                        //
                        // If we are receiving a PUT to the same endpoint address as the bridge server, it means that
                        // a test is going to be run on this box
                        //
                        // In keeping with the semantic of these classes, we must PUT before we can GET a cert
                        certificate = CertificateManager.CreateAndInstallLocalMachineCertificates(generator);
                    }
                    else
                    {
                        CertificateCreationSettings certificateCreationSettings = new CertificateCreationSettings()
                        {
                            Subjects = subjects,
                        };
                        certificate = generator.CreateMachineCertificate(certificateCreationSettings).Certificate;
                    }

                    X509Certificate2 dummy;
                    if (!isLocal || !s_createdCertsByThumbprint.TryGetValue(certificate.Thumbprint, out dummy))
                    {
                        // when isLocal, it's possible for there to be > 1 subject sharing the same thumbprint
                        // in this case, we only cache the first isLocal subject, the rest we don't cache
                        s_createdCertsBySubject.Add(subjects[0], certificate);
                        s_createdCertsByThumbprint.Add(certificate.Thumbprint, certificate);
                    }
                }
            }

            ResourceResponse response = new ResourceResponse();

            response.Properties.Add(thumbprintKeyName, certificate.Thumbprint);
            response.Properties.Add(isLocalKeyName, isLocal.ToString());

            return(response);
        }
Example #3
0
        public void IsForEncryption(X509KeyUsageFlags flags, bool exceptedResult)
        {
            X509Certificate2 certificate = CertificateGenerator.Create("X509Certificate2ExtensionsTests", flags);
            bool             result      = certificate.IsForEncryption();

            Assert.AreEqual(exceptedResult, result);
        }
Example #4
0
        internal static void ResetCertificateGenerator(ResourceRequestContext context)
        {
            var config = context.BridgeConfiguration;

            if (s_certificateGenerator == null)
            {
                lock (s_certificateHelperLock)
                {
                    if (s_certificateGenerator == null)
                    {
                        s_certificateGenerator = new CertificateGenerator()
                        {
                            CertificatePassword = config.BridgeCertificatePassword,
                            CrlUriBridgeHost    = string.Format("http://{0}:{1}", config.BridgeHost, config.BridgePort),
                            CrlUriRelativePath  = s_crlUriRelativePath,
                            ValidityPeriod      = config.BridgeCertificateValidityPeriod
                        };

                        // Upon creation, we want to immediately get the authority certificate and install it
                        // as it means we are about to run a test requiring certs
                        CertificateManager.InstallCertificateToRootStore(s_certificateGenerator.AuthorityCertificate.Certificate);
                    }
                }
            }
        }
Example #5
0
        public static X509Certificate2 CreateSelfSignedCertificate(string subject)
        {
            var oids = new OidCollection();

            oids.Add(new Oid("1.3.6.1.5.5.7.3.2")); // client auth

            var extensions = new X509ExtensionCollection();

            extensions.Add(new X509EnhancedKeyUsageExtension(oids, true));

            var cgr = new CertificateGenerationRequest()
            {
                Subject          = subject,
                Extensions       = extensions,
                ExpirationLength = TimeSpan.FromDays(365 * 5),
                KeySize          = 2048
            };

            var cert = CertificateGenerator.CreateSelfSignedCertificate(cgr);

            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            try
            {
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);
            }
            finally
            {
                store.Close();
            }

            return(cert);
        }
Example #6
0
 private static void OnResourceFolderChanged(object sender, EventArgs args)
 {
     lock (s_certificateHelperLock)
     {
         s_certificateGenerator = null;
     }
 }
Example #7
0
        static public void CreateGroup(APIServer server, CertificateGenerator generator)
        {
            // Generate group Certificate
            var groupKeys = generator.GenerateCertificate("C=DE,O=Organiztion", TimeSpan.FromDays(1), "cert.pfx", "Test.123");

            Console.WriteLine("Group certificate was generated");

            BlindSigner  blindSigner  = new BlindSigner(groupKeys);
            GroupCreator groupCreator = new GroupCreator(server, blindSigner);

            Console.WriteLine("Create group");
            Console.WriteLine("Enter group name:");
            string groupName = Console.ReadLine();
            //string groupName = "Loazarii";
            Group group = new Group();

            group.Name = groupName;
            Console.WriteLine("Enter owner email:");
            string ownerEmail = Console.ReadLine();

            //string ownerEmail = "*****@*****.**";
            group.OwnerEmail   = ownerEmail;
            group.RsaPublicKey = (RsaKeyParameters)groupKeys.Public;
            groupCreator.RegisterGroup(group);
            Console.WriteLine("");

            //Write keys to file
            File.WriteAllText(group.Name + "PublicKey.txt", RsaKeyUtils.GetSerializedPublicKey((RsaKeyParameters)groupKeys.Public));
            File.WriteAllText(group.Name + "PrivateKey.txt", RsaKeyUtils.GetSerializedPrivateKey((RsaKeyParameters)groupKeys.Private));

            Console.WriteLine("You're group " + group.Name + " was registered!");
        }
Example #8
0
        public void Example_SignDocument()
        {
            using X509Certificate2 signingCertificate = CertificateGenerator.Create("Signer", X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.DigitalSignature);

            Assert.IsTrue(signingCertificate.IsForDocumentSigning());

            byte[] data = Encoding.UTF8.GetBytes("Hello World!");

            ContentInfo content   = new ContentInfo(data);
            SignedCms   signedCms = new SignedCms(content, false);

            CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate);

            signer.DigestAlgorithm = new Oid(Oids.SHA256);
            signer.IncludeOption   = X509IncludeOption.WholeChain;
            signer.SignedAttributes.Add(new AsnEncodedData(new Pkcs9SigningTime(DateTime.Now)));
            signer.SignedAttributes.Add(new Pkcs7IdAaContentHint("helloWorld.txt", "text/plain"));
            signer.SignedAttributes.Add(new Pkcs7IdAaSigningCertificateV2(signingCertificate));
            signer.SignedAttributes.Add(new Pkcs9IdSigningPolicy("1.3.158.36061701.1.2.2", HashAlgorithmName.SHA256, "1A5A86D067512E00DB45FCD8DFB9A0574749D1D1F2A7189ED9F2DFE6ADE82DBD")); // Only for old Slovak format - SK ZEP

            signedCms.ComputeSignature(signer, false);
            byte[] eidasP7mFileBytes = signedCms.Encode();

            Assert.IsNotNull(eidasP7mFileBytes);
        }
Example #9
0
        public static IWebHost BuildWebHost() =>
        WebHost.CreateDefaultBuilder()
        .UseKestrel(
            options =>
        {
#if DEBUG
            options.Listen(IPAddress.Loopback, 5000);
            backendServerPort = 5000;
#else
            // Get free TCP port and write it to STDOUT where the Electron frontend can catch it.
            backendServerPort = FindFreeTcpPort();
            options.Listen(IPAddress.Loopback, backendServerPort, listenOptions =>
            {
                var httpsOptions =
                    new HttpsConnectionAdapterOptions
                {
                    ServerCertificate =
                        CertificateGenerator
                        .GenerateCertificate(
                            $"CN={DigestUtils.GetDigestFromAssembly(typeof(Program).Assembly).ToLowerInvariant()}")
                };

                listenOptions.UseHttps(httpsOptions);
            });
#endif
        })
        .UseStartup <Startup>()
        .Build();
Example #10
0
        public async Task Example_SignDocumentWithTs()
        {
            using X509Certificate2 signingCertificate = CertificateGenerator.Create("Signer", X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.DigitalSignature);
            Assert.IsTrue(signingCertificate.IsForDocumentSigning());

            byte[] data = Encoding.UTF8.GetBytes("Hello World!");

            ContentInfo content   = new ContentInfo(data);
            SignedCms   signedCms = new SignedCms(content, false);

            CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate);

            signer.DigestAlgorithm = new Oid(Oids.SHA256);
            signer.IncludeOption   = X509IncludeOption.WholeChain;
            signer.SignedAttributes.Add(new AsnEncodedData(new Pkcs9SigningTime(DateTime.Now)));
            signer.SignedAttributes.Add(new Pkcs7IdAaContentHint("helloWorld.txt", "text/plain"));
            signer.SignedAttributes.Add(new Pkcs7IdAaSigningCertificateV2(signingCertificate));
            // Without Pkcs9IdSigningPolicy

            signedCms.ComputeSignature(signer, false);

            await this.CreateTimeStamp(signedCms);

            byte[] eidasP7mFileBytes = signedCms.Encode();

            Assert.IsNotNull(eidasP7mFileBytes);
        }
Example #11
0
        public CertificatesController(ULearnDb db, WebCourseManager courseManager)
        {
            this.courseManager = courseManager;

            certificatesRepo     = new CertificatesRepo(db);
            userManager          = new ULearnUserManager(db);
            certificateGenerator = new CertificateGenerator(db, courseManager);
        }
Example #12
0
        public void Setup()
        {
            _fileSystemMock  = new Mock <IFileSystem>();
            _objectUnderTest = new CertificateGenerator(_fileSystemMock.Object);


            _loggerListenerMock = new Mock <ILoggerListener>();
            AppioLogger.RegisterListener(_loggerListenerMock.Object);
        }
Example #13
0
        public void GenerateSelfSigned(string commonName = "ah101Signed")
        {
            const string outputFile = "certs\\general.pfx";

            X509Certificate2 generalCert =
                CertificateGenerator.CreateSelfSignedCertificate(commonName, new string[] { "example.com" }, new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth });

            CertificateGenerator.WriteCertificate(generalCert, outputFile);
        }
Example #14
0
        public void IsForEmailProtection(X509KeyUsageFlags flags, bool exceptedResult)
        {
            X509Certificate2 certificate = (exceptedResult) ?
                                           CertificateGenerator.Create("X509Certificate2ExtensionsTests", flags, "1.3.6.1.5.5.7.3.4") :
                                           CertificateGenerator.Create("X509Certificate2ExtensionsTests", flags);

            bool result = certificate.IsForEmailProtection();

            Assert.AreEqual(exceptedResult, result);
        }
Example #15
0
        public void GetEncoded(AsnFormat format)
        {
            X509Certificate2 certificate = CertificateGenerator.Create("X509Certificate2ExtensionsTests");

            byte[] encoded = certificate.GetEncoded(format);

            X509Certificate2 result = new X509Certificate2(encoded);

            Assert.IsNotNull(result);
        }
Example #16
0
        public bool GenerateCA(string commonName = "ah101CA")
        {
            if (!IsAdmin())
            {
                return(false);
            }
            X509Certificate2 caCert = CertificateGenerator.CreateCertificateAuthorityCertificate(commonName, null, null);

            CertificateGenerator.WriteCertificate(caCert, "certs\\AHROOT.pfx");
            return(true);
        }
        public void GenerateNewLeafCertificate(string name, string organization, string organizationalUnit, string city, string stateCode, string countryCode, string password, string additionalSANs = null)
        {
            if (!Directory.Exists(CAStorePathInfo.CACertPath))
            {
                Directory.CreateDirectory(CAStorePathInfo.CACertPath);
            }

            CertificateGenerator generator = new CertificateGenerator();

            String        subjectDN = $"CN={name},O={organization},OU={organizationalUnit},L={city},C={countryCode}"; //,ST={stateCode}";
            List <String> sanList   = new List <String>()
            {
                name
            };

            Console.WriteLine("Additional SANs: " + additionalSANs);
            if (additionalSANs != null)
            {
                string[] moreSANs = additionalSANs.Split(',');
                sanList.AddRange(moreSANs);
            }
            String[] subjectAlternativeNames = sanList.ToArray();

            KeyPurposeID[] usages = new List <KeyPurposeID>()
            {
                //KeyPurposeID.AnyExtendedKeyUsage,
                KeyPurposeID.IdKPClientAuth,
                KeyPurposeID.IdKPEmailProtection,
                KeyPurposeID.IdKPServerAuth
            }.ToArray();

            X509Certificate2    issuerCertificate = GetCACertificate("test").Certificate;
            AsymmetricAlgorithm issuerPrivateKey  = issuerCertificate.GetRSAPrivateKey();

            X509Certificate2 certForCA = generator.IssueCertificate(subjectDN, issuerCertificate, issuerPrivateKey, subjectAlternativeNames, usages).Certificate;


            try
            {
                if (!Directory.Exists(CAStorePathInfo.LeafCertPath))
                {
                    Directory.CreateDirectory(CAStorePathInfo.LeafCertPath);
                }

                String leafPathAndFilename = Path.Combine(CAStorePathInfo.LeafCertPath, $"{certForCA.Thumbprint}.pfx");

                File.WriteAllBytes(leafPathAndFilename, certForCA.Export(X509ContentType.Pfx, password));
                Console.WriteLine("PFX/PKCS12: SUCCESS");
            }
            catch (Exception exception)
            {
                Console.WriteLine("PFX/PKCS12: " + exception.Message);
            }
        }
        public void GetNameInfo_ForSubject(string subject, string oid, string values)
        {
            string[] nameValues = values.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            X509Certificate2 certificate = CertificateGenerator.Create(subject);

            IReadOnlyList <string> resultList1 = certificate.GetNameInfo(oid, false);
            IReadOnlyList <string> resultList2 = certificate.GetNameInfo(oid, X509NameSource.Subject);

            CollectionAssert.AreEquivalent(nameValues, resultList1.ToArray(), "Error with bool variant.");
            CollectionAssert.AreEquivalent(nameValues, resultList2.ToArray(), "Error with X509NameSource variant.");
        }
Example #19
0
        public void BCGenerateCertificate(string hostName)
        {
            if (!File.Exists("certs\\AHROOT.pfx"))
            {
                return;
            }
            X509Certificate2 caCert     = CertificateGenerator.LoadCertificate("certs\\AHROOT.pfx", "password");
            X509Certificate2 serverCert = CertificateGenerator.IssueCertificate(hostName, caCert, new string[] { hostName, "*." + hostName }, new KeyPurposeID[] {
                KeyPurposeID.IdKPServerAuth
            });

            CertificateGenerator.WriteCertificate(serverCert, "certs\\" + hostName + ".pfx");
        }
        public void GetNameInfo_ForIssuer(string subject, string oid, string values)
        {
            string[] nameValues = values.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            X509Certificate2 issuerCertificate = CertificateGenerator.Create(subject, X509KeyUsageFlags.KeyCertSign);
            X509Certificate2 certificate       = CertificateGenerator.Create("CN=end", signedCertificate: issuerCertificate);

            IReadOnlyList <string> resultList1 = certificate.GetNameInfo(oid, true);
            IReadOnlyList <string> resultList2 = certificate.GetNameInfo(oid, X509NameSource.Issuer);

            CollectionAssert.AreEquivalent(nameValues, resultList1.ToArray(), "Error with bool variant.");
            CollectionAssert.AreEquivalent(nameValues, resultList2.ToArray(), "Error with X509NameSource variant.");
        }
Example #21
0
        public void GenerateCsrTest()
        {
            var certificateSubjectText = "CN=Magnet, C=NL";

            var generator = new CertificateGenerator();

            var keypair = generator.GenerateKeyPair();

            var csr = generator.GenerateCsr(keypair, certificateSubjectText);

            Assert.NotNull(csr.CsrAsPem);
            Assert.NotNull(csr.PrivateKeyAsPem);
        }
        public async Task <ActionResult> Index2()
        {
            var _merchantPFXForTest            = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/1231181189.p12"));
            var _merchantCertificateDataInPEM  = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/prod.pem"));
            var _merchantCertificateDataInPEM2 = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/prod2.pem"));
            var _merchantPrivateKey            = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/private.key"));
            var _merchantCertificatePassword   = "";
            var _merchantId = "test";

            bool test1, test2 = false, test3;

            var bytes = CertificateGenerator.GenerateP12(_merchantPrivateKey, _merchantCertificateDataInPEM, "");

            var client = new SwishClient(SwishEnvironment.Production,
                                         P12CertificateCollectionBytes: bytes,
                                         P12CertificateCollectionPassphrase: _merchantCertificatePassword,
                                         merchantId: _merchantId);

            var paymentStatus = await client.GetPaymentStatus("anything");

            test1 = true;


            var bytes2  = CertificateGenerator.GenerateP12(_merchantPrivateKey, _merchantCertificateDataInPEM2, "");
            var client2 = new SwishClient(SwishEnvironment.Production,
                                          P12CertificateCollectionBytes: bytes2,
                                          P12CertificateCollectionPassphrase: "swish",
                                          merchantId: _merchantId);

            try
            {
                var paymentStatus2 = await client2.GetPaymentStatus("anything");
            }
            catch (Exception ex)
            {
                test2 = true;
            }

            var paymentStatus3 = await client.GetPaymentStatus("anything");

            var client4 = new SwishClient(SwishEnvironment.Production,
                                          P12CertificateCollectionBytes: bytes,
                                          P12CertificateCollectionPassphrase: _merchantCertificatePassword,
                                          merchantId: _merchantId);

            var paymentStatus4 = await client.GetPaymentStatus("anything");

            test3 = true;

            return(test1 && test2 && test3?View() : View("Error"));
        }
Example #23
0
        static void Main(string[] args)
        {
            SignatureVerifier  signatureVerifier = new SignatureVerifier();
            RNGRandomGenerator rngGenerator      = new RNGRandomGenerator();
            EmailSender        emailSender       = new EmailSender();
            BlindChatDbContext context           = new BlindChatDbContext();
            GroupRepository    groupRepository   = new GroupRepository(context);
            APIServer          server            = new APIServer(groupRepository, emailSender, rngGenerator, signatureVerifier);

            CertificateGenerator generator = new CertificateGenerator();


            int userInput = 0;

            do
            {
                userInput = DisplayMenu();
                switch (userInput.ToString())
                {
                case "1":
                    CreateGroup(server, generator);
                    break;

                case "2":
                    InviteParticipants(context, server);
                    break;

                case "3":
                    RegisterParticipant(server, groupRepository, generator);
                    break;

                case "4":
                    SignCertificate(server);
                    break;

                case "5":
                    SaveBlindParticipant(server, groupRepository);
                    break;

                case "6":
                    SendMessageOnGroup(server, groupRepository);
                    break;

                default:
                    Console.WriteLine("Default case");
                    break;
                }
            } while (userInput != 7);
        }
Example #24
0
        public async Task <int> OnExecuteAsync(CommandLineApplication app)
        {
            var fileWriter = new FileWriter(app.Out);

            if (OutputPath != null &&
                _hasWebhooks &&
                (!File.Exists(Path.Join(OutputPath, "ca.pem")) || !File.Exists(Path.Join(OutputPath, "ca-key.pem"))))
            {
                using var certManager = new CertificateGenerator(app.Out);
                await certManager.CreateCaCertificateAsync(OutputPath);
            }

            fileWriter.Add(
                $"kustomization.{Format.ToString().ToLower()}",
                _serializer.Serialize(
                    new KustomizationConfig
            {
                Resources = new List <string>
                {
                    $"deployment.{Format.ToString().ToLower()}",
                },
                CommonLabels = new Dictionary <string, string>
                {
                    { "operator-element", "operator-instance" },
                },
                ConfigMapGenerator = _hasWebhooks
                            ? new List <KustomizationConfigMapGenerator>
                {
                    new()
                    {
                        Name  = "webhook-ca",
                        Files = new List <string>
                        {
                            "ca.pem",
                            "ca-key.pem",
                        },
                    },
                    new()
                    {
                        Name     = "webhook-config",
                        Literals = new List <string>
                        {
                            "KESTREL__ENDPOINTS__HTTP__URL=http://0.0.0.0:80",
                            "KESTREL__ENDPOINTS__HTTPS__URL=https://0.0.0.0:443",
                            "KESTREL__ENDPOINTS__HTTPS__CERTIFICATE__PATH=/certs/server.pem",
                            "KESTREL__ENDPOINTS__HTTPS__CERTIFICATE__KEYPATH=/certs/server-key.pem",
                        },
                    },
                }
        // Requests a certificate to be generated by the Bridge based on a user name and not machine name
        public override ResourceResponse Put(ResourceRequestContext context)
        {
            X509Certificate2 certificate;

            string subject;

            if (!context.Properties.TryGetValue(subjectKeyName, out subject) || string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("When PUTting to this resource, specify an non-empty 'subject'", "context.Properties");
            }

            // There can be multiple subjects, separated by ,
            string[] subjects = subject.Split(',');

            lock (s_certificateResourceLock)
            {
                if (!s_createdCertsBySubject.TryGetValue(subjects[0], out certificate))
                {
                    CertificateGenerator generator = CertificateResourceHelpers.GetCertificateGeneratorInstance(context.BridgeConfiguration);

                    CertificateCreationSettings certificateCreationSettings = new CertificateCreationSettings()
                    {
                        FriendlyName            = "WCF Bridge - UserCertificateResource",
                        Subject                 = subjects[0],
                        SubjectAlternativeNames = subjects
                    };
                    certificate = generator.CreateUserCertificate(certificateCreationSettings).Certificate;

                    // Cache the certificates
                    s_createdCertsBySubject.Add(subjects[0], certificate);
                    s_createdCertsByThumbprint.Add(certificate.Thumbprint, certificate);

                    // Created certs get put onto the local machine
                    // We ideally don't want this to happen, but until we find a way to have BridgeClient not need elevation for cert installs
                    // we need this to happen so that running locally doesn't require elevation as it messes up our CI and developer builds
                    CertificateManager.InstallCertificateToMyStore(certificate);
                }
            }

            ResourceResponse response = new ResourceResponse();

            response.Properties.Add(thumbprintKeyName, certificate.Thumbprint);

            return(response);
        }
        public async Task CertificateAcceptedTest23()
        {
            var bytes = CertificateGenerator.GenerateP12(_merchantPrivateKey, _merchantCertificateDataInPEM, "");

            var client = new SwishClient(SwishEnvironment.Production,
                P12CertificateCollectionBytes: bytes,
                P12CertificateCollectionPassphrase: "",
                merchantId: "123");

            var paymentStatus = await client.GetPaymentStatus("test");

            var client2 = new SwishClient(SwishEnvironment.Production,
                P12CertificateCollectionBytes: bytes,
                P12CertificateCollectionPassphrase: "",
                merchantId: "123");

            var paymentStatus2 = await client2.GetPaymentStatus("test");
        }
Example #27
0
        /// <summary>
        /// this method produces a valid SSL certificate given an account email and a domain
        /// </summary>
        /// <returns></returns>
        public static async Task Main()
        {
            // get an IDnsUpdater
            IDnsUpdater dnsUpdater = new PowerShellWindowsDnsUpdater();
            // get a client with the specified account
            IACMEClient client = new ACMEWebAPIClient(ACMEWebAPIClient.STAGE_API_ENDPOINT);
            // get a wrapper which will automate the process of obtaining a certificate
            var wrapper = new CertificateGenerator(client, dnsUpdater);

            // parameters
            var path             = Path.GetTempPath();
            var userAccount      = "*****@*****.**";
            var domainToGenerate = "testdomain.com";

            var x = await wrapper.SaveNewWildCardCertificate(userAccount, domainToGenerate, path);

            Console.WriteLine($"Saved certificate to: {x}");
        }
        /// <summary>
        /// Checks view availability
        /// </summary>
        /// <param name="testRun">The testRun used to generate the view calling script</param>
        /// <param name="output">An output parameter, used to capture the exception message</param>
        /// <returns>True, the compilation is a success; false, the compilation failed</returns>
        public static bool CheckViewAvailability(string scriptToCompile, out string output)
        {
            var certificate = CertificateGenerator.GetCertificateFromBase64String();

            VC.Setup(null, certificate);

            var    scriptFilePath   = $"./TheScript_{Guid.NewGuid()}.script";
            var    isSuccessful     = true;
            string exceptionMessage = "Succesful Compilation";

            try
            {
                File.WriteAllText(scriptFilePath, scriptToCompile);
                try
                {
                    ScopeClient.Scope.Compile(scriptFilePath);
                }
                // This exception catches the following conditions:
                // The View is not at the location specified.
                // The data behind the view is not available.
                // The View itself has error handling, and we have run into a view defined issue.
                // The view itself has an error within it during compilation
                catch (ScopeClient.CompilationErrorException e)
                {
                    var trimmedCompilationError = GetCosmosCompileErrorMessage(e.Message);

                    exceptionMessage = trimmedCompilationError;
                }
            }
            finally
            {
                if (File.Exists(scriptFilePath))
                {
                    File.Delete(scriptFilePath);
                }
            }

            output = exceptionMessage;
            return(isSuccessful);
        }
        public async Task CertificateAcceptedTest2()
        {
            var bytes = CertificateGenerator.GenerateP12(_merchantPrivateKey, _merchantCertificateDataInPEM, "");

            var client = new SwishClient(SwishEnvironment.Production,
                P12CertificateCollectionBytes: bytes,
                P12CertificateCollectionPassphrase: _merchantCertificatePassword,
                merchantId: _merchantId);

            var paymentStatus = await client.GetPaymentStatus("anything");

            // should be "not found" in the error message, which states that connection is established but obviously transaction was not found
            Assert.NotNull(paymentStatus.ErrorMessage);

            // now test misconfigured client (should throw exception)
            var clientWithWrongPfx = new SwishClient(SwishEnvironment.Production,
                P12CertificateCollectionBytes: _merchantPFXForTest,
                P12CertificateCollectionPassphrase: "swish",
                merchantId: _merchantId);

            try
            {
                var _ = await clientWithWrongPfx.GetPaymentStatus("anything");
            }
            catch (Exception ex)
            {

            }

            // now create working client to check if any of the certificates sticked from last one
            var client2 = new SwishClient(SwishEnvironment.Production,
                P12CertificateCollectionBytes: bytes,
                P12CertificateCollectionPassphrase: _merchantCertificatePassword,
                merchantId: _merchantId);

            var paymentStatus2 = await client.GetPaymentStatus("anything");

            // should be "not found" in the error message, which states that connection is established but obviously transaction was not found
            Assert.NotNull(paymentStatus.ErrorMessage);
        }
Example #30
0
        public bool InstallToTrustedRoot()
        {
            const string caCertFile = "certs\\AHROOT.pfx";

            if (!File.Exists(caCertFile))
            {
                return(false);
            }
            X509Certificate2 caCert = CertificateGenerator.LoadCertificate(caCertFile, "password");

            try
            {
                X509Store certStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                certStore.Open(OpenFlags.ReadWrite);
                certStore.Add(caCert);
                certStore.Close();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }