Ejemplo n.º 1
0
        /// <summary>
        /// Compare names
        /// </summary>
        /// <param name="name"></param>
        /// <param name="other"></param>
        /// <returns></returns>
        public static bool SameAs(this X500DistinguishedName name, X500DistinguishedName other)
        {
            var n1 = name?.Name;
            var n2 = other?.Name;

            return(CertUtils.CompareDistinguishedName(n1, n2));
        }
        public void GetMasterKeyCertificate_CertNotCached_ReturnsFromLocator()
        {
            var options = new MsisClientCertLocator.Config
            {
                CertId = "key-id"
            };
            var    cacheKey          = nameof(MsisClientCertLocator);
            object emptyCachedResult = null;
            var    certificate       = CertUtils.GenerateTestEccCert();

            var automocker = new AutoMocker();

            automocker.SetupOptions(options);

            automocker
            .Setup <IMemoryCache, bool>(x => x.TryGetValue(cacheKey, out emptyCachedResult))
            .Returns(false);

            automocker
            .Setup <IMemoryCache, ICacheEntry>(x => x.CreateEntry(cacheKey))
            .Returns(Mock.Of <ICacheEntry>());

            automocker
            .Setup <ICertificateLocator, Option <X509Certificate2> >(x => x.GetCertificate("key-id"))
            .Returns(certificate.Some());

            var target = automocker.CreateInstance <MsisClientCertLocator>();

            var result = target.GetCertificate();

            result.Should().Be(certificate);
        }
        public void Pkcs11RsaSignatureReuseTest()
        {
            using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm))
            {
                byte[]        signingCertificate       = pkcs11RsaSignature.GetSigningCertificate();
                List <byte[]> otherCertificates        = pkcs11RsaSignature.GetAllCertificates();
                ICollection <X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates);

                for (int i = 0; i < 100; i++)
                {
                    string unsignedPdfPath = GetTempDocPath();
                    string signedPdfPath   = GetTempDocPath();

                    try
                    {
                        GenerateRandomPdf(unsignedPdfPath);

                        using (PdfReader pdfReader = new PdfReader(unsignedPdfPath))
                            using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create))
                                using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', GetTempDocPath(), true))
                                    MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES);

                        Assert.IsTrue(1 == VerifySignatureIntegrity(signedPdfPath));
                    }
                    finally
                    {
                        File.Delete(unsignedPdfPath);
                        File.Delete(signedPdfPath);
                    }
                }
            }
        }
Ejemplo n.º 4
0
        public void FindUserCertificates(StoreName storeName, X509FindType type, object value)
        {
            var certs1 = CertUtils.FindCertificates(StoreLocation.CurrentUser, storeName, type, value, validOnly: true);
            var certs2 = CertUtils.FindUserCertificates(type, value, storeName, validOnly: true);

            Assert.That(certs1, Is.EqualTo(certs2));
        }
        public void AddMsisLookup_GivenMockDisabled_AddsRealClientToCollection()
        {
            // Arrange
            var config = new MsisConfig
            {
                Mock    = false,
                CertId  = "some-cert",
                BaseUrl = "https://msis.api.com/api/v1/"
            };

            var certificate = CertUtils.GenerateTestEccCert();

            var certLocator = new Mock <ICertificateLocator>();

            certLocator
            .Setup(x => x.GetCertificate("some-cert"))
            .Returns(certificate.Some());

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddSingleton(certLocator.Object);

            // Act
            serviceCollection.AddMsisLookup(config);

            // Assert
            var serviceProvider = serviceCollection.BuildServiceProvider();
            var msisClient      = serviceProvider.GetRequiredService <IMsisClient>();

            msisClient.Should().BeOfType <MsisClient>();
            certLocator.Verify();
        }
