Exemplo n.º 1
0
        public static X509Certificate2 CreateSelfSignedCert(string subjectName, string issuerName, AsymmetricKeyParameter privateKey)
        {
            const int keyStrength = 2048;

            if (privateKey == null)
            {
                privateKey = CreatePrivateKeyResource(issuerName);
            }
            var issuerPrivKey = privateKey;

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivKey, random);
            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.DnsName, "localhost"), new GeneralName(GeneralName.DnsName, "127.0.0.1") }));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>()
            {
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
            }));

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(70);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // self sign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // corresponding private key
            var info = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new X509Certificate2(certificate.GetEncoded());

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new Org.BouncyCastle.OpenSsl.PemException("malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq); //new RsaPrivateKeyStructure(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

#if NETCOREAPP
            x509 = x509.CopyWithPrivateKey(ToRSA(rsaparams));
#else
            //x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            x509.PrivateKey = ToRSA(rsaparams);
#endif

            return(x509);
        }
Exemplo n.º 2
0
        public string CreateAndStoreNewCertificate(string subjectName, string pvkPass, X509Certificate2 issuer,
                                                   string path = @".\certs\")
        {
            var generator = new X509V3CertificateGenerator();

            // Generate pseudo random number
            var randomGen = new CryptoApiRandomGenerator();
            var random    = new SecureRandom(randomGen);

            // Set certificate serial number
            var serialNumber =
                BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            generator.SetSerialNumber(serialNumber);

            // Set certificate subject name
            var subjectDN = new X509Name($"CN={subjectName}");

            generator.SetSubjectDN(subjectDN);

            // Set issuer subject name
            var issuerDN = new X509Name(issuer.Subject);

            generator.SetIssuerDN(issuerDN);

            // Set certificate validity
            var notBefore = DateTime.UtcNow.Date;

            generator.SetNotBefore(notBefore);
            generator.SetNotAfter(notBefore.AddYears(2));

            // Generate new RSA key pair for certificate
            var keyGeneratorParameters = new KeyGenerationParameters(random, RSAKeyStrength);
            var keyPairGenerator       = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGeneratorParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            // Import public key into generator
            generator.SetPublicKey(subjectKeyPair.Public);

            var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey);

            // Get key pair from .net issuer certificate
            //var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey);
            var issuerSerialNumber = new BigInteger(issuer.GetSerialNumber());

            // Id CA key with serial
            var caKeyIdentifier = new AuthorityKeyIdentifier(
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public),
                new GeneralNames(new GeneralName(issuerDN)),
                issuerSerialNumber);

            generator.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                caKeyIdentifier);

            // Create signature factory to sign new cert
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerKeyPair.Private);

            // Generate new bouncy castle certificate signed by issuer
            var newCertificate = generator.Generate(signatureFactory);

            var store        = new Pkcs12Store();
            var friendlyName = newCertificate.SubjectDN.ToString().Split('=')[1];

            var certificateEntry = new X509CertificateEntry(newCertificate);

            // Set certificate
            store.SetCertificateEntry(friendlyName, certificateEntry);
            // Set private key
            store.SetKeyEntry(
                friendlyName,
                new AsymmetricKeyEntry(subjectKeyPair.Private),
                new[] { certificateEntry });

            var privatePath = path + $"{friendlyName}.pfx";
            var publicPath  = path + $"{friendlyName}.cer";

            using (var stream = new MemoryStream())
            {
                // Convert bouncy castle cert => .net cert
                store.Save(stream, pvkPass.ToCharArray(), random);
                var dotNetCertificate = new X509Certificate2(
                    stream.ToArray(),
                    pvkPass,
                    X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                // Extract public part to store in server storage
                var publicCert = dotNetCertificate.Export(X509ContentType.Cert);
                // Extract private parameters to export into .pfx for distribution
                var privateCert = dotNetCertificate.Export(X509ContentType.Pfx, pvkPass);

                dotNetCertificate.Reset();
                dotNetCertificate.Import(publicCert);

                // Store public cert info in storage
                using (var storage = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                {
                    storage.Open(OpenFlags.ReadWrite);
                    storage.Add(dotNetCertificate);
                    storage.Close();
                }

                dotNetCertificate.Dispose();

                // Write private parameters to .pfx file to install at client
                File.WriteAllBytes(privatePath, privateCert);
                File.WriteAllBytes(publicPath, publicCert);
            }

            return(privatePath);
        }
Exemplo n.º 3
0
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            var subjectDN = new X509Name("CN=" + subjectName);
            var issuerDN  = new X509Name("CN=" + issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

            // correcponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            using (var sw = File.CreateText(Path.Combine("D:\\", "PrivateKey")))
            {
                var pw = new PemWriter(sw);
                pw.WriteObject(subjectKeyPair.Private);
            }

            using (var sw = File.CreateText(Path.Combine("D:\\", "PublicKey")))
            {
                var pw = new PemWriter(sw);
                pw.WriteObject(subjectKeyPair.Public);
            }
            string encryptionKey = "*****";

            var a = Encrypt(encryptionKey);

            var pass = "******";
            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded(), pass);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);

            string       text     = System.IO.File.ReadAllText(@"C:\xampp\apache\conf\ssl.crt\server.crt");
            UTF8Encoding encoding = new System.Text.UTF8Encoding();

            byte[]           byteCert = encoding.GetBytes(text);
            X509Certificate2 uberCert = new X509Certificate2();

            uberCert.Import(byteCert);
            Console.WriteLine("Has privateKey:" + uberCert.HasPrivateKey.ToString());
            Console.WriteLine("PrivateKey: \n" + uberCert.PrivateKey);

            addCertToStore(x509, StoreName.Root, StoreLocation.CurrentUser);
            using (x509)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("-----BEGIN CERTIFICATE-----");
                builder.AppendLine(
                    Convert.ToBase64String(x509.RawData, Base64FormattingOptions.InsertLineBreaks));
                builder.AppendLine("-----END CERTIFICATE-----");
                builder.ToString();
            }
            return(x509);
        }
Exemplo n.º 4
0
        /// <summary>
        /// https://stackoverflow.com/questions/22230745/generate-a-self-signed-certificate-on-the-fly
        /// </summary>
        /// <param name="subjectName"></param>
        /// <param name="issuerName"></param>
        /// <param name="issuerPrivKey"></param>
        /// <returns></returns>
        public static X509Certificate2 GenerateSelfSignedCertificate(
            string subjectName,
            string issuerName,
            AsymmetricKeyParameter issuerPrivKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDn = new X509Name(subjectName);
            X509Name issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerPrivKey, random);

            // Corresponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // Merge into X509Certificate2
            X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded(), string.Empty, X509KeyStorageFlags.EphemeralKeySet);

            Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure     rsa       = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = ToDotNetKey(rsaparams); // x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return(x509);
        }
Exemplo n.º 5
0
        public static (CertPrivateKey, BcCertificate) GenerateRsaCACertificate(string subjectName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

#pragma warning disable CS0618 // Type or member is obsolete
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
#pragma warning restore CS0618 // Type or member is obsolete

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
#pragma warning disable CS0618 // Type or member is obsolete
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
#pragma warning restore CS0618 // Type or member is obsolete

            // var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            // // Add CA certificate to Root store
            // addCertToStore(cert, StoreName.Root, StoreLocation.CurrentUser);

            var key = new CertPrivateKey
            {
                KeyPair = issuerKeyPair,
            };

            return(key, certificate);
        }
Exemplo n.º 6
0
        X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);


            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // create key factory
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerPrivKey, random);

            // selfsign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // correcponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = RsaPrivateKeyStructure.GetInstance(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return(x509);
        }
        /// <summary>
        /// Create the RSA certificate as Pfx byte array with a private key.
        /// </summary>
        /// <returns>
        /// Returns the Pfx with certificate and private key.
        /// </returns>
        private byte[] CreatePfxForRSA(string passcode, ISignatureFactory signatureFactory = null)
        {
            // Cases locked out by API flow
            Debug.Assert(m_rsaPublicKey == null, "A public key is not supported for the certificate.");

            if (signatureFactory != null && IssuerCAKeyCert == null)
            {
                throw new NotSupportedException("Need an issuer certificate for a signature generator.");
            }

            if (IssuerCAKeyCert != null &&
                (!IssuerCAKeyCert.HasPrivateKey && signatureFactory == null))
            {
                throw new NotSupportedException("Need an issuer certificate with a private key or a signature generator.");
            }

            using (var cfrg = new CertificateFactoryRandomGenerator())
            {
                // cert generators
                SecureRandom random = new SecureRandom(cfrg);

                CreateDefaults(cfrg);

                X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
                CreateMandatoryFields(cg);

                // create Private/Public Keypair
                AsymmetricKeyParameter subjectPublicKey  = null;
                AsymmetricKeyParameter subjectPrivateKey = null;
                using (var rsa = new RSACryptoServiceProvider(m_keySize == 0 ? X509Defaults.RSAKeySize : m_keySize))
                {
                    subjectPublicKey  = X509Utils.GetPublicKeyParameter(rsa);
                    subjectPrivateKey = X509Utils.GetPrivateKeyParameter(rsa);
                }

                cg.SetPublicKey(subjectPublicKey);
                CreateExtensions(cg, subjectPublicKey);

                // sign certificate
                if (signatureFactory == null)
                {
                    AsymmetricKeyParameter signingKey;
                    if (IssuerCAKeyCert != null)
                    {
                        // signed by issuer
                        signingKey = X509Utils.GetPrivateKeyParameter(IssuerCAKeyCert);
                    }
                    else
                    {
                        // self signed
                        signingKey = subjectPrivateKey;
                    }
                    signatureFactory = new Asn1SignatureFactory(
                        X509Utils.GetRSAHashAlgorithm(HashAlgorithmName), signingKey, random);
                }
                Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

                // note: this Pfx has a private key!
                return(X509Utils.CreatePfxWithPrivateKey(x509, null, subjectPrivateKey, passcode, random));
            }
        }
