示例#1
0
        public static void ExportArchive(CertPrivateKey pk, IEnumerable <BcCertificate> certs,
                                         ArchiveFormat fmt, Stream target, string password = null)
        {
            if (fmt == ArchiveFormat.PKCS12)
            {
                var bcCerts = certs.Select(x =>
                                           new X509CertificateEntry(x)).ToArray();
                var pfx = new Pkcs12Store();
                pfx.SetCertificateEntry(bcCerts[0].Certificate.SubjectDN.ToString(), bcCerts[0]);
                pfx.SetKeyEntry(bcCerts[0].Certificate.SubjectDN.ToString(),
                                new AsymmetricKeyEntry(pk.KeyPair.Private), new[] { bcCerts[0] });

                for (int i = 1; i < bcCerts.Length; ++i)
                {
                    //pfx.SetCertificateEntry(bcCerts[i].Certificate.SubjectDN.ToString(),
                    pfx.SetCertificateEntry(i.ToString(), bcCerts[i]);
                }

                // It used to be pretty straight forward to export this...
                pfx.Save(target, password?.ToCharArray(), new SecureRandom());
            }
            else
            {
                throw new NotSupportedException("unsupported archive format");
            }
        }
示例#2
0
        ToDotNetCert(CertPrivateKey key, BcCertificate certificate)
        {
            // merge into X509Certificate2

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

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

#pragma warning disable CS0618 // Type or member is obsolete
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
#pragma warning restore CS0618 // Type or member is obsolete
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

#pragma warning disable CS0618 // Type or member is obsolete
            var rsa = new RsaPrivateKeyStructure(seq);
#pragma warning restore CS0618 // Type or member is obsolete
            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);
        }
示例#3
0
        public static (CertPrivateKey, BcCertificate) GenerateRsaSelfSignedCertificate(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";

#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  = new X509Name(issuerName);
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.AddMonths(-1).Date;
            var notAfter  = DateTime.UtcNow.AddMonths(1).Date;

            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(issuerPrivKey, random);
#pragma warning restore CS0618 // Type or member is obsolete

            var key = new CertPrivateKey
            {
                KeyPair = subjectKeyPair,
            };
            return(key, certificate);
        }
示例#4
0
        public static byte[] GenerateEcCsr(IEnumerable <string> names,
                                           CertPrivateKey pk, SysHashAlgorName?hashAlgor = null)
        {
            if (hashAlgor == null)
            {
                hashAlgor = SysHashAlgorName.SHA256;
            }

            var attrs = new Dictionary <DerObjectIdentifier, string>
            {
                [X509Name.CN] = names.First(),
            };
            var subj = new X509Name(attrs.Keys.ToList(), attrs.Values.ToList());

            var ackp = pk.KeyPair;

            var sigAlg   = $"{hashAlgor.Value.Name}withECDSA";
            var csrAttrs = new List <Asn1Encodable>();

            var gnames = new List <GeneralName>(
                names.Select(x => new GeneralName(GeneralName.DnsName, x)));

            var altNames = new GeneralNames(gnames.ToArray());

#pragma warning disable CS0612 // Type or member is obsolete
            var x509Ext = new X509Extensions(new Hashtable
            {
                [X509Extensions.SubjectAlternativeName] = new X509Extension(
                    false, new DerOctetString(altNames))
            });
#pragma warning restore CS0612 // Type or member is obsolete

            csrAttrs.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(
                             PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                             new DerSet(x509Ext)));

#pragma warning disable CS0618 // Type or member is obsolete
            var csr = new Pkcs10CertificationRequest(sigAlg,
                                                     subj, ackp.Public, new DerSet(csrAttrs.ToArray()), ackp.Private);
#pragma warning restore CS0618 // Type or member is obsolete

            return(csr.GetDerEncoded());
        }
示例#5
0
        public static void ExportPrivateKey(CertPrivateKey pk, EncodingFormat fmt, Stream target)
        {
            switch (fmt)
            {
            case EncodingFormat.PEM:
                var pem   = ToPrivatePem(pk.KeyPair);
                var bytes = Encoding.UTF8.GetBytes(pem);
                target.Write(bytes, 0, bytes.Length);
                break;

            case EncodingFormat.DER:
                var der = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pk.KeyPair.Private).GetDerEncoded();
                target.Write(der, 0, der.Length);
                break;

            default:
                throw new NotSupportedException("unsupported encoding format");
            }
        }
示例#6
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);
        }