Ejemplo n.º 6
0
        public async Task GetSigningCredentialsAsync_ResultNotCachedMultipleValidVersions_ReturnsFirstOlderThanRollover()
        {
            //Arrange
            var cert1 = CertUtils.GenerateTestCert();
            var cert2 = CertUtils.GenerateTestCert();
            var cert3 = CertUtils.GenerateTestCert();

            var    rollover     = TimeSpan.FromHours(2);
            var    epsilon      = TimeSpan.FromSeconds(1);
            object cachedResult = null;

            var automocker = new AutoMocker();

            automocker
            .Setup <IMemoryCache, bool>(x => x.TryGetValue("IsOAuthCerts", out cachedResult))
            .Returns(false);

            automocker
            .Setup <IMemoryCache, ICacheEntry>(x => x.CreateEntry("IsOAuthCerts"))
            .Returns(Mock.Of <ICacheEntry>());

            automocker
            .Setup <IOptions <SigningCredentialsStore.Config>, SigningCredentialsStore.Config>(x => x.Value)
            .Returns(new SigningCredentialsStore.Config
            {
                Signing             = "cert-id",
                KeyRolloverDuration = rollover
            });

            automocker
            .Setup <ICertificateLocator, Task <ICollection <CertificateVersion> > >(x =>
                                                                                    x.GetAllEnabledCertificateVersionsAsync("cert-id"))
            .ReturnsAsync(new[]
            {
                new CertificateVersion
                {
                    Certificate = cert1,
                    Timestamp   = DateTime.UtcNow
                },
                new CertificateVersion
                {
                    Certificate = cert2,
                    Timestamp   = DateTime.UtcNow - rollover - epsilon
                },
                new CertificateVersion
                {
                    Certificate = cert3,
                    Timestamp   = DateTime.UtcNow - rollover - epsilon
                }
            });

            var target = automocker.CreateInstance <SigningCredentialsStore>();

            //Act
            var result = await target.GetSigningCredentialsAsync();

            //Assert
            result.Key.Should().BeOfType <X509SecurityKey>();
            ((X509SecurityKey)result.Key).Certificate.Should().Be(cert2);
        }
Ejemplo n.º 7
0
        public async Task GetSigningCredentialsAsync_ResultIsCached_ReturnsCachedResult()
        {
            //Arrange
            var cert = CertUtils.GenerateTestCert();
            var alg  = SecurityAlgorithms.RsaSha256;
            var activeSigningCredentials = new SigningCredentials(new X509SecurityKey(cert), alg);
            IEnumerable <SecurityKeyInfo> enabledValidationKeys = new[]
            {
                new SecurityKeyInfo
                {
                    Key = new X509SecurityKey(cert),
                    SigningAlgorithm = SecurityAlgorithms.RsaSha256
                }
            };
            object cachedResult = (activeSigningCredentials, enabledValidationKeys);

            var automocker = new AutoMocker();

            automocker
            .Setup <IMemoryCache, bool>(x => x.TryGetValue("IsOAuthCerts", out cachedResult))
            .Returns(true);

            var target = automocker.CreateInstance <SigningCredentialsStore>();

            //Act
            var result = await target.GetSigningCredentialsAsync();

            //Assert
            result.Should().Be(activeSigningCredentials);
        }
        public static KubernetesClientConfiguration InClusterConfig()
        {
            if (!IsInCluster())
            {
                var local = LocalClusterConfig();
                if (local is null)
                {
                    throw new KubeConfigException("unable to load in-cluster configuration token and ca.crt must exists, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined");
                }

                return(local);
            }

            var token      = File.ReadAllText(Path.Combine(ServiceAccountPath, ServiceAccountTokenKeyFileName));
            var rootCAFile = Path.Combine(ServiceAccountPath, ServiceAccountRootCAKeyFileName);

            var host = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_HOST");
            var port = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_PORT");

            return(new KubernetesClientConfiguration
            {
                Host = new UriBuilder("https", host, Convert.ToInt32(port)).ToString(),
                AccessToken = token,
                SslCaCerts = CertUtils.LoadPemFileCert(rootCAFile)
            });
        }