Exemplo n.º 8
0
    /// <summary>
    /// Creates a self signed application instance certificate.
    /// </summary>
    /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
    /// <param name="storePath">The store path (syntax depends on storeType).</param>
    /// <param name="password">The password to use to protect the certificate.</param>
    /// <param name="applicationUri">The application uri (created if not specified).</param>
    /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
    /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
    /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
    /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
    /// <param name="startTime">The start time.</param>
    /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
    /// <param name="hashSizeInBits">The hash size in bits.</param>
    /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
    /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
    /// <returns>The certificate with a private key.</returns>
    public static X509Certificate2 CreateCertificate(
        string storeType,
        string storePath,
        string password,
        string applicationUri,
        string applicationName,
        string subjectName,
        IList <String> domainNames,
        ushort keySize,
        DateTime startTime,
        ushort lifetimeInMonths,
        ushort hashSizeInBits,
        bool isCA = false,
        X509Certificate2 issuerCAKeyCert = null,
        byte[] publicKey = null)
    {
        if (issuerCAKeyCert != null)
        {
            if (!issuerCAKeyCert.HasPrivateKey)
            {
                throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
            }
        }

        if (publicKey != null && issuerCAKeyCert == null)
        {
            throw new NotSupportedException("Cannot use a public key without a CA certificate with a private key.");
        }

        // set default values.
        X509Name subjectDN = SetSuitableDefaults(
            ref applicationUri,
            ref applicationName,
            ref subjectName,
            ref domainNames,
            ref keySize,
            ref lifetimeInMonths);

        using (var cfrg = new CertificateFactoryRandomGenerator())
        {
            // cert generators
            SecureRandom random           = new SecureRandom(cfrg);
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            cg.SetSerialNumber(serialNumber);

            // subject and issuer DN
            X509Name issuerDN = null;
            if (issuerCAKeyCert != null)
            {
                issuerDN = new CertificateFactoryX509Name(issuerCAKeyCert.Subject);
            }
            else
            {
                // self signed
                issuerDN = subjectDN;
            }
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

            // set Private/Public Key
            AsymmetricKeyParameter subjectPublicKey;
            AsymmetricKeyParameter subjectPrivateKey;
            if (publicKey == null)
            {
                var keyGenerationParameters = new KeyGenerationParameters(random, keySize);
                var keyPairGenerator        = new RsaKeyPairGenerator();
                keyPairGenerator.Init(keyGenerationParameters);
                AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();
                subjectPublicKey  = subjectKeyPair.Public;
                subjectPrivateKey = subjectKeyPair.Private;
            }
            else
            {
                // special case, if a cert is signed by CA, the private key of the cert is not needed
                subjectPublicKey  = PublicKeyFactory.CreateKey(publicKey);
                subjectPrivateKey = null;
            }
            cg.SetPublicKey(subjectPublicKey);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                            new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectPublicKey)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier references the issuer cert or itself when self signed
            AsymmetricKeyParameter issuerPublicKey;
            BigInteger             issuerSerialNumber;
            if (issuerCAKeyCert != null)
            {
                issuerPublicKey    = GetPublicKeyParameter(issuerCAKeyCert);
                issuerSerialNumber = GetSerialNumber(issuerCAKeyCert);
            }
            else
            {
                issuerPublicKey    = subjectPublicKey;
                issuerSerialNumber = serialNumber;
            }

            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                            new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerPublicKey),
                                                       new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                                             KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                }));

                // subject alternate name
                List <GeneralName> generalNames = new List <GeneralName>();
                generalNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri));
                generalNames.AddRange(CreateSubjectAlternateNameDomains(domainNames));
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(generalNames.ToArray()));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            AsymmetricKeyParameter signingKey;
            if (issuerCAKeyCert != null)
            {
                // signed by issuer
                signingKey = GetPrivateKeyParameter(issuerCAKeyCert);
            }
            else
            {
                // self signed
                signingKey = subjectPrivateKey;
            }
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(GetRSAHashAlgorithm(hashSizeInBits), signingKey, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // convert to X509Certificate2
            X509Certificate2 certificate = null;
            if (subjectPrivateKey == null)
            {
                // create the cert without the private key
                certificate = new X509Certificate2(x509.GetEncoded());
            }
            else
            {
                // note: this cert has a private key!
                certificate = CreateCertificateWithPrivateKey(x509, null, subjectPrivateKey, random);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath) && !String.IsNullOrEmpty(storeType))
            {
                using (ICertificateStore store = CertificateStoreIdentifier.CreateStore(storeType))
                {
                    if (store == null)
                    {
                        throw new ArgumentException("Invalid store type");
                    }

                    store.Open(storePath);
                    store.Add(certificate, password).Wait();
                    store.Close();
                }
            }

            return(certificate);
        }
    }
Exemplo n.º 9
0
        /// <summary>
        /// Enroll certificate file base on request
        /// </summary>
        /// <param name="csr"></param>
        /// <param name="rootCert"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        private Org.BouncyCastle.X509.X509Certificate GenerateSignedCertificate(
            Pkcs10CertificationRequest csr,
            Org.BouncyCastle.X509.X509Certificate rootCert,
            AsymmetricCipherKeyPair issuerKeyPair,
            DateTime startDate, DateTime endDate)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            //List<ExtensionsItem> extensions = null;

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(rootCert.SubjectDN);

            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(endDate);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            certGen.SetSubjectDN(info.Subject);

            certGen.SetPublicKey(csr.GetPublicKey());

            var sigAlg  = csr.Signature;
            var sigAlg1 = csr.SignatureAlgorithm;

            certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");


            // Add certificate extensions
            Asn1Set attributes = csr.GetCertificationRequestInfo().Attributes;

            if (attributes != null)
            {
                for (int i = 0; i != attributes.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(attributes[i]);

                    if (attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions1 = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier oid in extensions1.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions1.GetExtension(oid);

                            // !!! NOT working !!!
                            //certGen.AddExtension(oid, ext.IsCritical, ext.Value);

                            //OK
                            certGen.AddExtension(oid, ext.IsCritical, ext.Value, true);
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate issuedCert = null;
            try
            {
                issuedCert = certGen.Generate(issuerKeyPair.Private);
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generate certificate file." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Check if generated certificate file is valid, plase wait ..." + "\n";
                issuedCert.CheckValidity(DateTime.UtcNow);
                tbOutputMessageBox.Text += "Generate certificate file is valid." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Verify generated certificate file, plase wait ..." + "\n";
                issuedCert.Verify(issuerKeyPair.Public);
                tbOutputMessageBox.Text += "Generate certificate file verification is OK." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file verification is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            return(issuedCert);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a cert with the connectionstring (token) and stores it in the given cert store.
        /// </summary>
        public async static Task WriteAsync(string name, string connectionString, string storeType, string storePath)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Token not found in X509Store and no new token provided!");
            }

            SecureRandom random = new SecureRandom();
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair();

            ArrayList nameOids = new ArrayList();
            nameOids.Add(X509Name.CN);
            ArrayList nameValues = new ArrayList();
            nameValues.Add(name);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN = subjectDN;

            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);
            cg.SetNotBefore(DateTime.Now);
            cg.SetNotAfter(DateTime.Now.AddMonths(12));
            cg.SetPublicKey(keys.Public);
            cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment));

            // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and
            // "hide" it in the instruction code cert extension
            RSA rsa = RSA.Create();
            RSAParameters rsaParams = new RSAParameters();
            RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public;

            rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
            keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0);

            rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
            keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0);

            rsa.ImportParameters(rsaParams);
            if (rsa != null)
            {
                byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1);
                if (bytes != null)
                {
                    cg.AddExtension(X509Extensions.InstructionCode, false, bytes);
                }
                else
                {
                    throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!");
                }
            }

            // sign the cert with the private key
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create a PKCS12 store for the cert and its private key
            X509Certificate2 certificate = null;
            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                Pkcs12Store pkcsStore = builder.Build();
                X509CertificateEntry[] chain = new X509CertificateEntry[1];
                string passcode = Guid.NewGuid().ToString();
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // create X509Certificate2 object from PKCS12 file
                certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);

                // handle each store type differently
                switch (storeType)
                {
                    case CertificateStoreType.Directory:
                        {
                            // Add to DirectoryStore
                            using (DirectoryCertificateStore store = new DirectoryCertificateStore())
                            {
                                store.Open(storePath);
                                X509CertificateCollection certificates = await store.Enumerate().ConfigureAwait(false);

                                // remove any existing cert with our name from the store
                                foreach (X509Certificate2 cert in certificates)
                                {
                                    if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        await store.Delete(cert.Thumbprint).ConfigureAwait(false);
                                    }
                                }

                                // add new one
                                await store.Add(certificate).ConfigureAwait(false);
                            }
                            break;
                        }
                    case CertificateStoreType.X509Store:
                        {
                            // Add to X509Store
                            using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser))
                            {
                                store.Open(OpenFlags.ReadWrite);

                                // remove any existing cert with our name from the store
                                foreach (X509Certificate2 cert in store.Certificates)
                                {
                                    if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        store.Remove(cert);
                                    }
                                }

                                // add new cert to store
                                try
                                {
                                    store.Add(certificate);
                                }
                                catch (Exception e)
                                {
                                    throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'.");
                                }
                            }
                            break;
                        }
                    default:
                        {
                            throw new Exception($"The requested store type '{storeType}' is not supported. Please change.");
                        }
                }
                return;
            }
        }
        public static X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, out AsymmetricKeyParameter CaPrivateKey, out AsymmetricKeyParameter CaPublicKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair    = subjectKeyPair;
            ISignatureFactory       signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            var dotNetPrivateKey = ToDotNetKey((RsaPrivateCrtKeyParameters)subjectKeyPair.Private);

            //X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());
            //x509.FriendlyName = subjectName;

            X509Certificate2 x509 = new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));

            //x509.PrivateKey = dotNetPrivateKey; set private key for x509 is not supported for now
            x509.FriendlyName = subjectName;

            CaPrivateKey = issuerKeyPair.Private;
            CaPublicKey  = subjectKeyPair.Public;

            return(x509);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Create a self signed certificate with bouncy castle.
        /// </summary>
        public static X509Certificate2 GenerateCertificate(
            string subjectName,
            Action <X509V3CertificateGenerator> modifyGenerator,
            string signatureAlgorithm = "SHA256WITHRSA",
            int publicKeyLength       = 2048,
            ChainCertificateRequest chainCertificateRequest = null)
        {
            if (string.IsNullOrEmpty(subjectName))
            {
                subjectName = "NuGetTest";
            }

            var random  = new SecureRandom();
            var keyPair = GenerateKeyPair(publicKeyLength);

            // Create cert
            var subjectDN = $"CN={subjectName}";
            var certGen   = new X509V3CertificateGenerator();

            certGen.SetSubjectDN(new X509Name(subjectDN));

            // default to new key pair
            var issuerPrivateKey = keyPair.Private;
            var keyUsage         = KeyUsage.DigitalSignature;
            var issuerDN         = chainCertificateRequest?.IssuerDN ?? subjectDN;

            certGen.SetIssuerDN(new X509Name(issuerDN));

#if IS_DESKTOP
            if (chainCertificateRequest != null)
            {
                if (chainCertificateRequest.Issuer != null)
                {
                    // for a certificate with an issuer assign Authority Key Identifier
                    var issuer   = chainCertificateRequest?.Issuer;
                    var bcIssuer = DotNetUtilities.FromX509Certificate(issuer);
                    var authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(bcIssuer);
                    issuerPrivateKey = DotNetUtilities.GetKeyPair(issuer.PrivateKey).Private;
                    certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier);
                }

                if (chainCertificateRequest.ConfigureCrl)
                {
                    // for a certificate in a chain create CRL distribution point extension
                    var crlServerUri  = $"{chainCertificateRequest.CrlServerBaseUri}{issuerDN}.crl";
                    var generalName   = new Org.BouncyCastle.Asn1.X509.GeneralName(Org.BouncyCastle.Asn1.X509.GeneralName.UniformResourceIdentifier, new DerIA5String(crlServerUri));
                    var distPointName = new DistributionPointName(new GeneralNames(generalName));
                    var distPoint     = new DistributionPoint(distPointName, null, null);

                    certGen.AddExtension(X509Extensions.CrlDistributionPoints, critical: false, extensionValue: new DerSequence(distPoint));
                }

                if (chainCertificateRequest.IsCA)
                {
                    // update key usage with CA cert sign and crl sign attributes
                    keyUsage |= KeyUsage.CrlSign | KeyUsage.KeyCertSign;
                }
            }
