/// <summary>
        /// Return an  array of attributes matching the passed in type OID.
        /// </summary>
        /// <param name="type">The type of the attribute being looked for.</param>
        /// <returns>An array of Attribute of the requested type, zero length if none present.</returns>
        public AttributePkcs[] GetAttributes(DerObjectIdentifier type)
        {
            Asn1Set attrSet = certificationRequest.GetCertificationRequestInfo().Attributes;

            if (attrSet == null)
            {
                return(EMPTY_ARRAY);
            }

            IList list = Platform.CreateArrayList();

            for (int i = 0; i != attrSet.Count; i++)
            {
                AttributePkcs attr = AttributePkcs.GetInstance(attrSet[i]);
                if (attr.AttrType.Equals(type))
                {
                    list.Add(attr);
                }
            }

            if (list.Count == 0)
            {
                return(EMPTY_ARRAY);
            }

            AttributePkcs[] attrs = new AttributePkcs[list.Count];

            for (int i = 0; i != attrs.Length; i++)
            {
                attrs[i] = (AttributePkcs)list[i];
            }
            return(attrs);
        }
예제 #2
0
        private string attributeString()
        {
            string value = "";

            foreach (object entry in Attributes)
            {
                AttributePkcs attrib = AttributePkcs.GetInstance(entry);
                value = value + "OID :";
            }

            return(value);
        }
        /// <summary>
        /// Call to request a certificate
        /// </summary>
        /// <param name="csr">Certificate signing request</param>
        /// <param name="effectiveDate">Effective date of certificate</param>
        /// <param name="expirationDate">Expiration date of certificate</param>
        /// <param name="ca">Signing authority</param>
        /// <param name="asn1Set">Extensions</param>
        /// <exception cref="InvalidParameterException">Thrown if <paramref name="ca"/> is null</exception>
        /// <returns>Certificate signed by <paramref name="ca"/></returns>
        public static X509Certificate2 RequestCertificate(Pkcs10CertificationRequest csr, DateTime effectiveDate, DateTime expirationDate, X509Certificate2 ca, Asn1Set asn1Set)
        {
            AsymmetricKeyParameter keyParameter = null;

            if (ca == null)
            {
                throw new InvalidParameterException("ca can not be null");
            }

            keyParameter = TransformRSAPrivateKey((RSACryptoServiceProvider)ca.PrivateKey);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(CreateSerialNumber());
            certGen.SetIssuerDN(new X509Name(ca.Subject));
            certGen.SetNotBefore(effectiveDate.ToUniversalTime());
            certGen.SetNotAfter(expirationDate.ToUniversalTime());
            certGen.SetSubjectDN(csr.GetCertificationRequestInfo().Subject);
            certGen.SetPublicKey(csr.GetPublicKey());
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            if (asn1Set != null)
            {
                // Iterate through each extension and add it to the certificate
                for (int i = 0; i < asn1Set.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(asn1Set[i]);

                    if (attr != null && attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions = X509Extensions.GetInstance(attr.AttrValues[0]);

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

                            certGen.AddExtension(extOid, ext.IsCritical, ext.GetParsedValue());
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(keyParameter);

            return(new X509Certificate2(bcCert.GetEncoded()));
        }
        /// <summary>
        /// Generate an PKCS#10 request based on the past in signer.
        /// </summary>
        /// <param name="signerFactory">the content signer to be used to generate the signature validating the certificate.</param>
        /// <returns>a holder containing the resulting PKCS#10 certification request.</returns>
        public Pkcs10CertificationRequest Build(
            ISignatureFactory <AlgorithmIdentifier> signerFactory)
        {
            CertificationRequestInfo info;

            if (attributes.Count == 0)
            {
                if (leaveOffEmpty)
                {
                    info = new CertificationRequestInfo(subject, publicKeyInfo, null);
                }
                else
                {
                    info = new CertificationRequestInfo(subject, publicKeyInfo, new DerSet());
                }
            }
            else
            {
                Asn1EncodableVector v = new Asn1EncodableVector();

                for (int i = 0; i != attributes.Count; i++)
                {
                    v.Add(AttributePkcs.GetInstance(attributes[i]));
                }

                info = new CertificationRequestInfo(subject, publicKeyInfo, new DerSet(v));
            }

            try
            {
                IStreamCalculator <IBlockResult> signer = signerFactory.CreateCalculator();

                Stream sOut = signer.Stream;

                byte[] data = info.GetEncoded(Asn1Encodable.Der);

                sOut.Write(data, 0, data.Length);

                sOut.Close();

                return(new Pkcs10CertificationRequest(new CertificationRequest(info, signerFactory.AlgorithmDetails, new DerBitString(signer.GetResult().Collect()))));
            }
            catch (IOException e)
            {
                throw new InvalidOperationException("cannot produce certification request signature: " + e.Message, e);
            }
        }
예제 #5
0
        public AttributePkcs[] GetAttributes()
        {
            Asn1Set attrs = safeBag.BagAttributes;

            if (attrs == null)
            {
                return(null);
            }

            AttributePkcs[] attributes = new AttributePkcs[attrs.Count];
            for (int i = 0; i != attrs.Count; i++)
            {
                attributes[i] = AttributePkcs.GetInstance(attrs[i]);
            }

            return(attributes);
        }
        /// <summary>
        /// Return the attributes, if any associated with this request.
        /// </summary>
        /// <returns>An array of Attribute, zero length if none present.</returns>
        public AttributePkcs[] GetAttributes()
        {
            Asn1Set attrSet = certificationRequest.GetCertificationRequestInfo().Attributes;

            if (attrSet == null)
            {
                return(EMPTY_ARRAY);
            }

            AttributePkcs[] attrs = new AttributePkcs[attrSet.Count];

            for (int i = 0; i != attrSet.Count; i++)
            {
                attrs[i] = AttributePkcs.GetInstance(attrSet[i]);
            }

            return(attrs);
        }
예제 #7
0
        /// <summary>
        /// Get an X509Extensions object containing all extensions from the request
        /// </summary>
        /// <returns>List of extension (or null)</returns>
        private X509Extensions getExtensions()
        {
            if (Attributes == null)
            {
                return(null);
            }

            DerObjectIdentifier ExtensionsOid = new DerObjectIdentifier("1.2.840.113549.1.9.14");

            // Iterate over the Attributes
            foreach (object entry in Attributes)
            {
                AttributePkcs attrib = AttributePkcs.GetInstance(entry);
                // Find the Attribute entry that has extensions in it
                if (ExtensionsOid.Equals(attrib.AttrType))
                {
                    X509ExtensionsGenerator gen = new X509ExtensionsGenerator();
                    bool critical;
                    foreach (DerSequence outer in attrib.AttrValues)
                    {
                        foreach (DerSequence inner in outer)
                        {
                            // Note that the extension value is wrapped in an OctetString, but the generator expects an unwrapped value
                            if (inner.Count == 3)                        // Critical flag set
                            {
                                critical = isTrue((DerBoolean)inner[1]); // Just in case it is false
                                gen.AddExtension((DerObjectIdentifier)inner[0], critical, ((DerOctetString)inner[2]).GetOctets());
                            }
                            else                       // Count==2; Critical flag not set
                            {
                                gen.AddExtension((DerObjectIdentifier)inner[0], false, ((DerOctetString)inner[1]).GetOctets());
                            }
                        }
                    }
                    return(gen.Generate());
                }
            }
            return(null);
        }
예제 #8
0
        private void readRequest(bool verify)
        {
            // Perform POP on the request
            if ((verify) && (!Request.Verify()))
            {
                throw new SignatureException("Invalid signature on PKCS#10 request");
            }

            // Contents
            info = Request.GetCertificationRequestInfo();

            // Attributes - if there are no attributes in the request then info.Attributes will be null and cause an
            // exception in the following foreach; attributes should be null if there aren't any.
            if (info.Attributes != null)
            {
                attributes = new Dictionary <DerObjectIdentifier, Asn1Set>();
                foreach (object entry in info.Attributes)
                {
                    AttributePkcs attrib = AttributePkcs.GetInstance(entry);
                    attributes.Add(attrib.AttrType, attrib.AttrValues);
                }
            }
            else
            {
                attributes = null;
            }

            // Extensions in OSCA format
            // Make sure there are some extensions first
            if (Extensions != null)
            {
                foreach (DerObjectIdentifier oid in Extensions.ExtensionOids)
                {
                    oscaExtensions.Add(ProfileExtensionFactory.GetExtension(oid, Extensions.GetExtension(oid)));
                }
            }
        }
예제 #9
0
        private void readRequest()
        {
            // Perform POP on the request
            if (!request.Verify())
            {
                throw new SignatureException("Invalid signature on PKCS#10 request");
            }

            // Contents
            info = request.GetCertificationRequestInfo();

            // Extensions in OSCA format
            foreach (DerObjectIdentifier oid in Extensions.ExtensionOids)
            {
                oscaExtensions.Add(ProfileExtensionFactory.GetExtension(oid, Extensions.GetExtension(oid)));
            }

            // Attributes
            foreach (object entry in Attributes)
            {
                AttributePkcs attrib = AttributePkcs.GetInstance(entry);
                attributes.Add(attrib.AttrType, attrib.AttrValues);
            }
        }
예제 #10
0
        /// <summary>
        /// Enroll certificate file base on request
        /// </summary>
        /// <param name="cerRequest"></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 cerRequest,
            Org.BouncyCastle.X509.X509Certificate rootCert,
            AsymmetricCipherKeyPair issuerKeyPair,
            DateTime startDate, DateTime endDate)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(rootCert.SubjectDN);
            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(endDate);

            CertificationRequestInfo info = cerRequest.GetCertificationRequestInfo();

            certGen.SetSubjectDN(info.Subject);

            certGen.SetPublicKey(cerRequest.GetPublicKey());

            AlgorithmIdentifier sigAlg = cerRequest.SignatureAlgorithm;
            string algName             = GetAlgorithmName(sigAlg.Algorithm.Id);

            certGen.SetSignatureAlgorithm(algName);

            // Add certificate extensions
            Asn1Set attributes = cerRequest.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);
                            certGen.AddExtension(oid, ext.IsCritical, ext.GetParsedValue());
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate issuedCert = null;
            try
            {
                issuedCert = certGen.Generate(issuerKeyPair.Private);
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Certificate file sucessfully generated." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generate certificate file." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            try
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Check if generated certificate file is valid, plase wait ..." + "\n",
                        Foreground = System.Windows.Media.Brushes.Black
                    });
                }));
                issuedCert.CheckValidity(DateTime.UtcNow);
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Generate certificate file is valid." + "\n",
                        Foreground = System.Windows.Media.Brushes.Black
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generated certificate file is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            try
            {
                tbOutputMessageBox.Inlines.Add(new Run
                {
                    Text       = "Verify generated certificate file, plase wait ..." + "\n",
                    Foreground = System.Windows.Media.Brushes.Black
                });
                issuedCert.Verify(issuerKeyPair.Public);
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Generate certificate file verification is OK." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generated certificate file verification is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }
            return(issuedCert);
        }
예제 #11
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);
        }