Ejemplo n.º 9
0
        private void GetPointer(String ThePath)
        {
            if (checkBox1.Checked == true)
            {
                byte[] TheCert = CertUtils.GetCert(ThePath, true);
                string SavFile = "";
                saveFileDialog1.ShowDialog();
                SavFile = saveFileDialog1.FileName;

                FileStream fs2 = new FileStream(SavFile, FileMode.Create);
                fs2.Write(TheCert, 0, TheCert.Length);
                fs2.Flush();
                fs2.Close();
            }
            else
            {
                byte[] TheCert = CertUtils.GetCert(ThePath, false);
                string SavFile = "";
                saveFileDialog1.ShowDialog();
                SavFile = saveFileDialog1.FileName;

                FileStream fs2 = new FileStream(SavFile, FileMode.Create);
                fs2.Write(TheCert, 0, TheCert.Length);
                fs2.Flush();
                fs2.Close();
            }
        }
Ejemplo n.º 10
0
        protected void SetProvisioningConfiguration(WindowsProvisioningConfigurationSet provisioningConfiguration)
        {
            provisioningConfiguration.AdminUsername             = AdminUsername;
            provisioningConfiguration.AdminPassword             = Password;
            provisioningConfiguration.ResetPasswordOnFirstLogon = ResetPasswordOnFirstLogon.IsPresent;
            provisioningConfiguration.StoredCertificateSettings = CertUtils.GetCertificateSettings(Certificates, X509Certificates);
            provisioningConfiguration.EnableAutomaticUpdates    = !DisableAutomaticUpdates.IsPresent;

            if (!string.IsNullOrEmpty(TimeZone))
            {
                provisioningConfiguration.TimeZone = TimeZone;
            }

            if (ParameterSetName == "WindowsDomain")
            {
                provisioningConfiguration.DomainJoin = new WindowsProvisioningConfigurationSet.DomainJoinSettings
                {
                    Credentials = new WindowsProvisioningConfigurationSet.DomainJoinCredentials
                    {
                        Username = DomainUserName,
                        Password = DomainPassword,
                        Domain   = Domain
                    },
                    MachineObjectOU = MachineObjectOU,
                    JoinDomain      = JoinDomain
                };
            }
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> Api()
        {
            await LoadCommonValue4ViewAsync("Sample Api");

            var IdToken = "";

            try
            {
                //AccessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
                IdToken = await _httpContextAccessor.HttpContext.GetTokenAsync("id_token");
            }
            catch (Exception) { }

            var vm = new ApiViewModel
            {
                IdToken              = IdToken,
                ApiUri               = GetConfig("Dummy1RAPI"),
                ApiRequestHeader     = "",
                ApiRequestRespose    = "",
                AuthenticatedSubject = "",
            };

            try
            {
                var jwtToken = new JwtSecurityToken(IdToken);
                if (jwtToken == null && jwtToken.Claims == null)
                {
                    vm.VerifyMessage = "Verify error: jwt is not found data";
                    return(View(vm));
                }

                var rstMessage = "";
                vm.VerifyMessage = rstMessage;

                string certificateFilePath   = GetConfig("ClientCert:Path");
                string certificatePassphrase = GetConfig("ClientCert:Passphrase");


                X509Certificate2 cert = new CertUtils(string.Empty)
                                        .LoadCertPfx(certificateFilePath, certificatePassphrase);

                vm.ApiRequestHeader = JsonFormatPretty(new { id_token = IdToken });
                rstMessage          = Call1RDummyAPI(IdToken, cert);

                vm.VerifyMessage = rstMessage;
                var resultObj = Convert2Object <OneRecordDummyResponse>(rstMessage);

                vm.VerifyResult         = resultObj?.message == Constances.VERIFY_OK;
                vm.ApiRequestRespose    = JsonFormatPrettyStr(rstMessage);
                vm.AuthenticatedSubject = GetAuthenSubject(rstMessage);
                vm.ResultData           = GetDataResult(rstMessage);
            }
            catch (Exception ex)
            {
                vm.VerifyResult  = false;
                vm.VerifyMessage = ex.Message;
            }

            return(View(vm));
        }
Ejemplo n.º 12
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                if (!Directory.Exists(TargetLocation))
                {
                    throw new ArgumentException(Resources.VaultCredPathException);
                }

                string subscriptionId = DefaultContext.Subscription.Id.ToString();
                string resourceType   = "BackupVault";
                string displayName    = subscriptionId + "_" + Vault.ResourceGroupName + "_" + Vault.Name;

                WriteDebug(string.Format(CultureInfo.InvariantCulture,
                                         Resources.ExecutingGetVaultCredCmdlet,
                                         subscriptionId, Vault.ResourceGroupName, Vault.Name, TargetLocation));

                X509Certificate2 cert = CertUtils.CreateSelfSignedCert(CertUtils.DefaultIssuer,
                                                                       CertUtils.GenerateCertFriendlyName(subscriptionId, Vault.Name),
                                                                       CertUtils.DefaultPassword,
                                                                       DateTime.UtcNow.AddMinutes(-10),
                                                                       DateTime.UtcNow.AddHours(this.GetCertificateExpiryInHours()));

                AcsNamespace acsNamespace  = new AcsNamespace();
                string channelIntegrityKey = string.Empty;
                try
                {
                    // Upload cert into ID Mgmt
                    WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadingCertToIdmgmt));
                    acsNamespace = UploadCert(cert, subscriptionId, Vault.Name, resourceType, Vault.ResourceGroupName);
                    WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadedCertToIdmgmt));
                }
                catch (Exception exception)
                {
                    throw exception;
                }

                // generate vault credentials
                string vaultCredsFileContent = GenerateVaultCreds(cert, subscriptionId, resourceType, acsNamespace);

                // NOTE: One of the scenarios for this cmdlet is to generate a file which will be an input to DPM servers.
                //       We found a bug in the DPM UI which is looking for a particular namespace in the input file.
                //       The below is a hack to circumvent this issue and this would be removed once the bug can be fixed.
                vaultCredsFileContent = vaultCredsFileContent.Replace("Microsoft.Azure.Commands.AzureBackup.Models",
                                                                      "Microsoft.Azure.Portal.RecoveryServices.Models.Common");

                // prepare for download
                string fileName = string.Format("{0}_{1}.VaultCredentials", displayName, DateTime.UtcNow.ToString("yyyy-dd-M--HH-mm-ss"));
                string filePath = Path.Combine(TargetLocation, fileName);
                WriteDebug(string.Format(Resources.SavingVaultCred, filePath));

                File.WriteAllBytes(filePath, Encoding.UTF8.GetBytes(vaultCredsFileContent));

                // Output filename back to user
                WriteObject(fileName);
            });
        }