#endif
            certGen.SetNotAfter(DateTime.UtcNow.Add(TimeSpan.FromHours(1)));
            certGen.SetNotBefore(DateTime.UtcNow.Subtract(TimeSpan.FromHours(1)));
            certGen.SetPublicKey(keyPair.Public);

            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
            certGen.SetSerialNumber(serialNumber);

            var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public));
            certGen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier);

            certGen.AddExtension(X509Extensions.KeyUsage.Id, false, new KeyUsage(keyUsage));
            certGen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(chainCertificateRequest?.IsCA ?? false));

            // Allow changes
            modifyGenerator?.Invoke(certGen);

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerPrivateKey, random);
            var certificate      = certGen.Generate(signatureFactory);
            var certResult       = new X509Certificate2(certificate.GetEncoded());

#if IS_DESKTOP
            certResult.PrivateKey = DotNetUtilities.ToRSA(keyPair.Private as RsaPrivateCrtKeyParameters);
#endif

            return(certResult);
        }
Exemplo n.º 13
0
        public override X509Certificate2 LoadApplicationCertificate(string thumbprint, string subjectName, string applicationURI, string password)
        {
            try
            {
                // Create a handle based on the hash of the keys
                ushort    slotIndex = ushort.Parse(thumbprint);
                TpmHandle nvHandle  = TpmHandle.NV(slotIndex);
                ushort    offset    = 0;

                // Read the serial number
                byte[] serialNumber = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(long), offset);
                offset += sizeof(long);

                // Read the "valid from" date (today) in FileTime format
                byte[] validFrom = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(long), offset);
                offset += sizeof(long);

                // Read size of keys from NV storage (located in the first 4 bytes)
                byte[] certSizeBlob = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeof(int), offset);
                offset += sizeof(int);

                // Read keys from NV storage in 64-byte chunks
                int    certSize   = BitConverter.ToInt32(certSizeBlob, 0);
                byte[] rawData    = new byte[certSize];
                ushort index      = 0;
                ushort sizeToRead = 0;
                while (index < certSize)
                {
                    if ((certSize - index) < 64)
                    {
                        sizeToRead = (ushort)(certSize - index);
                    }
                    else
                    {
                        sizeToRead = 64;
                    }

                    byte[] dataToRead = m_tpm[m_ownerAuth].NvRead(nvHandle, nvHandle, sizeToRead, offset);
                    offset += sizeToRead;

                    for (int i = 0; i < sizeToRead; i++)
                    {
                        rawData[index + i] = dataToRead[i];
                    }

                    index += sizeToRead;
                }

                // Import
                TextReader textReader        = new StringReader(new string(Encoding.ASCII.GetChars(rawData)));
                PemReader  pemReader         = new PemReader(textReader);
                AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pemReader.ReadObject();

                X509Name   CN            = new X509Name("CN=" + subjectName + ",DC=" + Utils.GetHostName());
                BigInteger SN            = new BigInteger(serialNumber).Abs();
                DateTime   validFromDate = DateTime.FromFileTime(BitConverter.ToInt64(validFrom, 0));

                // Certificate Generator
                X509V3CertificateGenerator cGenerator = new X509V3CertificateGenerator();
                cGenerator.SetSerialNumber(SN);
                cGenerator.SetSubjectDN(CN);
                cGenerator.SetIssuerDN(CN);
                cGenerator.SetNotBefore(validFromDate);
                cGenerator.SetNotAfter(validFromDate.AddYears(1));
                cGenerator.SetPublicKey(keys.Public);
                cGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
                }));
                cGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public), new GeneralNames(new GeneralName(CN)), SN));
                cGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, applicationURI)));

                ISignatureFactory signatureFactory         = new Asn1SignatureFactory("SHA1withRSA", keys.Private, new SecureRandom());
                Org.BouncyCastle.X509.X509Certificate cert = cGenerator.Generate(signatureFactory);
                X509Certificate2 certificate = new X509Certificate2(cert.GetEncoded());

                RSACng rsa = new RSACng();
                RsaPrivateCrtKeyParameters keyParams = (RsaPrivateCrtKeyParameters)keys.Private;

                m_RSAParams = new RSAParameters();

                m_RSAParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
                keyParams.Modulus.ToByteArrayUnsigned().CopyTo(m_RSAParams.Modulus, 0);

                m_RSAParams.P = new byte[keyParams.P.ToByteArrayUnsigned().Length];
                keyParams.P.ToByteArrayUnsigned().CopyTo(m_RSAParams.P, 0);

                m_RSAParams.Q = new byte[keyParams.Q.ToByteArrayUnsigned().Length];
                keyParams.Q.ToByteArrayUnsigned().CopyTo(m_RSAParams.Q, 0);

                m_RSAParams.DP = new byte[keyParams.DP.ToByteArrayUnsigned().Length];
                keyParams.DP.ToByteArrayUnsigned().CopyTo(m_RSAParams.DP, 0);

                m_RSAParams.DQ = new byte[keyParams.DQ.ToByteArrayUnsigned().Length];
                keyParams.DQ.ToByteArrayUnsigned().CopyTo(m_RSAParams.DQ, 0);

                m_RSAParams.InverseQ = new byte[keyParams.QInv.ToByteArrayUnsigned().Length];
                keyParams.QInv.ToByteArrayUnsigned().CopyTo(m_RSAParams.InverseQ, 0);

                m_RSAParams.D = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
                keyParams.Exponent.ToByteArrayUnsigned().CopyTo(m_RSAParams.D, 0);

                m_RSAParams.Exponent = new byte[keyParams.PublicExponent.ToByteArrayUnsigned().Length];
                keyParams.PublicExponent.ToByteArrayUnsigned().CopyTo(m_RSAParams.Exponent, 0);

                rsa.ImportParameters(m_RSAParams);
                if (rsa != null)
                {
                    int    inputBlockSize = rsa.KeySize / 8 - 42;
                    byte[] bytes1         = rsa.Encrypt(new byte[inputBlockSize], RSAEncryptionPadding.OaepSHA1);
                    byte[] bytes2         = rsa.Decrypt(bytes1, RSAEncryptionPadding.OaepSHA1);
                    if (bytes2 != null)
                    {
                        return(certificate);
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Could not load application certificate " + subjectName);
            }

            return(null);
        }
        public void TestCreationECDSA()
        {
            IBigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            IBigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            IBigInteger ECParraH = new BigInteger(Base64.Decode("AQ=="));
            IBigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            IBigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            IBigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            IBigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));
            FPCurve curve = new FPCurve(
               new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
            ECDomainParameters ecDomain =
                new ECDomainParameters(curve, new FPPoint(curve, curve.FromBigInteger(ECParraGX), curve.FromBigInteger(ECParraGY)), ECParraN);
            ECPublicKeyParameters ecPub = new ECPublicKeyParameters(
                "ECDSA",
                new FPPoint(curve,
                    curve.FromBigInteger(ECPubQX),
                    curve.FromBigInteger(ECPubQY)),
                ecDomain);
            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters("ECDSA", ECPrivD, ecDomain);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
            certGen.SetNotAfter(DateTime.Today.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(ecPub);
            certGen.SetSignatureAlgorithm("SHA1WITHECDSA");

            X509Certificate cert = certGen.Generate(ecPriv);

            //            Assert.IsTrue((cert.IsValidNow && cert.Verify(ecPub)), "Certificate failed to be valid (ECDSA)");
            cert.CheckValidity();
            cert.Verify(ecPub);

            ISet dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();

            dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 15
0
        public Org.BouncyCastle.X509.X509Certificate GenerateCertificate(SecureRandom random,
                                                                         string subjectName,
                                                                         AsymmetricCipherKeyPair subjectKeyPair,
                                                                         BigInteger subjectSerialNumber,
                                                                         string[] subjectAlternativeNames,
                                                                         string issuerName,
                                                                         AsymmetricCipherKeyPair issuerKeyPair,
                                                                         BigInteger issuerSerialNumber,
                                                                         bool isCertificateAuthority,
                                                                         KeyPurposeID[] usages)
        {
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(subjectSerialNumber);

            // Set the signature algorithm. This is used to generate the thumbprint which is then signed
            // with the issuer's private key. We'll use SHA-256, which is (currently) considered fairly strong.
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            var issuerDN = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);

            // Note: The subject can be omitted if you specify a subject alternative name (SAN).
            var subjectDN = new X509Name(subjectName);

            certificateGenerator.SetSubjectDN(subjectDN);

            // Our certificate needs valid from/to values.
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(20);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // The subject's public key goes in the certificate.
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            AddAuthorityKeyIdentifier(certificateGenerator, issuerDN, issuerKeyPair, issuerSerialNumber);
            AddSubjectKeyIdentifier(certificateGenerator, subjectKeyPair);
            AddBasicConstraints(certificateGenerator, isCertificateAuthority);

            if (usages != null && usages.Any())
            {
                AddExtendedKeyUsage(certificateGenerator, usages);
            }

            if (subjectAlternativeNames != null && subjectAlternativeNames.Any())
            {
                AddSubjectAlternativeNames(certificateGenerator, subjectAlternativeNames);
            }



            // The certificate is signed with the issuer's private key.
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

            return(certificate);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Generates a ca certificate
        /// </summary>
        /// <param name="privateKey">The CA private key used to sign certificates</param>
        /// <param name="base64EncodedCer">The cer file used to configure the browser</param>
        /// <returns></returns>
        public static void GenerateCACert(out string privateKey, out string base64EncodedCer)
        {
            string subjectName = CA_NAME;
            int    keyStrength = 1024;

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);


            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);


            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", issuerKeyPair.Private, random);
            var certificate = certificateGenerator.Generate(signatureFactory);


            base64EncodedCer = String.Format("-----BEGIN CERTIFICATE-----\r\n{0}\r\n-----END CERTIFICATE-----",
                                             Convert.ToBase64String(certificate.GetEncoded()));

            //var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            //System.Security.Cryptography.X509Certificates.X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(certificate);
            //X509Certificate2 dotNetCert2 = new X509Certificate2(dotNetCert);
            // Add CA certificate to Root store
            //AddCertToStore(dotNetCert2, StoreName.Root, StoreLocation.LocalMachine);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(issuerKeyPair.Private);

            privateKey = Convert.ToBase64String(info.GetEncoded());
        }
