Esempio n. 1
0
        public X509Certificate2 NewRsaSelfSignedCertificate(
            DistinguishedName distinguishedName,
            BasicConstraints basicConstraints,
            ValidityPeriod validityPeriod,
            SubjectAlternativeName subjectAlternativeName,
            OidCollection enhancedKeyUsages,
            X509KeyUsageFlags x509KeyUsageFlags,
            RsaConfiguration rsaConfiguration)
        {
            using var rsa = RSA.Create(rsaConfiguration.KeySize); // 1024, 2048 or 4096
            var request = new CertificateRequest(
                _certificateUtility.CreateIssuerOrSubject(distinguishedName),
                rsa,
                rsaConfiguration.HashAlgorithmName,
                rsaConfiguration.RSASignaturePadding);

            X509Certificate2 generatedCertificate = SelfSignedConfiguration(
                basicConstraints,
                validityPeriod,
                subjectAlternativeName,
                enhancedKeyUsages,
                x509KeyUsageFlags,
                request);

            return(generatedCertificate);
        }
        /// <summary>
        /// Create an device chained certificate for Client and Server TLS Auth using RSA algorithm
        ///
        /// The device certificate (also called a leaf certificate) must have the Subject Name set to the Device ID that was used when registering the IoT device in the Azure IoT Hub. This setting is required for authentication.
        /// </summary>
        /// <param name="distinguishedName">Distinguished Name used for the subject and the issuer properties</param>
        /// <param name="validityPeriod">Valid from, Valid to certificate properties</param>
        /// <param name="dnsName">Dns name use the certificate validation</param>
        /// <param name="parentCertificateAuthority"> Parent cert to create the chain from</param>
        /// <returns>X509Certificate2 device chained certificate</returns>
        public X509Certificate2 NewRsaDeviceChainedCertificate(
            DistinguishedName distinguishedName,
            ValidityPeriod validityPeriod,
            string dnsName,
            X509Certificate2 parentCertificateAuthority,
            RsaConfiguration rsaConfiguration = null)
        {
            var enhancedKeyUsages = new OidCollection {
                OidLookup.ClientAuthentication,
                OidLookup.ServerAuthentication
            };

            return(NewRsaDeviceChainedCertificate(distinguishedName,
                                                  validityPeriod, dnsName, enhancedKeyUsages, parentCertificateAuthority,
                                                  rsaConfiguration));
        }
        private X509Certificate2 NewRsaDeviceChainedCertificate(
            DistinguishedName distinguishedName,
            ValidityPeriod validityPeriod,
            string dnsName,
            OidCollection enhancedKeyUsages,
            X509Certificate2 parentCertificateAuthority,
            RsaConfiguration rsaConfiguration = null)
        {
            var basicConstraints = new BasicConstraints
            {
                CertificateAuthority    = false,
                HasPathLengthConstraint = false,
                PathLengthConstraint    = 0,
                Critical = true
            };

            var subjectAlternativeName = new SubjectAlternativeName
            {
                DnsName = new List <string>
                {
                    dnsName,
                }
            };

            var x509KeyUsageFlags =
                X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment;

            var deviceCert = _createCertificates.NewRsaChainedCertificate(
                distinguishedName,
                basicConstraints,
                validityPeriod,
                subjectAlternativeName,
                parentCertificateAuthority,
                enhancedKeyUsages,
                x509KeyUsageFlags,
                rsaConfiguration ?? new RsaConfiguration());

            return(deviceCert);
        }