Ejemplo n.º 13
0
        public void IsSelfSignedTest()
        {
            BCX509.X509Certificate bcCert = CertUtils.ToBouncyCastleObject(_rootCA);
            Assert.IsTrue(CertUtils.IsSelfSigned(bcCert));

            bcCert = CertUtils.ToBouncyCastleObject(_subCA);
            Assert.IsFalse(CertUtils.IsSelfSigned(bcCert));
        }
        public void ContextEllipticKey(string context)
        {
            var fi  = new FileInfo("assets/kubeconfig.yml");
            var cfg = KubernetesClientConfiguration.BuildConfigFromConfigFile(fi, context, useRelativePaths: false);
            var pfx = CertUtils.GeneratePfx(cfg);

            Assert.NotNull(pfx);
        }
Ejemplo n.º 15
0
        public void LoadFromInlineDataRelativePath()
        {
            var cfg = KubernetesClientConfiguration.BuildConfigFromConfigFile(kubeConfigWithRelativePathsFileName, "victorian-context");

            // Just validate that this doesn't throw and private key is non-null
            var cert = CertUtils.GeneratePfx(cfg);

            Assert.NotNull(cert.PrivateKey);
        }
Ejemplo n.º 16
0
        public void LoadFromFiles()
        {
            var cfg = KubernetesClientConfiguration.BuildConfigFromConfigFile(kubeConfigFileName, "federal-context", useRelativePaths: false);

            // Just validate that this doesn't throw and private key is non-null
            var cert = CertUtils.GeneratePfx(cfg);

            Assert.NotNull(cert.PrivateKey);
        }