Exemplo n.º 17
0
        /// <summary>
        /// Builds the certificate depending on the parameters
        /// </summary>
        /// <returns>X509Certificate2 from the chosen parameters</returns>
        public X509Certificate2 Build()
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            if (_signatureAlgorithm < 0 || (int)_signatureAlgorithm >= PKCS15SignatureAlgorithmList.Length)
            {
                _signatureAlgorithm = PKCS15SignatureAlgorithm.SHA256WITHRSA;
            }

            // Add SAN Extension
            if (_SubjectAlternativeName != null)
            {
                certificateGenerator.AddExtension
                (
                    X509Extensions.SubjectAlternativeName,
                    false,
                    SubjectAlternativeNamesToGeneralNames(_SubjectAlternativeName)
                );
            }

            // Issuer and Subject Name
            if (_DistinguishedName == null)
            {
                certificateGenerator.SetIssuerDN(new X509Name(_issuerName ?? _subjectName));
                certificateGenerator.SetSubjectDN(new X509Name(_subjectName));
            }
            else
            {
                if (_issuerName != null && _issuerName.Length > 0)
                {
                    certificateGenerator.SetIssuerDN(new X509Name(_issuerName));
                }
                else
                {
                    certificateGenerator.SetIssuerDN(DistinguishedNamesToX509Name(_DistinguishedName));
                }
                certificateGenerator.SetSubjectDN(DistinguishedNamesToX509Name(_DistinguishedName));
            }

            // Authority Key Identifier
            if (_issuer != null)
            {
                var authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(
                    DotNetUtilities.FromX509Certificate(_issuer)
                    );
                certificateGenerator.AddExtension(
                    X509Extensions.AuthorityKeyIdentifier.Id,
                    false,
                    authorityKeyIdentifier
                    );
            }

            // Basic Constraints - certificate is allowed to be used as intermediate.
            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, new BasicConstraints(_intermediate));

            // Key intended purpose constrain
            if (_keyPurpose.Length > 0)
            {
                ArrayList kpList = new ArrayList();
                for (int i = 0; i < _keyPurpose.Length; i++)
                {
                    kpList.Add(new DerObjectIdentifier(_keyPurpose[i]));
                }
                IEnumerable kp = kpList;
                certificateGenerator.AddExtension(
                    X509Extensions.ExtendedKeyUsage.Id,
                    _criticalKeyPurpose,
                    new ExtendedKeyUsage(kp)
                    );
            }

            // Key usage
            if (_keyUsage > 0)
            {
                certificateGenerator.AddExtension(
                    X509Extensions.KeyUsage.Id,
                    _criticalKeyUsage,
                    new KeyUsage(_keyUsage)
                    );
            }

            // Valid For
            certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(2));

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, _keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            var issuerKeyPair  = _issuerPrivateKey == null
                ? subjectKeyPair
                : DotNetUtilities.GetKeyPair(_issuerPrivateKey);

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // self-sign certificate
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(PKCS15SignatureAlgorithmList[(int)_signatureAlgorithm], issuerKeyPair.Private, random);
            var certificate = certificateGenerator.Generate(signatureFactory);

            // merge into X509Certificate2
            if (_friendlyName != null)
            {
                return(new X509Certificate2(certificate.GetEncoded())
                {
                    PrivateKey = ConvertToRsaPrivateKey(subjectKeyPair),
                    FriendlyName = _friendlyName
                });
            }
            return(new X509Certificate2(certificate.GetEncoded())
            {
                PrivateKey = ConvertToRsaPrivateKey(subjectKeyPair)
            });
        }
