Esempio n. 1
0
        public static X509Certificate2 GenerateCACertificate(
            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(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            certificateGenerator.SetSubjectAndIssuer(subjectName);

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

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

            // Generate KeyPair
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

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

            // Generate Signature Factory
            ISignatureFactory sigFact = new Asn1SignatureFactory(
                SignatureAlgorithm, keyPair.Private);

            // Set extensions
            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints,
                true,
                new BasicConstraints(true));
            var ski = new SubjectKeyIdentifier(
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                    keyPair.Public));

            certificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier, false, ski);

            // Add Public Key
            certificateGenerator.SetPublicKey(keyPair.Public);

            // Generating the BC Certificate
            var certificate = certificateGenerator.Generate(sigFact);

            // Add Private key (and convert to X509Certificate2)
            var x509 = GenerateX509WithPrivateKey(
                keyPair, certificate);

            return(x509);
        }