Ejemplo n.º 17
0
        public void BuildCertPathTest()
        {
            List <byte[]> otherCerts = null;
            ICollection <BCX509.X509Certificate> certPath = null;

            // Self-signed signing certificate
            certPath = CertUtils.BuildCertPath(_derCert, otherCerts);
            Assert.IsTrue(certPath.Count == 1);
            Assert.IsTrue(Convert.ToBase64String(GetCertAt(certPath, 0).GetEncoded()) == Convert.ToBase64String(_derCert));

            // Path cannot be built when signing certificate is not self-signed and no additional certs are provided
            try
            {
                certPath = CertUtils.BuildCertPath(_endEntity, otherCerts);
                Assert.Fail("Exception expected but not thrown");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is Org.BouncyCastle.Pkix.PkixCertPathBuilderException);
            }

            // Fails when additional certs are provided and the path cannot be build because root CA is missing
            try
            {
                otherCerts = new List <byte[]>();
                otherCerts.Add(_subCA);
                certPath = CertUtils.BuildCertPath(_endEntity, otherCerts);
                Assert.Fail("Exception expected but not thrown");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is Org.BouncyCastle.Pkix.PkixCertPathBuilderException);
            }

            // Fails when additional certs are provided and the path cannot be build because intermediate CA is missing
            try
            {
                otherCerts = new List <byte[]>();
                otherCerts.Add(_rootCA);
                certPath = CertUtils.BuildCertPath(_endEntity, otherCerts);
                Assert.Fail("Exception expected but not thrown");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is Org.BouncyCastle.Pkix.PkixCertPathBuilderException);
            }

            // Returns full chain when the path can be built
            otherCerts = new List <byte[]>();
            otherCerts.Add(_rootCA);
            otherCerts.Add(_subCA);
            certPath = CertUtils.BuildCertPath(_endEntity, otherCerts);
            Assert.IsTrue(certPath.Count == 3);
            Assert.IsTrue(Convert.ToBase64String(GetCertAt(certPath, 0).GetEncoded()) == Convert.ToBase64String(_endEntity));
            Assert.IsTrue(Convert.ToBase64String(GetCertAt(certPath, 1).GetEncoded()) == Convert.ToBase64String(_subCA));
            Assert.IsTrue(Convert.ToBase64String(GetCertAt(certPath, 2).GetEncoded()) == Convert.ToBase64String(_rootCA));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Helper to make issuer match System.Security conventions
        /// </summary>
        /// <param name="issuerDN"></param>
        /// <returns></returns>
        private static string FixUpIssuer(string issuerDN)
        {
            // replace state ST= with S=
            issuerDN = issuerDN.Replace("ST=", "S=");
            // reverse DN order
            var issuerList = CertUtils.ParseDistinguishedName(issuerDN);

            issuerList.Reverse();
            return(string.Join(", ", issuerList));
        }
Ejemplo n.º 19
0
        public void InvalidBundleCert()
        {
            var caCert   = CertUtils.LoadPemFileCert("assets/ca-bundle.crt");
            var testCert = new X509Certificate2("assets/ca2.crt");
            var chain    = new X509Chain();
            var errors   = SslPolicyErrors.RemoteCertificateChainErrors;

            var result = Kubernetes.CertificateValidationCallBack(this, caCert, testCert, chain, errors);

            Assert.False(result);
        }