Exemplo n.º 18
0
        private static X509Certificate2 CreateSelfSignedCertificateBasedOnPrivateKey(string commonNameValue, string issuerSubjectName,
                                                                                     AsymmetricKeyParameter issuerPrivKey, bool isClientCertificate, int yearsUntilExpiration)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            var random = GetSeededSecureRandom();
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            var extendedKeyUsage = isClientCertificate
                ? new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth)
                : new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth);

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, extendedKeyUsage);

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name("CN=" + commonNameValue);
            X509Name issuerDN  = new X509Name(issuerSubjectName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date.AddDays(-7);
            DateTime notAfter  = notBefore.AddYears(yearsUntilExpiration);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            X509Certificate certificate      = certificateGenerator.Generate(signatureFactory);
            var             store            = new Pkcs12Store();
            string          friendlyName     = certificate.SubjectDN.ToString();
            var             certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });
            var stream = new MemoryStream();

            store.Save(stream, new char[0], random);
            var convertedCertificate =
                new X509Certificate2(
                    stream.ToArray(), (string)null,
                    X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            stream.Position = 0;

            return(convertedCertificate);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Builds the CSR depending on the parameters provided.
        /// </summary>
        /// <returns>CSR data.</returns>
        public CSR GenerateCSR()
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            if (_signatureAlgorithm < 0 || (int)_signatureAlgorithm >= PKCS15SignatureAlgorithmList.Length)
            {
                _signatureAlgorithm = PKCS15SignatureAlgorithm.SHA256WITHRSA;
            }

            // Issuer and Subject Name
            if (_DistinguishedName == null)
            {
                certificateGenerator.SetIssuerDN(new X509Name(_subjectName));
                certificateGenerator.SetSubjectDN(new X509Name(_subjectName));
            }
            else
            {
                certificateGenerator.SetIssuerDN(DistinguishedNamesToX509Name(_DistinguishedName));
                certificateGenerator.SetSubjectDN(DistinguishedNamesToX509Name(_DistinguishedName));
            }

            // Add SAN extension
            if (_SubjectAlternativeName != null)
            {
                certificateGenerator.AddExtension
                (
                    X509Extensions.SubjectAlternativeName,
                    false,
                    SubjectAlternativeNamesToGeneralNames(_SubjectAlternativeName)
                );
            }

            // Basic Constraints - certificate is not allowed to be used as intermediate.
            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false));

            // Key intended purpose constrain
            if (_keyPurpose.Length > 0)
            {
                ArrayList kpList = new ArrayList();
                for (int i = 0; i < _keyPurpose.Length; i++)
                {
                    kpList.Add(new DerObjectIdentifier(_keyPurpose[i]));
                }
                IEnumerable kp = kpList;
                certificateGenerator.AddExtension(
                    X509Extensions.ExtendedKeyUsage.Id,
                    _criticalKeyPurpose,
                    new ExtendedKeyUsage(kp)
                    );
            }

            // Key usage
            if (_keyUsage > 0)
            {
                certificateGenerator.AddExtension(
                    X509Extensions.KeyUsage.Id,
                    _criticalKeyUsage,
                    new KeyUsage(_keyUsage)
                    );
            }

            // Valid For
            certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(2));

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, _keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            var issuerKeyPair  = _issuerPrivateKey == null
                ? subjectKeyPair
                : DotNetUtilities.GetKeyPair(_issuerPrivateKey);

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            //Generate CSR
            ISignatureFactory          signatureFactory     = new Asn1SignatureFactory(PKCS15SignatureAlgorithmList[(int)_signatureAlgorithm], issuerKeyPair.Private, random);
            Pkcs10CertificationRequest certificationRequest = null;

            if (_DistinguishedName == null)
            {
                certificationRequest = new Pkcs10CertificationRequest(signatureFactory, new X509Name(_subjectName), subjectKeyPair.Public, null);
            }
            else
            {
                certificationRequest = new Pkcs10CertificationRequest(signatureFactory, DistinguishedNamesToX509Name(_DistinguishedName), subjectKeyPair.Public, null);
            }
            var certificate = certificateGenerator.Generate(signatureFactory);

            //Build the CSR
            StringBuilder csrStrBuilder = new StringBuilder();
            PemWriter     csrPemWriter  = new PemWriter(new StringWriter(csrStrBuilder));

            csrPemWriter.WriteObject(certificationRequest);
            csrPemWriter.Writer.Flush();

            CSR csrResult = new CSR();

            csrResult.CSRPEM = csrStrBuilder.ToString();

            //Merge the private key into X509Certificate2
            X509Certificate2 privateKey;

            if (_friendlyName != null)
            {
                privateKey = new X509Certificate2(certificate.GetEncoded())
                {
                    PrivateKey   = ConvertToRsaPrivateKey(subjectKeyPair),
                    FriendlyName = _friendlyName
                };
            }
            else
            {
                privateKey = new X509Certificate2(certificate.GetEncoded())
                {
                    PrivateKey = ConvertToRsaPrivateKey(subjectKeyPair)
                };
            }
            csrResult.PrivateKey = privateKey;

            return(csrResult);
        }
Exemplo n.º 20
0
        /// <summary>
        ///     Generates the certificate.
        /// </summary>
        /// <param name="subjectName">Name of the subject.</param>
        /// <param name="issuerName">Name of the issuer.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="keyStrength">The key strength.</param>
        /// <param name="signatureAlgorithm">The signature algorithm.</param>
        /// <param name="issuerPrivateKey">The issuer private key.</param>
        /// <param name="hostName">The host name</param>
        /// <returns>X509Certificate2 instance.</returns>
        /// <exception cref="PemException">Malformed sequence in RSA private key</exception>
        private static X509Certificate2 generateCertificate(string hostName,
                                                            string subjectName,
                                                            string issuerName, DateTime validFrom,
                                                            DateTime validTo, int keyStrength       = 2048,
                                                            string signatureAlgorithm               = "SHA256WithRSA",
                                                            AsymmetricKeyParameter issuerPrivateKey = null)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom    = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber =
                BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), secureRandom);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            certificateGenerator.SetNotBefore(validFrom);
            certificateGenerator.SetNotAfter(validTo);

            if (hostName != null)
            {
                // add subject alternative names
                var subjectAlternativeNames = new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, hostName) };

                var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);
                certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false,
                                                  subjectAlternativeNamesExtension);
            }

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(secureRandom, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Set certificate intended purposes to only Server Authentication
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                                              new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));
            if (issuerPrivateKey == null)
            {
                certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true));
            }

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm,
                                                            issuerPrivateKey ?? subjectKeyPair.Private, secureRandom);

            // Self-sign the certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // Corresponding private key
            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyInfo.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                                                           rsa.Prime1, rsa.Prime2, rsa.Exponent1,
                                                           rsa.Exponent2, rsa.Coefficient);

#if NET45
            // Set private key onto certificate instance
            var x509Certificate = new X509Certificate2(certificate.GetEncoded());
            x509Certificate.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
#else
            var x509Certificate = withPrivateKey(certificate, rsaparams);
#endif

            if (!doNotSetFriendlyName)
            {
                try
                {
                    x509Certificate.FriendlyName = ProxyConstants.CNRemoverRegex.Replace(subjectName, string.Empty);
                }
                catch (PlatformNotSupportedException)
                {
                    doNotSetFriendlyName = true;
                }
            }

            return(x509Certificate);
        }
Exemplo n.º 21
0
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, int keyStrength)
        {
            try
            {
                // Generating Random Numbers
                var randomGenerator = new VmpcRandomGenerator();
                var random          = new SecureRandom(randomGenerator);

                // The Certificate Generator
                var certificateGenerator = new X509V3CertificateGenerator();

                // Serial Number
                var serialNumber = BigInteger.ProbablePrime(128, new Random());
                certificateGenerator.SetSerialNumber(serialNumber);

                // Signature Algorithm
                var signatureAlgorithm = "SHA512WithRSA";
                certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

                // Issuer and Subject Name
                var subjectDN = new X509Name(subjectName);
                var issuerDN  = new X509Name(issuerName);
                certificateGenerator.SetIssuerDN(issuerDN);
                certificateGenerator.SetSubjectDN(subjectDN);

                // Valid For
                var notBefore = DateTime.UtcNow.Date.AddYears(-1);
                var notAfter  = notBefore.AddYears(10);
                certificateGenerator.SetNotBefore(notBefore);
                certificateGenerator.SetNotAfter(notAfter);

                // Subject Public Key
                var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
                var keyPairGenerator        = new RsaKeyPairGenerator();
                keyPairGenerator.Init(keyGenerationParameters);

                if (userKeyPair == null)
                {
                    userKeyPair = keyPairGenerator.GenerateKeyPair();
                }

                certificateGenerator.SetPublicKey(userKeyPair.Public);

                //Extented
                certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                                  new SubjectKeyIdentifierStructure(userKeyPair.Public));
                certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                                  new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory
                                                                             .CreateSubjectPublicKeyInfo(userKeyPair.Public)));
                var valueData = Encoding.ASCII.GetBytes("Client");
                certificateGenerator.AddExtension("1.3.6.1.5.5.7.13.3", false, valueData);

                // Generating the Certificate
                var issuerKeyPair = userKeyPair;

                // selfsign certificate
                var certificate = certificateGenerator.Generate(userKeyPair.Private, random);

                // correcponding private key
                var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(userKeyPair.Private);

                // merge into X509Certificate2
                var x509 = new X509Certificate2(certificate.GetEncoded());

                var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());
                if (seq.Count != 9)
                {
                    throw new Exception("malformed sequence in RSA private key");
                }

                var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
                var rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                                                               rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                                                               rsa.Coefficient);
#if NETCOREAPP2_0 || NETCOREAPP2_1
                x509 = x509.CopyWithPrivateKey(PemUtils.ToRSA(rsaparams));
#endif
                return(x509);
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"The Method \"{nameof(GenerateSelfSignedCertificate)}\" has failed.");
                return(null);
            }
        }