Esempio n. 4
0
        public X509Certificate2 NewRsaChainedCertificate(
            DistinguishedName distinguishedName,
            BasicConstraints basicConstraints,
            ValidityPeriod validityPeriod,
            SubjectAlternativeName subjectAlternativeName,
            X509Certificate2 signingCertificate,
            OidCollection enhancedKeyUsages,
            X509KeyUsageFlags x509KeyUsageFlags,
            RsaConfiguration rsaConfiguration)
        {
            if (signingCertificate == null)
            {
                throw new ArgumentNullException(nameof(signingCertificate));
            }
            if (!signingCertificate.HasPrivateKey)
            {
                throw new Exception("Signing cert must have private key");
            }

            using var rsa = RSA.Create(rsaConfiguration.KeySize);
            var request = new CertificateRequest(
                _certificateUtility.CreateIssuerOrSubject(distinguishedName),
                rsa,
                rsaConfiguration.HashAlgorithmName,
                rsaConfiguration.RSASignaturePadding);

            X509Certificate2 cert = ChainedConfiguration(
                basicConstraints,
                validityPeriod,
                subjectAlternativeName,
                signingCertificate,
                enhancedKeyUsages,
                x509KeyUsageFlags,
                request);

            return(cert.CopyWithPrivateKey(rsa));
        }
        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                                  .AddCertificateManager()
                                  .BuildServiceProvider();

            var createCertificates = serviceProvider.GetService <CreateCertificates>();
            var certificateUtility = serviceProvider.GetService <CertificateUtility>();

            string password = "******";

            var signingCertificate = new X509Certificate2("root.cert.pfx", password);
            var enhancedKeyUsages  = new OidCollection {
                OidLookup.ClientAuthentication,
                OidLookup.ServerAuthentication
            };

            var basicConstraints = new CertificateManager.Models.BasicConstraints
            {
                CertificateAuthority    = false,
                HasPathLengthConstraint = true,
                PathLengthConstraint    = 3,
                Critical = true
            };

            var x509KeyUsageFlags = X509KeyUsageFlags.DigitalSignature
                                    | X509KeyUsageFlags.KeyEncipherment
                                    | X509KeyUsageFlags.NonRepudiation;

            // Read in CSR data from a file
            Pkcs10CertificationRequest decodedCsr = (Pkcs10CertificationRequest) new PemReader(new StringReader(File.ReadAllText(args[0]))).ReadObject();
            // Get Common Name (CN) from CSR Subject
            CertificationRequestInfo csrData = decodedCsr.GetCertificationRequestInfo();
            var subjectKeyPairs = csrData.Subject.ToString().Split(',')
                                  .Select(x => x.Split('='))
                                  .Where(x => x.Length == 2)
                                  .ToDictionary(x => x.First(), x => x.Last());
            var commonName             = subjectKeyPairs["CN"];
            var subjectAlternativeName = new SubjectAlternativeName
            {
                DnsName = new List <string>
                {
                    commonName,
                }
            };
            // Get Public key data from CSR and create RSA data based on that
            RsaKeyParameters rsaKeyParams = (RsaKeyParameters)decodedCsr.GetPublicKey();
            var rsaParams = new RSAParameters();

            rsaParams.Modulus  = rsaKeyParams.Modulus.ToByteArray();
            rsaParams.Exponent = rsaKeyParams.Exponent.ToByteArray();
            var rsa = RSA.Create();

            rsa.ImportParameters(rsaParams);

            // Create Certificate Request with the data extracted from csr file earlier
            var rsaConfiguration = new RsaConfiguration();
            var request          = new CertificateRequest(
                certificateUtility.CreateIssuerOrSubject(new DistinguishedName {
                CommonName = commonName
            }),
                rsa,
                rsaConfiguration.HashAlgorithmName,
                rsaConfiguration.RSASignaturePadding);

            // Sign the csr
            var device1Certificate = createCertificates.NewRsaChainedCertificate(
                basicConstraints,
                new ValidityPeriod {
                ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(1)
            },
                subjectAlternativeName,
                signingCertificate,
                enhancedKeyUsages,
                x509KeyUsageFlags,
                request,
                null);

            // Export content of certificates into files
            var importExportCertificate = serviceProvider.GetService <ImportExportCertificate>();
            var deviceCertificatePem    = importExportCertificate.PemExportPublicKeyCertificate(device1Certificate);
            var signingCertificatePem   = importExportCertificate.PemExportPublicKeyCertificate(signingCertificate);

            File.WriteAllText("device1.cert.pem", deviceCertificatePem);
            File.WriteAllText("device1-full-chain.cert.pem", String.Concat(deviceCertificatePem, signingCertificatePem));

            Console.WriteLine("Certificates exported to pem files");
        }