Ejemplo n.º 20
0
        private void signPDF(int llx, int lly, int urx, int ury)
        {
            // Do something interesting with unsigned PDF document
            FileInfo unsignedPdfInfo = new FileInfo(unsignedPdfPath);
            //Assert.IsTrue(unsignedPdfInfo.Length > 0);
            // Specify path to the unmanaged PCKS#11 library
            string libraryPath = @"C:\Windows\System32\cvP11.dll";
            // Specify serial number of the token that contains signing key. May be null if tokenLabel is specified.
            string tokenSerial = @"910e21b0da172e34";
            // Specify label of of the token that contains signing key. May be null if tokenSerial is specified
            string tokenLabel = @"SuisseID";
            // Specify PIN for the token
            string pin = "091011";
            // Specify label (value of CKA_LABEL attribute) of the private key used for signing. May be null if ckaId is specified.
            string ckaLabel = null;
            // Specify hex encoded string with identifier (value of CKA_ID attribute) of the private key used for signing. May be null if ckaLabel is specified.

            string ckaId = "6D808CE0BF9C368FB0AD28E24366F646BA0B3F67";
            // Specify hash algorihtm used for the signature creation
            HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256;

            // Create instance of Pkcs11Signature class that allows iText to create PKCS#1 v1.5 RSA signature with the private key stored on PKCS#11 compatible device
            using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(libraryPath, tokenSerial, tokenLabel, pin, ckaLabel, ckaId, HashAlgorithm.SHA256))
            {
                // When signing certificate is stored on the token it can be usually read with GetSigningCertificate() method
                byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate();
                // All certificates stored on the token can be usually read with GetAllCertificates() method
                List <byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates();
                // Build certification path for the signing certificate
                ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates);
                // Read unsigned PDF document
                using (PdfReader pdfReader = new PdfReader(unsignedPdfPath))
                {
                    // Create output stream for signed PDF document
                    using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create))
                    {
                        // Create PdfStamper that applies extra content to the PDF document
                        using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', Path.GetTempFileName(), true))
                        {
                            // Sign PDF document
                            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
                            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
                            signatureAppearance.SignatureGraphic       = iTextSharp.text.Image.GetInstance("logo_sign.png");
                            signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle((float)llx, (float)lly, (float)urx, (float)ury), 1, null);
                            MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES);
                            //MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES);
                        }
                    }
                }
            }
            // Do something interesting with the signed PDF document
            FileInfo signedPdfInfo = new FileInfo(signedPdfPath);
            //Assert.IsTrue(signedPdfInfo.Length > signedPdfPath.Length);
        }
Ejemplo n.º 21
0
        public void LoadPemWithMultiCert()
        {
            var certCollection = CertUtils.LoadPemFileCert("assets/ca-bundle.crt");

            var intermediateCert = new X509Certificate2("assets/ca-bundle-intermediate.crt");
            var rootCert         = new X509Certificate2("assets/ca-bundle-root.crt");

            Assert.Equal(2, certCollection.Count);

            Assert.True(certCollection[0].RawData.SequenceEqual(intermediateCert.RawData));
            Assert.True(certCollection[1].RawData.SequenceEqual(rootCert.RawData));
        }
Ejemplo n.º 22
0
        public void ConvertToBouncyCastleObjectTest()
        {
            X509Certificate2 dotNetCert = null;

            BCX509.X509Certificate bcCert = null;

            // From ByteArray
            try
            {
                bcCert = CertUtils.ToBouncyCastleObject((byte[])null);
                Assert.Fail("Exception expected but not thrown");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is ArgumentNullException);
            }

            bcCert = CertUtils.ToBouncyCastleObject(_derCert);
            Assert.IsTrue(bcCert != null);

            bcCert = CertUtils.ToBouncyCastleObject(_pemCert);
            Assert.IsTrue(bcCert != null);

            try
            {
                bcCert = CertUtils.ToBouncyCastleObject(_noCert);
                Assert.IsTrue(bcCert == null);
                Assert.Fail("Exception expected but not thrown");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is CryptographicException);
            }

            // From DotNetObject
            try
            {
                bcCert = CertUtils.ToBouncyCastleObject((X509Certificate2)null);
                Assert.Fail("Exception expected but not thrown");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is ArgumentNullException);
            }

            dotNetCert = CertUtils.ToDotNetObject(_derCert);
            bcCert     = CertUtils.ToBouncyCastleObject(dotNetCert);
            Assert.IsTrue(bcCert != null);

            dotNetCert = CertUtils.ToDotNetObject(_pemCert);
            bcCert     = CertUtils.ToBouncyCastleObject(dotNetCert);
            Assert.IsTrue(bcCert != null);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Sets the parameters to suitable defaults.
 /// </summary>
 public static X500DistinguishedName Create(string subjectName)
 {
     // parse the subject name if specified.
     if (!string.IsNullOrEmpty(subjectName))
     {
         var subjectNameEntries = CertUtils.ParseDistinguishedName(subjectName)
                                  .Select(e => e.Contains("=") ? e : "CN=" + e);
         // enforce proper formatting for the subject name string
         subjectName = string.Join(", ", subjectNameEntries);
     }
     return(new X500DistinguishedName(subjectName));
 }