Exemplo n.º 22
0
        public async Task ValidateMergeCertificate()
        {
            string serverCertificateName = Recording.GenerateId();

            // Generate the request.
            CertificatePolicy policy = new CertificatePolicy(WellKnownIssuerNames.Unknown, "CN=Azure SDK")
            {
                CertificateTransparency = false,
                ContentType             = CertificateContentType.Pkcs12,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(serverCertificateName, policy);

            RegisterForCleanup(serverCertificateName);
            await using IAsyncDisposable disposableOperation = EnsureDeleted(operation);

            // Read the CA.
            byte[]           caCertificateBytes = Convert.FromBase64String(CaPublicKeyBase64);
            X509Certificate2 caCertificate      = new X509Certificate2(caCertificateBytes);

            // Read CA private key since getting it from caCertificate above throws.
            AsymmetricCipherKeyPair caPrivateKey;

            using (StringReader caPrivateKeyReader = new StringReader(CaPrivateKeyPem))
            {
                Org.BouncyCastle.OpenSsl.PemReader reader = new Org.BouncyCastle.OpenSsl.PemReader(caPrivateKeyReader);
                caPrivateKey = (AsymmetricCipherKeyPair)reader.ReadObject();
            }

            // Read the CSR.
            Pkcs10CertificationRequest csr     = new Pkcs10CertificationRequest(operation.Properties.Csr);
            CertificationRequestInfo   csrInfo = csr.GetCertificationRequestInfo();

            // Parse the issuer subject name.
            Hashtable oidLookup = new Hashtable(X509Name.DefaultLookup)
            {
                { "s", new DerObjectIdentifier("2.5.4.8") },
            };

            X509Name issuerName = new X509Name(true, oidLookup, caCertificate.Subject);

            // Sign the request.
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetIssuerDN(issuerName);
            generator.SetSerialNumber(BigInteger.One);
            generator.SetNotBefore(DateTime.Now);
            generator.SetNotAfter(DateTime.Now.AddDays(1));
            generator.SetSubjectDN(csrInfo.Subject);
            generator.SetPublicKey(csr.GetPublicKey());

            Asn1SignatureFactory signatureFactory      = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.Private);
            X509Certificate      serverSignedPublicKey = generator.Generate(signatureFactory);

            // Merge the certificate chain.
            MergeCertificateOptions       options = new MergeCertificateOptions(serverCertificateName, new[] { serverSignedPublicKey.GetEncoded(), caCertificateBytes });
            KeyVaultCertificateWithPolicy mergedServerCertificate = await Client.MergeCertificateAsync(options);

            X509Certificate2 serverCertificate = new X509Certificate2(mergedServerCertificate.Cer);

            Assert.AreEqual(csrInfo.Subject.ToString(), serverCertificate.Subject);
            Assert.AreEqual(serverCertificateName, mergedServerCertificate.Name);

            KeyVaultCertificateWithPolicy completedServerCertificate = await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            Assert.AreEqual(mergedServerCertificate.Name, completedServerCertificate.Name);
            CollectionAssert.AreEqual(mergedServerCertificate.Cer, completedServerCertificate.Cer);
        }
Exemplo n.º 23
0
        // Note: Much of this code comes from https://stackoverflow.com/a/22247129
        private static X509Certificate2 GenerateSelfSignedCertificate(string subject)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random));

            // Subject Public Key
            var keyPairGenerator        = new RsaKeyPairGenerator();
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Subject DN
            certificateGenerator.SetSubjectDN(new X509Name("CN=" + subject));

            // Subject Alternative Name
            var subjectAlternativeNames = new List <Asn1Encodable>()
            {
                new GeneralName(GeneralName.DnsName, Environment.MachineName),
                new GeneralName(GeneralName.DnsName, "localhost"),
                new GeneralName(GeneralName.IPAddress, "127.0.0.1"),
            };

            if (subject != "localhost" && subject != Environment.MachineName)
            {
                subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, subject));
            }

            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, new DerSequence(subjectAlternativeNames.ToArray()));

            // Issuer
            certificateGenerator.SetIssuerDN(new X509Name("CN=" + subject));
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)));

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Add basic constraint
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false));

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";
            var          signatureFactory   = new Asn1SignatureFactory(signatureAlgorithm, subjectKeyPair.Private);

            // selfsign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // correcponding private key
            var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new X509Certificate2(certificate.GetEncoded());
            var seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                // throw new PemException("malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            try
            {
                x509.PrivateKey = ToDotNetKey(rsaparams); // x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            }
            catch (CryptographicException e)
            {
                throw new Exception($"Exception on cert generation!\nSubject {subject}\nHostname {Environment.MachineName}\nSequenceCount {seq.Count} (should be 9?)", e);
            }

            return(x509);
        }
        public override X509CertificateBuilderResult Build()
        {
            var issuerX509Certificate2 = new SystemX509Certificates.X509Certificate2(
                IssuerCertificate,
                IssuerCertificatePassword,
                SystemX509Certificates.X509KeyStorageFlags.Exportable
                );

            var issuerSubjectDN = issuerX509Certificate2.ToX509Certificate().SubjectDN;

            X509V3CertificateGenerator.SetIssuerDN(issuerSubjectDN);

            // Generate Keys.
            var rsaKeyPairGenerator = new RsaKeyPairGenerator();

            rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), this.KeySize));
            var asymmetricCipherKeyPair = rsaKeyPairGenerator.GenerateKeyPair();

            // Set Public Key.
            X509V3CertificateGenerator.SetPublicKey(asymmetricCipherKeyPair.Public);

            // Key Usage - for maximum interoperability, specify all four flags.
            var keyUsage = KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyEncipherment | KeyUsage.KeyAgreement;

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(keyUsage)
                );

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.BasicConstraints,
                true,
                new BasicConstraints(false)
                );

            // Extended Key Usage.
            var extendedKeyUsage = new List <KeyPurposeID>();

            // Set TLS Web Server Authentication (1.3.6.1.5.5.7.3.1).
            if (IsServerAuthKeyUsage)
            {
                extendedKeyUsage.Add(KeyPurposeID.IdKPServerAuth);
            }

            // Set TLS Web Client Authentication (1.3.6.1.5.5.7.3.2).
            if (IsClientAuthKeyUsage)
            {
                extendedKeyUsage.Add(KeyPurposeID.IdKPClientAuth);
            }

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                new ExtendedKeyUsage(extendedKeyUsage)
                );

            // Set Subject Alternative Names.
            if (SubjectAlternativeNames != null)
            {
                var subjectAlternativeNames = new Asn1Encodable[SubjectAlternativeNames.Count];

                for (int i = 0; i < SubjectAlternativeNames.Count; i++)
                {
                    subjectAlternativeNames[i] = new GeneralName(GeneralName.DnsName, SubjectAlternativeNames[i]);
                }

                X509V3CertificateGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName,
                    false,
                    new DerSequence(subjectAlternativeNames)
                    );
            }

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.AuthorityKeyIdentifier,
                false,
                new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerX509Certificate2.GetPublicKeyAsAsymmetricKeyParameter()),
                    new GeneralNames(new GeneralName(issuerSubjectDN)),
                    new Org.BouncyCastle.Math.BigInteger(issuerX509Certificate2.GetSerialNumber())
                    )
                );

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier,
                false,
                new SubjectKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricCipherKeyPair.Public)
                    )
                );

            var signatureFactory = new Asn1SignatureFactory(GetSignatureAlgorithm(this.KeySize), issuerX509Certificate2.GetPrivateKeyAsAsymmetricKeyParameter());

            // Generate X.509 Certificate.
            var x509Certificate = X509V3CertificateGenerator.Generate(signatureFactory);

            return(new X509CertificateBuilderResult(x509Certificate, asymmetricCipherKeyPair.Private));
        }
Exemplo n.º 25
0
        public void TestCreationDSA()
        {
            BigInteger DSAParaG    = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            BigInteger DSAParaP    = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            BigInteger DSAParaQ    = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            BigInteger DSAPublicY  = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters           para    = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters  dsaPub  = new DsaPublicKeyParameters(DSAPublicY, para);

            IDictionary attrs = new Hashtable();

            attrs[X509Name.C]  = "AU";
            attrs[X509Name.O]  = "The Legion of the Bouncy Castle";
            attrs[X509Name.L]  = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E]  = "*****@*****.**";

            IList ord = new ArrayList();

            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();

            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(dsaPub);
            certGen.SetSignatureAlgorithm("SHA1WITHDSA");

            X509Certificate cert = certGen.Generate(dsaPriv);

//			Assert.IsTrue((cert.IsValidNow && cert.Verify(dsaPub)), "Certificate failed to be valid (DSA Test)");
            cert.CheckValidity();
            cert.Verify(dsaPub);

            //ISet dummySet = cert.GetNonCriticalExtensionOids();

            //if (dummySet != null)
            //{
            //    foreach (string key in dummySet)
            //    {
            //        Console.WriteLine("\t{0}:\t{1}", key);
            //    }
            //}

            //Console.WriteLine();

            //dummySet = cert.GetNonCriticalExtensionOids();
            //if (dummySet != null)
            //{
            //    foreach (string key in dummySet)
            //    {
            //        Console.WriteLine("\t{0}:\t{1}", key);
            //    }
            //}

            //Console.WriteLine();
        }
