/// <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); }
/// <summary> /// Creates a PKCS10 Certificate Signing Request (CSR) for the DeviceID key /// </summary> /// <param name="deviceID">Signing key</param> /// <param name="signingSeed">Seed for the signing BRBG</param> /// <returns>The CSR</returns> private static Pkcs10CertificationRequest CreateCsr(AsymmetricCipherKeyPair deviceID, byte[] signingSeed) { var random = GetDrbg(signingSeed, SeedUsage.CSR); ISignatureFactory signatureFactory = new Asn1SignatureFactory(rSigSch, deviceID.Private, random); // adapt extension request as needed IList oids = new ArrayList(); IList values = new ArrayList(); oids.Add(X509Extensions.BasicConstraints); values.Add(new X509Extension(true, new DerOctetString(new BasicConstraints(rPathLenConstraint)))); oids.Add(X509Extensions.KeyUsage); values.Add(new X509Extension(true, new DerOctetString(new KeyUsage(KeyUsage.KeyCertSign)))); AttributePkcs attribute = new AttributePkcs( PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(oids, values))); Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest( signatureFactory, rDeviceCertSubject, deviceID.Public, new DerSet(attribute), deviceID.Private); return(csr); }
private Pkcs10CertificationRequest GeneratePkcs10() { var x509 = new X509Name(attributes.Select(p => p.Item1).ToArray(), attributes.Select(p => p.Item2).ToArray()); if (this.SubjectAlternativeNames.Count == 0) { this.SubjectAlternativeNames.Add(commonName); } var altNames = this.SubjectAlternativeNames .Distinct() .Select(n => new GeneralName(GeneralName.DnsName, n)) .ToArray(); var extensions = new X509Extensions(new Dictionary <DerObjectIdentifier, X509Extension> { { X509Extensions.BasicConstraints, new X509Extension(false, new DerOctetString(new BasicConstraints(false))) }, { X509Extensions.KeyUsage, new X509Extension(false, new DerOctetString(new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment | KeyUsage.NonRepudiation))) }, { X509Extensions.SubjectAlternativeName, new X509Extension(false, new DerOctetString(new GeneralNames(altNames))) } }); var attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(extensions)); var signatureFactory = new Asn1SignatureFactory(this.Algorithm.ToPkcsObjectId(), this.KeyPair.Private); var csr = new Pkcs10CertificationRequest(signatureFactory, x509, KeyPair.Public, new DerSet(attribute), KeyPair.Private); var valid = csr.Verify(); if (!valid) { throw new Exception(); } return(csr); }
public X509ChallengePasswordAttribute(string password) : base() { Password = password ?? throw new ArgumentNullException(nameof(password)); var attr = new AttributePkcs(new DerObjectIdentifier(OidAttributes.СhallengePassword), new DerSet(new DerUtf8String(Password))); Import(attr.GetDerEncoded()); }
private DerSet AddPasswordAttribute(string password, Asn1Set attributes) { if (attributes == null) { attributes = new DerSet(); } List <AttributePkcs> attributesPkcs = attributes .OfType <DerSequence>() .Select(AttributePkcs.GetInstance) .ToList(); bool hasPassword = attributesPkcs.Any(x => x.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtChallengePassword)); if (hasPassword) { throw new Exception("Cannot append password, already has password attribute in CSR."); } AttributePkcs passwordAttribute = ChallengePasswordAttribute(password); attributesPkcs.Add(passwordAttribute); // ReSharper disable once CoVariantArrayConversion DerSet attributesSet = new DerSet(attributesPkcs.ToArray()); return(attributesSet); }
// previous code found to cause a NullPointerException private void nullPointerTest() { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); AsymmetricCipherKeyPair pair = keyGen.GenerateKeyPair(); IList oids = new ArrayList(); IList values = new ArrayList(); oids.Add(X509Extensions.BasicConstraints); values.Add(new X509Extension(true, new DerOctetString(new BasicConstraints(true)))); oids.Add(X509Extensions.KeyUsage); values.Add(new X509Extension(true, new DerOctetString( new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign)))); SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pair.Public); X509Extension ski = new X509Extension(false, new DerOctetString(subjectKeyIdentifier)); oids.Add(X509Extensions.SubjectKeyIdentifier); values.Add(ski); AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(oids, values))); Pkcs10CertificationRequest p1 = new Pkcs10CertificationRequest( "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private); Pkcs10CertificationRequest p2 = new Pkcs10CertificationRequest( "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private); if (!p1.Equals(p2)) { Fail("cert request comparison failed"); } }
private static string CreateCertificateSigningRequest(Session session, string ckaLabel, byte[] ckaId, int defaultBits, string directDomain, string distinguishedName, int keyUsage) { // Generate key pair - Signing ObjectHandle publicKeyHandle; ObjectHandle privateKeyHandle; Pkcs11Util.GenerateKeyPair(session, ckaLabel, ckaId, out publicKeyHandle, out privateKeyHandle, defaultBits); // Generate x509 attributes for csr IList oids = new ArrayList(); IList values = new ArrayList(); oids.Add(X509Extensions.BasicConstraints); values.Add(new X509Extension( true, new DerOctetString(new BasicConstraints(true)))); oids.Add(X509Extensions.KeyUsage); values.Add(new X509Extension( true, new DerOctetString(new KeyUsage(keyUsage)))); if (directDomain.Contains("@")) { AddSubjectAltNameForRfc822Name(directDomain, oids, values); } else { AddSubjectAltNameForDnsName(directDomain, oids, values); } var attribute = new AttributePkcs( PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(oids, values))); var asn1Attributes = new DerSet(attribute); // Generate certificate request in PKCS#10 format byte[] pkcs10 = Pkcs11Util.GeneratePkcs10( session, publicKeyHandle, privateKeyHandle, distinguishedName, DigestAlgorithm.SHA256, asn1Attributes); //Export to Pem format. var sb = new StringBuilder(); var pemObject = new PemObject("CERTIFICATE REQUEST", pkcs10); using (var str = new StringWriter(sb)) { var pemWriter = new PemWriter(str); pemWriter.WriteObject(pemObject); } return(sb.ToString()); }
private static void GenerateBouncyCastleCertificate() { var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), new SecureRandom()); var date = DateTime.UtcNow.Date; var keyPair = GetKeyPair(); var subject = GetSubjectData(); var attributes = GetExtensions(keyPair.Public); var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.SetSerialNumber(serialNumber); certificateGenerator.SetSubjectDN(subject); certificateGenerator.SetIssuerDN(new X509Name("CN=XXX")); certificateGenerator.SetNotBefore(date); certificateGenerator.SetNotAfter(date.AddYears(2)); certificateGenerator.SetPublicKey(keyPair.Public); foreach (var attribute in attributes) { certificateGenerator.AddExtension(attribute.Id, attribute.Critical, attribute.Value); } var factory = new Asn1SignatureFactory(SignatureAlgorithm, keyPair.Private); var bcCertificate = certificateGenerator.Generate(factory); SavePrivateKey((ECPrivateKeyParameters)keyPair.Private); SaveCertificate(bcCertificate); IList oids = new ArrayList(); IList values = new ArrayList(); foreach (var attribute in attributes) { oids.Add(attribute.Id); values.Add(new X509Extension(attribute.Critical, new DerOctetString(attribute.Value.GetDerEncoded()))); } var extensions = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(oids, values))); var request = new Pkcs10CertificationRequest(SignatureAlgorithm, subject, keyPair.Public, new DerSet(extensions), keyPair.Private); /* Есть 2 стула... */ /* Первый - можно просто оформить чистый запрос на сертификат PKCS#10 * В нем не будет никаких других подписей, он максимально простой * и по сути в нем есть все необходимое чтобы потом подписывать документы, если банк его "примет" */ SavePkcs10Data(request); /* Второй - если в обязательном порядке нужен "заверенный" сертификат PKCS#7 * Для этого его нужно подписать другим сертификатом выданным от "сертифицированного СКЗИ" * Соответственно нужен сам сертификат (преобразованный в Bouncy Castle) + приватный ключ для подписи * С первым понятно откуда брать, а вот как вы "вытащите" приватный ключ... я не смог =) * Но код на всякий случай оставил тут * SavePkcs7Data(certificateForSign, request, PrivateKeyForSign); */ }
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())); }
public static AttributePkcs GetInstance(object obj) { AttributePkcs attributePkcs = obj as AttributePkcs; if (obj == null || attributePkcs != null) { return(attributePkcs); } Asn1Sequence asn1Sequence = obj as Asn1Sequence; if (asn1Sequence != null) { return(new AttributePkcs(asn1Sequence)); } throw new ArgumentException("Unknown object in factory: " + Platform.GetTypeName(obj), "obj"); }
/// <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); } }
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); }
/// <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); }
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))); } } }
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); } }
public Csr(PrivKey priv, CertificateOptions options) { X509Name subject = options.GenerateName(); GeneralNames alt = options.GenerateAltNames(); X509Extension altName = new X509Extension(false, new DerOctetString(alt)); List <object> oids = new List <object>() { X509Extensions.SubjectAlternativeName, }; List <object> values = new List <object>() { altName, }; X509Extensions x509exts = new X509Extensions(oids, values); X509Attribute attr = new X509Attribute(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest.Id, new DerSet(x509exts)); AttributePkcs attr2 = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(x509exts)); this.Request = new Pkcs10CertificationRequest(new Asn1SignatureFactory(options.GetSignatureAlgorithmOid(), priv.PrivateKeyData.Private, PkiUtil.NewSecureRandom()), subject, priv.PublicKey.PublicKeyData, new DerSet(attr2)); }
/// <summary> /// Creates a certificate signing request from an existing certificate. /// </summary> public static byte[] CreateSigningRequest( X509Certificate2 certificate, IList <String> domainNames = null ) { using (var cfrg = new CertificateFactoryRandomGenerator()) { SecureRandom random = new SecureRandom(cfrg); // try to get signing/private key from certificate passed in AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certificate); RsaKeyParameters publicKey = GetPublicKeyParameter(certificate); ISignatureFactory signatureFactory = new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random); Asn1Set attributes = null; X509SubjectAltNameExtension alternateName = null; foreach (System.Security.Cryptography.X509Certificates.X509Extension extension in certificate.Extensions) { if (extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltNameOid || extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltName2Oid) { alternateName = new X509SubjectAltNameExtension(extension, extension.Critical); break; } } domainNames = domainNames ?? new List <String>(); if (alternateName != null) { foreach (var name in alternateName.DomainNames) { if (!domainNames.Any(s => s.Equals(name, StringComparison.OrdinalIgnoreCase))) { domainNames.Add(name); } } foreach (var ipAddress in alternateName.IPAddresses) { if (!domainNames.Any(s => s.Equals(ipAddress, StringComparison.OrdinalIgnoreCase))) { domainNames.Add(ipAddress); } } } if (domainNames.Count > 0) { List <GeneralName> generalNames = CreateSubjectAlternateNameDomains(domainNames); if (generalNames.Count > 0) { IList oids = new ArrayList(); IList values = new ArrayList(); oids.Add(X509Extensions.SubjectAlternativeName); values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(new GeneralNames(generalNames.ToArray()).GetDerEncoded()))); AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(oids, values))); attributes = new DerSet(attribute); } } Pkcs10CertificationRequest pkcs10CertificationRequest = new Pkcs10CertificationRequest( signatureFactory, new CertificateFactoryX509Name(false, certificate.Subject), publicKey, attributes, signingKey); return(pkcs10CertificationRequest.GetEncoded()); } }
/// <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); }
/// <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); }
public X509EnrollmentNameValuePairAttribute(X509EnrollmentNameValuePairParams param) : base() { #region Sets propeties from param var seqList = new List <Asn1Encodable>(); if (param.CertificateTemplate != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.CertificateTemplate.ToString(), param.CertificateTemplate)); } if (param.CDC != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.CDC.ToString(), param.CDC)); } if (param.CertFile != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.CertFile.ToString(), param.CertFile)); } if (param.CertificateUsage != null) { string oidString = string.Join(", ", new List <Oid>(param.CertificateUsage).ConvertAll(i => i.Value.ToString()).ToArray()); seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.CertificateUsage.ToString(), oidString)); } if (param.CertType != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.CertType.ToString(), param.CertType.Value.ToString())); } if (param.Challenge != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.Challenge.ToString(), param.Challenge)); } if (param.ExpirationDate != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.ExpirationDate.ToString(), param.ExpirationDate.Value.ToString())); } if (param.Other != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.Other.ToString(), param.Other)); } if (param.RequesterName != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.RequesterName.ToString(), param.RequesterName)); } if (param.RequestId != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.RequestId.ToString(), param.RequestId.Value.ToString())); } if (param.RMD != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.RMD.ToString(), param.RMD)); } if (param.SAN != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.SAN.ToString(), param.SAN)); } if (param.ValidityPeriod != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.ValidityPeriod.ToString(), param.ValidityPeriod.Value.ToString())); } if (param.ValidityPeriodUnits != null) { seqList.Add(CreateSequence(EnrollmentNameValuePairsEnum.ValidityPeriodUnits.ToString(), param.ValidityPeriodUnits.Value.ToString())); } #endregion var attr = new AttributePkcs(new DerObjectIdentifier(OidAttributes.EnrollmentNameValuePair), new DerSet(seqList.ToArray())); Import(attr.GetDerEncoded()); }