Ejemplo n.º 24
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                CertUtils.SignFile(textBox1.Text, textBox2.Text, true);
            }
            else
            {
                CertUtils.SignFile(textBox1.Text, textBox2.Text, false);
            }

            MessageBox.Show("done");
        }
Ejemplo n.º 25
0
        public void ValidBundleCert()
        {
            var caCert = CertUtils.LoadPemFileCert("assets/ca-bundle.crt");

            // Load the intermediate cert
            //
            var testCert = caCert[0];
            var chain    = new X509Chain();
            var errors   = SslPolicyErrors.RemoteCertificateChainErrors;

            var result = Kubernetes.CertificateValidationCallBack(this, caCert, testCert, chain, errors);

            Assert.True(result);
        }
Ejemplo n.º 26
0
        private byte[] GetCertificateData()
        {
            if (((CertToDeploy is PSObject) && ((PSObject)CertToDeploy).ImmediateBaseObject is X509Certificate2) ||
                (CertToDeploy is X509Certificate2))
            {
                var cert = ((PSObject)CertToDeploy).ImmediateBaseObject as X509Certificate2;

                return(CertUtils.GetCertificateData(cert));
            }
            else
            {
                var certPath = this.ResolvePath(CertToDeploy.ToString());
                return(CertUtils.GetCertificateData(certPath, Password));
            }
        }
Ejemplo n.º 27
0
        public void ConvertToDerEncodedByteArray()
        {
            byte[]           derCert    = null;
            X509Certificate2 dotNetCert = null;

            BCX509.X509Certificate bcCert = null;

            // From BouncyCastleObject
            try
            {
                derCert = CertUtils.ToDerEncodedByteArray((BCX509.X509Certificate)null);
                Assert.Fail("Exception expected but not thrown");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is ArgumentNullException);
            }

            bcCert  = CertUtils.ToBouncyCastleObject(_derCert);
            derCert = CertUtils.ToDerEncodedByteArray(bcCert);
            Assert.IsTrue(Convert.ToBase64String(derCert) == Convert.ToBase64String(_derCert));

            bcCert  = CertUtils.ToBouncyCastleObject(_pemCert);
            derCert = CertUtils.ToDerEncodedByteArray(bcCert);
            Assert.IsTrue(Convert.ToBase64String(derCert) == Convert.ToBase64String(_derCert));

            // From DotNetObject
            try
            {
                derCert = CertUtils.ToDerEncodedByteArray((X509Certificate2)null);
                Assert.Fail("Exception expected but not thrown");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is ArgumentNullException);
            }

            dotNetCert = CertUtils.ToDotNetObject(_derCert);
            derCert    = CertUtils.ToDerEncodedByteArray(dotNetCert);
            Assert.IsTrue(Convert.ToBase64String(derCert) == Convert.ToBase64String(_derCert));

            dotNetCert = CertUtils.ToDotNetObject(_pemCert);
            derCert    = CertUtils.ToDerEncodedByteArray(dotNetCert);
            Assert.IsTrue(Convert.ToBase64String(derCert) == Convert.ToBase64String(_derCert));
        }