Exemplo n.º 26
0
        protected virtual X509Certificate2 CreateCertificate(string subjectName, bool isCertificateAuthority, string altName)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            if (!isCertificateAuthority)
            {
                certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));
            }
            else
            {
                certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true));
            }

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDN = new X509Name(true, subjectName);

            certificateGenerator.SetSubjectDN(subjectDN);
            certificateGenerator.SetIssuerDN(isCertificateAuthority ? subjectDN : new X509Name(true, $"CN={RootCertificateName}, O={Issuer}"));

            if (!isCertificateAuthority)
            {
                var subjectAltName = new GeneralNames(new GeneralName(GeneralName.DnsName, altName));
                certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
            }

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;

            certificateGenerator.SetNotBefore(notBefore);

            DateTime notAfter = notBefore.AddYears(1);

            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, 1024);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            AsymmetricKeyParameter issuerPrivateKey = null;

            if (isCertificateAuthority)
            {
                issuerPrivateKey = subjectKeyPair.Private;
                _privateKey      = issuerPrivateKey;
            }
            else
            {
                if (_privateKey == null)
                {
                    X509Certificate2 rootCA = InstallCertificate(RootStore, RootCertificateName);
                    _privateKey = TransformRSAPrivateKey(rootCA.GetRSAPrivateKey().ExportParameters(true));
                }
                issuerPrivateKey = _privateKey;
            }

            var privateKey = (RsaPrivateCrtKeyParameters)issuerPrivateKey;

            if (!isCertificateAuthority)
            {
                PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
                var            seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());
                var            rsa  = RsaPrivateKeyStructure.GetInstance(seq);

                privateKey = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent,
                                                            rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);
            }

            // Self-Sign Certificate
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivateKey, random);
            X509Certificate2  certificate      = GetSignedCertificate(certificateGenerator.Generate(signatureFactory), privateKey);

            certificate.FriendlyName = subjectName;
            return(certificate);
        }
Exemplo n.º 27
0
        public void TestCreationECDSA()
        {
            BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            BigInteger ECParraH  = new BigInteger(Base64.Decode("AQ=="));
            BigInteger ECParraN  = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            BigInteger ECPubQX   = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            BigInteger ECPubQY   = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            BigInteger ECPrivD   = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));

            X9ECParameters     x9       = ECNamedCurveTable.GetByName("prime239v1");
            ECCurve            curve    = x9.Curve;
            ECDomainParameters ecDomain = new ECDomainParameters(curve, curve.ValidatePoint(ECParraGX, ECParraGY), ECParraN, ECParraH);

            ECPublicKeyParameters ecPub = new ECPublicKeyParameters("ECDSA",
                                                                    curve.ValidatePoint(ECPubQX, ECPubQY), ecDomain);
            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters("ECDSA", ECPrivD, ecDomain);

            IDictionary attrs = new Hashtable();

            attrs[X509Name.C]  = "AU";
            attrs[X509Name.O]  = "The Legion of the Bouncy Castle";
            attrs[X509Name.L]  = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E]  = "*****@*****.**";

            IList ord = new ArrayList();

            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();

            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(ecPub);
            certGen.SetSignatureAlgorithm("SHA1WITHECDSA");

            certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

            X509Certificate cert = certGen.Generate(ecPriv);

//            Assert.IsTrue((cert.IsValidNow && cert.Verify(ecPub)), "Certificate failed to be valid (ECDSA)");
            cert.CheckValidity();
            cert.Verify(ecPub);

            ISet extOidSet = cert.GetCriticalExtensionOids();

            if (extOidSet.Count != 1)
            {
                Fail("wrong number of oids");
            }
            //if (dummySet != null)
            //{
            //    foreach (string key in dummySet)
            //    {
            //        Console.WriteLine("\t{0}:\t{1}", key);
            //    }
            //}

            //Console.WriteLine();

            //dummySet = cert.GetNonCriticalExtensionOids();

            //if (dummySet != null)
            //{
            //    foreach (string key in dummySet)
            //    {
            //        Console.WriteLine("\t{0}:\t{1}", key);
            //    }
            //}

            //Console.WriteLine();
        }
Exemplo n.º 28
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation("Certificate trigger function processed a request.");

            try
            {
                await ReadAppSettings(context, log);

                string requestBody          = await new StreamReader(req.Body).ReadToEndAsync();
                Certificate_Request request = JsonConvert.DeserializeObject <Certificate_Request>(requestBody);

                // Validate payload
                if (string.IsNullOrEmpty(request.RegistrationId) || string.IsNullOrEmpty(request.Csr))
                {
                    return(new BadRequestResult());
                }

                // Check if the device is authorized to request a certificate
                bool isAuthorized = CheckIfAuthorized(request.RegistrationId);

                if (isAuthorized)
                {
                    log.LogInformation($"{request.RegistrationId} is authorized.");

                    Pkcs10CertificationRequest decodedCsr = null;
                    RsaKeyParameters           publicKey  = null;
                    CertificationRequestInfo   info       = null;

                    // Get the signing certificate from a location
                    X509Certificate serverCertificate = ReadCertificate(cert, location, log);

                    if (serverCertificate == null)
                    {
                        throw new System.Exception("ReadCertificate() was unable to retrieve the signing certificate.");
                    }

                    // Get signing cert private key from a location.
                    AsymmetricKeyParameter serverPrivateKey = ReadPrivateKey(key, location, log);

                    if (serverPrivateKey == null)
                    {
                        throw new System.Exception("ReadPrivateKey() was unable to retrieve the private key.");
                    }

                    byte[] csr = Convert.FromBase64String(request.Csr);

                    // Decode DER
                    decodedCsr = new Pkcs10CertificationRequest(csr);
                    info       = decodedCsr.GetCertificationRequestInfo();
                    SubjectPublicKeyInfo publicKeyInfo = info.SubjectPublicKeyInfo;

                    RsaPublicKeyStructure publicKeyStructure = RsaPublicKeyStructure.GetInstance(publicKeyInfo.ParsePublicKey());

                    publicKey = new RsaKeyParameters(false, publicKeyStructure.Modulus, publicKeyStructure.PublicExponent);

                    bool certIsOK = decodedCsr.Verify(publicKey);

                    // Create the device certificate
                    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

                    generator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
                    generator.SetIssuerDN(serverCertificate.SubjectDN);
                    generator.SetNotBefore(DateTime.Now);
                    generator.SetNotAfter(DateTime.Now.AddYears(certificateLifespanInYears));
                    generator.SetSubjectDN(info.Subject);
                    generator.SetPublicKey(publicKey);
                    generator.SetSignatureAlgorithm("SHA512withRSA");
                    generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(serverCertificate));
                    generator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));

                    // Generate the device certificate
                    var deviceCert = generator.Generate(serverPrivateKey);

                    // Convert to DER
                    byte[] encoded = deviceCert.GetEncoded();

                    // Convert byte array to Base64 string
                    string encodedString = Convert.ToBase64String(encoded);

                    Certificate_Response responseMessage = new Certificate_Response
                    {
                        Certificate = encodedString
                    };

                    log.LogInformation($"Certificate issued for: {info.Subject}");

                    return(new OkObjectResult(responseMessage));
                }
                else
                {
                    log.LogError($"{request.RegistrationId} is NOT authorized.");

                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message);
            }

            return(new BadRequestResult());
        }
Exemplo n.º 29
0
        public void TestCreationRSA()
        {
            BigInteger                 rsaPubMod   = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
            BigInteger                 rsaPubExp   = new BigInteger(Base64.Decode("EQ=="));
            BigInteger                 rsaPrivMod  = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
            BigInteger                 rsaPrivDP   = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ=="));
            BigInteger                 rsaPrivDQ   = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ=="));
            BigInteger                 rsaPrivExp  = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E="));
            BigInteger                 rsaPrivP    = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE="));
            BigInteger                 rsaPrivQ    = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0="));
            BigInteger                 rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg=="));
            RsaKeyParameters           rsaPublic   = new RsaKeyParameters(false, rsaPubMod, rsaPubExp);
            RsaPrivateCrtKeyParameters rsaPrivate  = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);

            IDictionary attrs = new Hashtable();

            attrs[X509Name.C]  = "AU";
            attrs[X509Name.O]  = "The Legion of the Bouncy Castle";
            attrs[X509Name.L]  = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E]  = "*****@*****.**";

            IList ord = new ArrayList();

            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();

            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(rsaPublic);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");

            X509Certificate cert = certGen.Generate(rsaPrivate);