Ejemplo n.º 28
0
        public async Task GetSigningCredentialsAsync_ResultNotCachedConfigSigningOnly_ReturnsBasedOnCertLocator()
        {
            //Arrange
            var    cert         = CertUtils.GenerateTestCert();
            object cachedResult = null;

            var automocker = new AutoMocker();

            automocker
            .Setup <IMemoryCache, bool>(x => x.TryGetValue("IsOAuthCerts", out cachedResult))
            .Returns(false);

            automocker
            .Setup <IMemoryCache, ICacheEntry>(x => x.CreateEntry("IsOAuthCerts"))
            .Returns(Mock.Of <ICacheEntry>());

            automocker
            .Setup <IOptions <SigningCredentialsStore.Config>, SigningCredentialsStore.Config>(x => x.Value)
            .Returns(new SigningCredentialsStore.Config
            {
                Signing = "cert-id"
            });

            automocker
            .Setup <ICertificateLocator, Task <ICollection <CertificateVersion> > >(x =>
                                                                                    x.GetAllEnabledCertificateVersionsAsync("cert-id"))
            .ReturnsAsync(new[]
            {
                new CertificateVersion
                {
                    Certificate = cert,
                    Timestamp   = DateTime.Now
                }
            });

            var target = automocker.CreateInstance <SigningCredentialsStore>();

            //Act
            var result = await target.GetSigningCredentialsAsync();

            //Assert
            result.Key.Should().BeOfType <X509SecurityKey>();
            ((X509SecurityKey)result.Key).Certificate.Should().Be(cert);
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                                  .AddCertificateManager()
                                  .AddTransient <CreateCertificatesClientServerAuthRsa>()
                                  .BuildServiceProvider();

            var createClientServerAuthCerts = serviceProvider.GetService <CreateCertificatesClientServerAuthRsa>();
            var iec = serviceProvider.GetService <ImportExportCertificate>();

            var fileName = CertUtils.CertPath("dpsIntermediate1Rsa.pfx");

            Console.WriteLine($"Importing {fileName}");
            var intermediate = new X509Certificate2(fileName, "1234");

            Console.WriteLine($"Imported  {fileName}");
            intermediate.PrintCert();

            var device = createClientServerAuthCerts.NewDeviceChainedCertificate(
                new DistinguishedName {
                CommonName = "testdevice01"
            },
                new ValidityPeriod {
                ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10)
            },
                "testdevice01", intermediate);
            //device.FriendlyName = "IoT device testdevice01";

            string password = "******";
            var    importExportCertificate = serviceProvider.GetService <ImportExportCertificate>();

            var deviceInPfxBytes = importExportCertificate.ExportChainedCertificatePfx(password, device, intermediate);

            fileName = CertUtils.CertPath("testdevice01Rsa.pfx");
            File.WriteAllBytes(fileName, deviceInPfxBytes);
            Console.WriteLine($"Exported {fileName}");

            var devicePEM = iec.PemExportPublicKeyCertificate(device);

            fileName = CertUtils.CertPath("testdevice01Rsa.pem");
            File.WriteAllText(fileName, devicePEM);
            Console.WriteLine($"Exported {fileName}");
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Generates vault creds file content for backup Vault
        /// </summary>
        /// <param name="cert">management certificate</param>
        /// <param name="subscriptionId">subscription Id</param>
        /// <param name="resourceType">resource type</param>
        /// <param name="displayName">display name</param>
        /// <param name="acsNamespace">acs namespace</param>
        /// <returns>xml file in string format</returns>
        private string GenerateVaultCredsForBackup(X509Certificate2 cert, string subscriptionId, string resourceType, AcsNamespace acsNamespace)
        {
            using (var output = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(output, GetXmlWriterSettings()))
                {
                    BackupVaultCreds backupVaultCreds = new BackupVaultCreds(subscriptionId,
                                                                             resourceType,
                                                                             Vault.Name,
                                                                             CertUtils.SerializeCert(cert, X509ContentType.Pfx),
                                                                             acsNamespace,
                                                                             GetAgentLinks());
                    DataContractSerializer serializer = new DataContractSerializer(typeof(BackupVaultCreds));
                    serializer.WriteObject(writer, backupVaultCreds);

                    WriteDebug(string.Format(CultureInfo.InvariantCulture, "RecoveryService - Backup Vault - Successfully serialized the file content"));
                }

                return(Encoding.UTF8.GetString(output.ToArray()));
            }
        }