//			Assert.IsTrue((cert.IsValidNow && cert.Verify(rsaPublic)),"Certificate failed to be valid (RSA)");
            cert.CheckValidity();
            cert.Verify(rsaPublic);

            //Console.WriteLine(ASN1Dump.DumpAsString(cert.ToAsn1Object()));

            //ISet dummySet = cert.GetNonCriticalExtensionOids();

            //if (dummySet != null)
            //{
            //    foreach (string key in dummySet)
            //    {
            //        Console.WriteLine("\t{0}:\t{1}", key);
            //    }
            //}

            //Console.WriteLine();

            //dummySet = cert.GetNonCriticalExtensionOids();
            //if (dummySet != null)
            //{
            //    foreach (string key in dummySet)
            //    {
            //        Console.WriteLine("\t{0}:\t{1}", key);
            //    }
            //}

            //Console.WriteLine();
        }
        public void TestCreationDSA()
        {
            IBigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            IBigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            IBigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            IBigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            IBigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(dsaPub);
            certGen.SetSignatureAlgorithm("SHA1WITHDSA");

            X509Certificate cert = certGen.Generate(dsaPriv);

            //			Assert.IsTrue((cert.IsValidNow && cert.Verify(dsaPub)), "Certificate failed to be valid (DSA Test)");
            cert.CheckValidity();
            cert.Verify(dsaPub);

            ISet dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();

            dummySet = cert.GetNonCriticalExtensionOids();
            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 31
0
        /// <summary>
        /// Create the actual certificate
        /// </summary>
        public static bool CreateCertificate(ICertificateSettings settings, Action <string> log, out string thumbprint, out string errorMessage)
        {
            errorMessage = string.Empty;
            thumbprint   = string.Empty;

            try
            {
                var keyStore = new Pkcs12Store();

                log(Strings.GeneratingKeys);
                var pGen     = new RsaKeyPairGenerator();
                var genParam = new
                               RsaKeyGenerationParameters(
                    BigInteger.ValueOf(0x10001),
                    new SecureRandom(),
                    1024,
                    10);
                pGen.Init(genParam);
                var keyPair = pGen.GenerateKeyPair();

                log(Strings.GeneratingCertificate);
                var attrs = new Dictionary <DerObjectIdentifier, string>();
                var oids  = new List <DerObjectIdentifier> {
                    X509Name.O, X509Name.L, X509Name.C, X509Name.CN, X509Name.EmailAddress, X509Name.OU, X509Name.ST
                };
                oids.Reverse();
                if (!string.IsNullOrEmpty(settings.OrgName))
                {
                    attrs.Add(X509Name.O, settings.OrgName);
                }
                else
                {
                    oids.Remove(X509Name.O);
                }
                if (!string.IsNullOrEmpty(settings.OrgUnit))
                {
                    attrs.Add(X509Name.OU, settings.OrgUnit);
                }
                else
                {
                    oids.Remove(X509Name.OU);
                }
                if (!string.IsNullOrEmpty(settings.City))
                {
                    attrs.Add(X509Name.L, settings.City);
                }
                else
                {
                    oids.Remove(X509Name.L);
                }
                if (!string.IsNullOrEmpty(settings.CountryCode))
                {
                    attrs.Add(X509Name.C, settings.CountryCode);
                }
                else
                {
                    oids.Remove(X509Name.C);
                }
                if (!string.IsNullOrEmpty(settings.State))
                {
                    attrs.Add(X509Name.ST, settings.State);
                }
                else
                {
                    oids.Remove(X509Name.ST);
                }
                if (!string.IsNullOrEmpty(settings.Email))
                {
                    attrs.Add(X509Name.EmailAddress, settings.Email);
                }
                else
                {
                    oids.Remove(X509Name.EmailAddress);
                }
                if (!string.IsNullOrEmpty(settings.UserName))
                {
                    attrs.Add(X509Name.CN, settings.UserName);
                }
                else
                {
                    oids.Remove(X509Name.CN);
                }

                var certGen = new X509V3CertificateGenerator();
                var random  = new SecureRandom();

                certGen.SetSerialNumber(BigInteger.ValueOf(Math.Abs(random.NextInt())));
                certGen.SetIssuerDN(new X509Name(oids, attrs));
                certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
                var years = Math.Min(settings.MaxYears, 50);
                certGen.SetNotAfter(DateTime.Today.AddYears(years));
                certGen.SetSubjectDN(new X509Name(oids, attrs));
                certGen.SetPublicKey(keyPair.Public);
                certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

                var cert = certGen.Generate(keyPair.Private);

                // Save
                log(Strings.SavingCertificate);
                var          keyEntry  = new AsymmetricKeyEntry(keyPair.Private);
                var          certEntry = new X509CertificateEntry(cert);
                const string alias     = "alias";
                keyStore.SetKeyEntry(alias, keyEntry, new[] { certEntry });

                var password     = settings.Password;
                var memoryStream = new MemoryStream();
                keyStore.Save(memoryStream, password.ToCharArray(), random);
                memoryStream.Position = 0;

                // Save certificate
                var path   = settings.Path;
                var folder = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                // Set path in finished page.
                using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    memoryStream.WriteTo(fileStream);
                }

                if (settings.ImportInCertificateStore)
                {
                    log("Importing certificate in My Certificates store");
                    var certificate = new X509Certificate2(path, password,
                                                           X509KeyStorageFlags.Exportable |
                                                           X509KeyStorageFlags.PersistKeySet);
                    thumbprint = certificate.Thumbprint;
                    var x509Store2 = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    try
                    {
                        x509Store2.Open(OpenFlags.ReadWrite);
                        x509Store2.Add(certificate);
                        x509Store2.Close();
                    }
                    catch (Exception ex)
                    {
                        errorMessage = string.Format("Failed to import certificate because: {0}", ex.Message);
                        return(false);
                    }
                }

                if (years < 30)
                {
                    log("Certificate is intended for evaluation purposes. It cannot be used to deploy to the market.");
                }
                return(true);
            }
            catch (Exception ex)
            {
                ErrorLog.DumpError(ex);
                errorMessage = string.Format("Failed to create certificate because {0}.", ex.Message);
                return(false);
            }
        }
        public void TestCreationRSA()
        {
            IBigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
            IBigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ=="));
            IBigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt"));
            IBigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ=="));
            IBigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ=="));
            IBigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E="));
            IBigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE="));
            IBigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0="));
            IBigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg=="));
            RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp);
            RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);

            IDictionary attrs = new Hashtable();
            attrs[X509Name.C] = "AU";
            attrs[X509Name.O] = "The Legion of the Bouncy Castle";
            attrs[X509Name.L] = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E] = "*****@*****.**";

            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(rsaPublic);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");

            X509Certificate cert = certGen.Generate(rsaPrivate);

            //			Assert.IsTrue((cert.IsValidNow && cert.Verify(rsaPublic)),"Certificate failed to be valid (RSA)");
            cert.CheckValidity();
            cert.Verify(rsaPublic);

            //Console.WriteLine(ASN1Dump.DumpAsString(cert.ToAsn1Object()));

            ISet dummySet = cert.GetNonCriticalExtensionOids();

            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();

            dummySet = cert.GetNonCriticalExtensionOids();
            if (dummySet != null)
            {
                foreach (string key in dummySet)
                {
                    Console.WriteLine("\t{0}:\t{1}", key);
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 33
0
        private void button1_Click(object sender, EventArgs e)
        {
            string signatureAlgorithm = algtxt.Text;
            var    rsaGenerator       = new RsaKeyPairGenerator();
            var    randomGenerator    = new CryptoApiRandomGenerator();
            var    secureRandom       = new SecureRandom(randomGenerator);
            var    keyParameters      = new KeyGenerationParameters(secureRandom, 1024);

            rsaGenerator.Init(keyParameters);
            var keyPair    = rsaGenerator.GenerateKeyPair();
            var attributes = new System.Collections.Hashtable();

            attributes[X509Name.E]  = emailtxt.Text;  //设置dn信息的邮箱地址
            attributes[X509Name.CN] = towhomtxt.Text; //设置证书的用户,也就是颁发给谁
            attributes[X509Name.O]  = Issuertxt.Text; //设置证书的办法者
            attributes[X509Name.C]  = "Zh";           //证书的语言
            var ordering = new System.Collections.ArrayList();

            ordering.Add(X509Name.E);
            ordering.Add(X509Name.CN);
            ordering.Add(X509Name.O);
            ordering.Add(X509Name.C);
            var generater = new X509V3CertificateGenerator();

            //设置证书序列化号
            generater.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            //设置颁发者dn信息
            generater.SetIssuerDN(new X509Name(ordering, attributes));
            //设置证书生效时间
            generater.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
            //设置证书失效时间
            generater.SetNotAfter(DateTime.Today.AddDays(365));
            //设置接受者dn信息
            generater.SetSubjectDN(new X509Name(ordering, attributes));
            //设置证书的公钥
            generater.SetPublicKey(keyPair.Public);
            //设置证书的加密算法
            generater.SetSignatureAlgorithm(signatureAlgorithm);
            generater.AddExtension(X509Extensions.BasicConstraints,
                                   true,
                                   new BasicConstraints(false));
            generater.AddExtension(X509Extensions.AuthorityKeyIdentifier,
                                   true,
                                   new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public)));
            // Key usage: Client authentication
            generater.AddExtension(X509Extensions.ExtendedKeyUsage.Id,
                                   false,
                                   new ExtendedKeyUsage(new System.Collections.ArrayList()
            {
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.2")
            }));

            Castle = generater.Generate(keyPair.Private);
            var    store        = new Org.BouncyCastle.Pkcs.Pkcs12Store();
            string friendlyname = Castle.SubjectDN.ToString();
            var    ccentry      = new Org.BouncyCastle.Pkcs.X509CertificateEntry(Castle);

            store.SetCertificateEntry(friendlyname, ccentry);
            store.SetKeyEntry(friendlyname, new Org.BouncyCastle.Pkcs.AsymmetricKeyEntry(keyPair.Private), new[] { ccentry });

            certificate.Text = "-----BEGIN CERTIFICATE-----\r\n" + Convert.ToBase64String(Castle.GetEncoded()) + "\r\n-----END CERTIFICATE-----";

            string password = pswtxt.Text;

            Castlekey = keyPair.Private;
            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), secureRandom);
            nametxt.Text = Castle.IssuerDN.ToString();
            TextWriter textWriter = new StringWriter();
            PemWriter  pemWriter  = new PemWriter(textWriter);

            pemWriter.WriteObject(Castle.GetPublicKey());
            pemWriter.Writer.Flush();
            pubtxt.Text = textWriter.ToString();
            SaveFileDialog output = new SaveFileDialog();

            output.Filter           = "pfx file|*.pfx";
            output.RestoreDirectory = true;
            output.InitialDirectory = Environment.CurrentDirectory;
            output.FilterIndex      = 1;
            if (output.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllBytes(output.FileName, stream.ToArray());
            }
            else
            {
                MessageBox.Show("pfx证书不导出!");
            }
            output.Filter = "cer file|*.cer";
            if (output.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(output.FileName, certificate.Text);
            }
            else
            {
                MessageBox.Show("cer证书没导出!");
            }
        }