private bool MatchesDN( X500Name subject, GeneralNames targets) { GeneralName[] names = targets.GetNames(); for (int i = 0; i != names.Length; i++) { GeneralName gn = names[i]; if (gn.TagNo == GeneralName.DirectoryName) { try { if (X500Name.GetInstance(gn.Name).Equivalent(subject)) { return(true); } } catch (Exception) { } } } return(false); }
protected virtual ICollection GetAlternativeNames( string oid) { Asn1OctetString altNames = GetExtensionValue(new DerObjectIdentifier(oid)); if (altNames == null) { return(null); } Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(altNames); GeneralNames gns = GeneralNames.GetInstance(asn1Object); IList result = Platform.CreateArrayList(); foreach (GeneralName gn in gns.GetNames()) { IList entry = Platform.CreateArrayList(); entry.Add(gn.TagNo); entry.Add(gn.Name.ToString()); result.Add(entry); } return(result); }
// Certificate Revocation Lists /** * Gets the URL of the Certificate Revocation List for a Certificate * @param certificate the Certificate * @return the String where you can check if the certificate was revoked * @throws CertificateParsingException * @throws IOException */ public static String GetCRLURL(X509Certificate certificate) { try { Asn1Object obj = GetExtensionValue(certificate, X509Extensions.CrlDistributionPoints.Id); if (obj == null) { return(null); } CrlDistPoint dist = CrlDistPoint.GetInstance(obj); DistributionPoint[] dists = dist.GetDistributionPoints(); foreach (DistributionPoint p in dists) { DistributionPointName distributionPointName = p.DistributionPointName; if (DistributionPointName.FullName != distributionPointName.PointType) { continue; } GeneralNames generalNames = (GeneralNames)distributionPointName.Name; GeneralName[] names = generalNames.GetNames(); foreach (GeneralName name in names) { if (name.TagNo != GeneralName.UniformResourceIdentifier) { continue; } DerIA5String derStr = DerIA5String.GetInstance((Asn1TaggedObject)name.ToAsn1Object(), false); return(derStr.GetString()); } } } catch { } return(null); }
private X509Name[] GetPrincipals( GeneralNames names) { object[] p = this.GetNames(names.GetNames()); int count = 0; for (int i = 0; i != p.Length; i++) { if (p[i] is X509Name) { ++count; } } X509Name[] result = new X509Name[count]; int pos = 0; for (int i = 0; i != p.Length; i++) { if (p[i] is X509Name) { result[pos++] = (X509Name)p[i]; } } return(result); }
private object[] GetNames() { GeneralNames generalNames = (!(form is V2Form)) ? ((GeneralNames)form) : ((V2Form)form).IssuerName; GeneralName[] names = generalNames.GetNames(); int num = 0; for (int i = 0; i != names.Length; i++) { if (names[i].TagNo == 4) { num++; } } object[] array = new object[num]; int num2 = 0; for (int j = 0; j != names.Length; j++) { if (names[j].TagNo == 4) { array[num2++] = X509Name.GetInstance(names[j].Name); } } return(array); }
/// <summary> /// Decodes the specified value. /// </summary> /// <param name="value">The value.</param> protected void decode(GeneralNames value) { GeneralName[] gnList = value.GetNames(); foreach (GeneralName gn in gnList) { genNames.Add(new OSCAGeneralName(gn)); } }
public string[] GetRoleAuthorityAsString() { if (roleAuthority == null) { return(new string[0]); } GeneralName[] names = roleAuthority.GetNames(); string[] array = new string[names.Length]; for (int i = 0; i < names.Length; i++) { Asn1Encodable name = names[i].Name; if (name is IAsn1String) { array[i] = ((IAsn1String)name).GetString(); } else { array[i] = name.ToString(); } } return(array); }
private X509Name[] GetPrincipals( GeneralNames names) { object[] p = this.GetNames(names.GetNames()); ArrayList l = new ArrayList(p.Length); for (int i = 0; i != p.Length; i++) { if (p[i] is X509Name) { l.Add(p[i]); } } return((X509Name[])l.ToArray(typeof(X509Name))); }
protected virtual ICollection GetAlternativeNames(string oid) { Asn1OctetString extensionValue = this.GetExtensionValue(new DerObjectIdentifier(oid)); if (extensionValue == null) { return(null); } GeneralNames instance = GeneralNames.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue)); IList list = Platform.CreateArrayList(); foreach (GeneralName name in instance.GetNames()) { IList list2 = Platform.CreateArrayList(); list2.Add(name.TagNo); list2.Add(name.Name.ToString()); list.Add(list2); } return(list); }
/// <inheritdoc /> public override void InjectReferenceValue(X509Certificate2 value) { Certificate = value; Asn1Object exValue = GetExtensionValue(value); if (exValue == null) { if (IsRequired()) { throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present."); } var emptyList = new List <string>(); PolicyValue = new PolicyValue <IList <string> >(emptyList); return; } CrlDistPoint distPoints = CrlDistPoint.GetInstance(exValue); IList <String> retVal = new List <String>(); foreach (var distPoint in distPoints.GetDistributionPoints()) { if (distPoint.DistributionPointName != null && distPoint.DistributionPointName.PointType == DistributionPointName.FullName) { GeneralNames names = GeneralNames.GetInstance(distPoint.DistributionPointName.Name); foreach (var generalName in names.GetNames()) { retVal.Add(generalName.Name.ToString()); } } } if (!retVal.Any() && IsRequired()) { throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present."); } PolicyValue = new PolicyValue <IList <string> >(retVal); }
protected virtual global::System.Collections.ICollection GetAlternativeNames(string oid) { Asn1OctetString extensionValue = GetExtensionValue(new DerObjectIdentifier(oid)); if (extensionValue == null) { return(null); } Asn1Object obj = X509ExtensionUtilities.FromExtensionValue(extensionValue); GeneralNames instance = GeneralNames.GetInstance(obj); global::System.Collections.IList list = Platform.CreateArrayList(); GeneralName[] names = instance.GetNames(); foreach (GeneralName generalName in names) { global::System.Collections.IList list2 = Platform.CreateArrayList(); list2.Add((object)generalName.TagNo); list2.Add((object)((object)generalName.Name).ToString()); list.Add((object)list2); } return((global::System.Collections.ICollection)list); }
// Certificate Revocation Lists /** * Gets the URL of the Certificate Revocation List for a Certificate * @param certificate the Certificate * @return the String where you can check if the certificate was revoked * @throws CertificateParsingException * @throws IOException */ public static String GetCRLURL(X509Certificate certificate) { try { Asn1Object obj = GetExtensionValue(certificate, X509Extensions.CrlDistributionPoints.Id); if (obj == null) { return(null); } CrlDistPoint dist = CrlDistPoint.GetInstance(obj); DistributionPoint[] dists = dist.GetDistributionPoints(); foreach (DistributionPoint p in dists) { DistributionPointName distributionPointName = p.DistributionPointName; if (DistributionPointName.FullName != distributionPointName.PointType) { continue; } GeneralNames generalNames = (GeneralNames)distributionPointName.Name; GeneralName[] names = generalNames.GetNames(); foreach (GeneralName name in names) { if (name.TagNo != GeneralName.UniformResourceIdentifier) { continue; } DerIA5String derStr = DerIA5String.GetInstance((Asn1TaggedObject)name.ToAsn1Object(), false); //return derStr.GetString(); //jbonilla - El URL del CRL para el BCE está en la tercera posición y solo se puede acceder desde HTTP. string urlCrl = derStr.GetString(); if (urlCrl.ToUpperInvariant().StartsWith("HTTP") && urlCrl.ToUpperInvariant().Contains("CRL")) { return(derStr.GetString()); } } } } catch { } return(null); }
private bool MatchesDN(X509Name subject, GeneralNames targets) { GeneralName[] names = targets.GetNames(); for (int num = 0; num != names.Length; num++) { GeneralName generalName = names[num]; if (generalName.TagNo == 4) { try { if (X509Name.GetInstance(generalName.Name).Equivalent(subject)) { return(true); } } catch (Exception) { } } } return(false); }
protected virtual ICollection GetAlternativeNames(string oid) { Asn1OctetString extensionValue = this.GetExtensionValue(new DerObjectIdentifier(oid)); if (extensionValue == null) { return(null); } Asn1Object obj = X509ExtensionUtilities.FromExtensionValue(extensionValue); GeneralNames instance = GeneralNames.GetInstance(obj); IList list = Platform.CreateArrayList(); GeneralName[] names = instance.GetNames(); for (int i = 0; i < names.Length; i++) { GeneralName generalName = names[i]; IList list2 = Platform.CreateArrayList(); list2.Add(generalName.TagNo); list2.Add(generalName.Name.ToString()); list.Add(list2); } return(list); }
private bool MatchesDN(X509Name subject, GeneralNames targets) { GeneralName[] names = targets.GetNames(); for (int i = 0; i != names.Length; i++) { GeneralName generalName = names[i]; if (generalName.TagNo != 4) { continue; } try { if (X509Name.GetInstance(generalName.Name).Equivalent(subject)) { return(true); } } catch (global::System.Exception) { } } return(false); }
private X509Name[] GetPrincipals(GeneralNames names) { object[] names2 = this.GetNames(names.GetNames()); int num = 0; for (int num2 = 0; num2 != names2.Length; num2++) { if (names2[num2] is X509Name) { num++; } } X509Name[] array = new X509Name[num]; int num3 = 0; for (int num4 = 0; num4 != names2.Length; num4++) { if (names2[num4] is X509Name) { array[num3++] = (X509Name)names2[num4]; } } return(array); }
private X509Name[] GetPrincipals(GeneralNames names) { object[] names2 = GetNames(names.GetNames()); int num = 0; for (int i = 0; i != names2.Length; i++) { if (names2[i] is X509Name) { num++; } } X509Name[] array = new X509Name[num]; int num2 = 0; for (int j = 0; j != names2.Length; j++) { if (names2[j] is X509Name) { array[num2++] = (X509Name)names2[j]; } } return(array); }
/// <summary> /// Gets a list of URLs from the specified certificate. /// </summary> /// <param name="cert">The certificate to find the URLs in.</param> /// <returns>A list of CRL URLs in the certificate</returns> public List <Uri> getCrlURLs(X509Certificate2 cert) { List <Uri> urls = new List <Uri>(); foreach (System.Security.Cryptography.X509Certificates.X509Extension extension in cert.Extensions) { if (extension.Oid.Value == X509Extensions.CrlDistributionPoints.Id) { // Retrieves the raw ASN1 data of the CRL Dist Points X509 extension, and wraps it in a container class CrlDistPoint crldp = CrlDistPoint.GetInstance(Asn1Object.FromByteArray(extension.RawData)); DistributionPoint[] distPoints = crldp.GetDistributionPoints(); foreach (DistributionPoint dp in crldp.GetDistributionPoints()) { // Only use the "General name" data in the distribution point entry. GeneralNames gns = (GeneralNames)dp.DistributionPointName.Name; foreach (GeneralName name in gns.GetNames()) { // Only retrieve URLs if (name.TagNo == GeneralName.UniformResourceIdentifier) { DerStringBase s = (DerStringBase)name.Name; urls.Add(new Uri(s.GetString())); } } } // There is only one CRL list so faster to break. break; } } return(urls); }
/// <inheritdoc/> public async Task <(X509Certificate Certificate, RsaKeyParameters Key)> GetLocalCertificateAsync(ApplicationDescription applicationDescription, ILogger logger = null) { string applicationUri = applicationDescription.ApplicationUri; if (string.IsNullOrEmpty(applicationUri)) { throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'."); } string subjectName = null; string hostName = null; string appName = null; UriBuilder appUri = new UriBuilder(applicationUri); if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host)) { var path = appUri.Path.Trim('/'); if (!string.IsNullOrEmpty(path)) { hostName = appUri.Host; appName = path; subjectName = $"CN={appName},DC={hostName}"; } } if (appUri.Scheme == "urn") { var parts = appUri.Path.Split(new[] { ':' }, 2); if (parts.Length == 2) { hostName = parts[0]; appName = parts[1]; subjectName = $"CN={appName},DC={hostName}"; } } if (subjectName == null) { throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'."); } var crt = default(X509Certificate); var key = default(RsaKeyParameters); // Build 'own/certs' certificate store. var ownCerts = new Org.BouncyCastle.Utilities.Collections.HashSet(); var ownCertsInfo = new DirectoryInfo(Path.Combine(this.pkiPath, "own", "certs")); if (ownCertsInfo.Exists) { foreach (var info in ownCertsInfo.EnumerateFiles()) { using (var crtStream = info.OpenRead()) { var c = this.certParser.ReadCertificate(crtStream); if (c != null) { ownCerts.Add(c); } } } } IX509Store ownCertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(ownCerts)); // Select the newest certificate that matches by subject name. var selector = new X509CertStoreSelector() { Subject = new X509Name(subjectName) }; crt = ownCertStore.GetMatches(selector).OfType <X509Certificate>().OrderBy(c => c.NotBefore).LastOrDefault(); if (crt != null) { // If certificate found, verify alt-name, and retrieve private key. var asn1OctetString = crt.GetExtensionValue(X509Extensions.SubjectAlternativeName); if (asn1OctetString != null) { var asn1Object = X509ExtensionUtilities.FromExtensionValue(asn1OctetString); GeneralNames gns = GeneralNames.GetInstance(asn1Object); if (gns.GetNames().Any(n => n.TagNo == GeneralName.UniformResourceIdentifier && n.Name.ToString() == applicationUri)) { var ki = new FileInfo(Path.Combine(this.pkiPath, "own", "private", $"{crt.SerialNumber}.key")); if (ki.Exists) { using (var keyStream = new StreamReader(ki.OpenRead())) { var keyReader = new PemReader(keyStream); var keyPair = keyReader.ReadObject() as AsymmetricCipherKeyPair; if (keyPair != null) { key = keyPair.Private as RsaKeyParameters; } } } } } } // If certificate and key are found, return to caller. if (crt != null && key != null) { logger?.LogTrace($"Found certificate with subject alt name '{applicationUri}'."); return(crt, key); } if (!this.CreateLocalCertificateIfNotExist) { return(null, null); } // Create new certificate var subjectDN = new X509Name(subjectName); // Create a keypair. var kp = await Task.Run <AsymmetricCipherKeyPair>(() => { RsaKeyPairGenerator kg = new RsaKeyPairGenerator(); kg.Init(new KeyGenerationParameters(this.rng, 2048)); return(kg.GenerateKeyPair()); }); key = kp.Private as RsaPrivateCrtKeyParameters; // Create a certificate. X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); var subjectSN = BigInteger.ProbablePrime(120, this.rng); cg.SetSerialNumber(subjectSN); cg.SetSubjectDN(subjectDN); cg.SetIssuerDN(subjectDN); cg.SetNotBefore(DateTime.Now.Date.ToUniversalTime()); cg.SetNotAfter(DateTime.Now.Date.ToUniversalTime().AddYears(25)); cg.SetPublicKey(kp.Public); cg.AddExtension( X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); cg.AddExtension( X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public))); cg.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subjectDN)), subjectSN)); cg.AddExtension( X509Extensions.SubjectAlternativeName, false, new GeneralNames(new[] { new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri), new GeneralName(GeneralName.DnsName, hostName) })); cg.AddExtension( X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment)); cg.AddExtension( X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth)); crt = cg.Generate(new Asn1SignatureFactory("SHA256WITHRSA", key, this.rng)); logger?.LogTrace($"Created certificate with subject alt name '{applicationUri}'."); var keyInfo = new FileInfo(Path.Combine(this.pkiPath, "own", "private", $"{crt.SerialNumber}.key")); if (!keyInfo.Directory.Exists) { Directory.CreateDirectory(keyInfo.DirectoryName); } else if (keyInfo.Exists) { keyInfo.Delete(); } using (var keystream = new StreamWriter(keyInfo.OpenWrite())) { var pemwriter = new PemWriter(keystream); pemwriter.WriteObject(key); } var crtInfo = new FileInfo(Path.Combine(this.pkiPath, "own", "certs", $"{crt.SerialNumber}.crt")); if (!crtInfo.Directory.Exists) { Directory.CreateDirectory(crtInfo.DirectoryName); } else if (crtInfo.Exists) { crtInfo.Delete(); } using (var crtstream = new StreamWriter(crtInfo.OpenWrite())) { var pemwriter = new PemWriter(crtstream); pemwriter.WriteObject(crt); } return(crt, key); }
/// <summary>Gives back the CRL URI meta-data found within the given X509 certificate. /// </summary> /// <remarks>Gives back the CRL URI meta-data found within the given X509 certificate. /// </remarks> /// <param name="certificate">the X509 certificate.</param> /// <returns>the CRL URI, or <code>null</code> if the extension is not present.</returns> /// <exception cref="System.UriFormatException">System.UriFormatException</exception> public virtual string GetCrlUri(X509Certificate certificate) { //byte[] crlDistributionPointsValue = certificate.GetExtensionValue(X509Extensions. // CrlDistributionPoints); Asn1OctetString crlDistributionPointsValue = certificate.GetExtensionValue(X509Extensions. CrlDistributionPoints); if (null == crlDistributionPointsValue) { return(null); } Asn1Sequence seq; try { DerOctetString oct; //oct = (DEROctetString)(new ASN1InputStream(new ByteArrayInputStream(crlDistributionPointsValue // )).ReadObject()); oct = (DerOctetString)crlDistributionPointsValue; seq = (Asn1Sequence) new Asn1InputStream(oct.GetOctets()).ReadObject(); } catch (IOException e) { throw new RuntimeException("IO error: " + e.Message, e); } CrlDistPoint distPoint = CrlDistPoint.GetInstance(seq); DistributionPoint[] distributionPoints = distPoint.GetDistributionPoints(); foreach (DistributionPoint distributionPoint in distributionPoints) { DistributionPointName distributionPointName = distributionPoint.DistributionPointName; if (DistributionPointName.FullName != distributionPointName.PointType) { continue; } GeneralNames generalNames = (GeneralNames)distributionPointName.Name; GeneralName[] names = generalNames.GetNames(); foreach (GeneralName name in names) { if (name.TagNo != GeneralName.UniformResourceIdentifier) { LOG.Info("not a uniform resource identifier"); continue; } string str = null; if (name.ToAsn1Object() is DerTaggedObject) { DerTaggedObject taggedObject = (DerTaggedObject)name.ToAsn1Object(); DerIA5String derStr = DerIA5String.GetInstance(taggedObject.GetObject()); str = derStr.GetString(); } else { DerIA5String derStr = DerIA5String.GetInstance(name.ToAsn1Object()); str = derStr.GetString(); } if (str != null && (str.StartsWith("http://") || str.StartsWith("https://")) && str.ToUpperInvariant().Contains("CRL")) //jbonilla - El URL del CRL para el BCE está en la tercera posición y solo se puede acceder desde HTTP. { return(str); } else { LOG.Info("Supports only http:// and https:// protocol for CRL"); } } } //jbonilla #region BCE if (certificate.SubjectDN.ToString() .Contains("AC BANCO CENTRAL DEL ECUADOR")) { return(this.IntermediateAcUrl); } #endregion return(null); }
static void Main(string[] args) { foreach (string s in args) { if (s.StartsWith("-out:")) { outputfile = s.Replace("-out:", ""); } if (s.StartsWith("-in:")) { certfile = s.Replace("-in:", ""); } } if (outputfile != "stdout") { str = new StreamWriter(outputfile, false); } System.Security.Cryptography.X509Certificates.X509Certificate2 cer = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certfile)); Al.Security.X509.X509Certificate CERT = Al.Security.Security.DotNetUtilities.FromX509Certificate(cer); Print("Certificate"); Print(" Data"); Print(" Version : " + cer.Version.ToString()); Print(" Valid : " + cer.Verify().ToString()); Print(" Serial Number:"); Print(" " + cer.SerialNumber); Print(" Signature Algorithm : "); Print(" " + cer.SignatureAlgorithm.FriendlyName); Print(" Issuer : " + cer.Issuer); Print(" Validity : "); Print(" Not Before : " + GetRFC822Date(cer.NotBefore)); Print(" Not After : " + GetRFC822Date(cer.NotAfter)); Print(" Subject : " + cer.Subject); Print(" Subject Public Key Info:"); Print(" Public Key Exchange Algorithm: " + cer.PublicKey.Key.KeyExchangeAlgorithm); Print(" Public Key: " + cer.PublicKey.Key.KeySize.ToString() + " bit"); Print(" Modulus:"); Print(cer.GetPublicKey(), " "); if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.RsaKeyParameters) { RsaKeyParameters rsa = (RsaKeyParameters)CERT.GetPublicKey(); Print(" Exponent:" + rsa.Exponent); } else if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.DsaKeyParameters) { DsaKeyParameters dsa = (DsaKeyParameters)CERT.GetPublicKey(); Print(" DSA Parameters:"); Print(" G:"); Print(" " + dsa.Parameters.G.ToString()); Print(" P:"); Print(" " + dsa.Parameters.P.ToString()); Print(" Q:"); Print(" " + dsa.Parameters.Q.ToString()); } // Extensions Print(" X509 Extensions"); string extab = " "; bool critical = true; foreach (string oid in CERT.GetCriticalExtensionOids()) { Print(" "); X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid)); if (oid == X509Extensions.BasicConstraints.Id) { BasicConstraints bc = BasicConstraints.GetInstance(ext); Print(extab + "Basic Constraints Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " CA:" + bc.IsCA().ToString()); if (bc.PathLenConstraint != null) { Print(extab + " Path Length:" + bc.PathLenConstraint.ToString()); } else { Print(extab + " Path Length:Null"); } } else if (oid == X509Extensions.KeyUsage.Id) { KeyUsage keyu = KeyUsage.GetInstance(ext); Print(extab + "Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Usages:" + keyu.ToString()); } else if (oid == X509Extensions.ExtendedKeyUsage.Id) { ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext); Print(extab + "Extended Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Extended Key Usages:"); foreach (DerObjectIdentifier id in keyu.GetAllUsages()) { Print(extab + " " + id.Id); } } else if (oid == X509Extensions.SubjectKeyIdentifier.Id) { SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext); Print(extab + "Subject Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.AuthorityKeyIdentifier.Id) { AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext); Print(extab + "Authority Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.SubjectAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Subject Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.IssuerAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Issuer Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.AuthorityInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Authority Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.SubjectInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Subject Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.CrlDistributionPoints.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); CrlDistPoint keyu = CrlDistPoint.GetInstance(asn1Object); Print(extab + "Crl Distribution Points Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Distribution Points:"); foreach (DistributionPoint acc in keyu.GetDistributionPoints()) { if (acc.Reasons != null) { Print(extab + " Reasons:" + acc.Reasons.GetString()); } else { Print(extab + " Reasons:Null"); } if (acc.CrlIssuer != null) { Print(extab + " Crl Issuer:"); foreach (GeneralName gen in acc.CrlIssuer.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + ": " + gen.Name); } } else { Print(extab + " Crl Issuer:Null"); } Print(extab + " Distribution Point Name:"); if (acc.DistributionPointName.PointType == DistributionPointName.FullName) { GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name); foreach (GeneralName gen in sgen.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else { Print(extab + " Not Supported by OCT"); } } } } critical = false; foreach (string oid in CERT.GetNonCriticalExtensionOids()) { Print(" "); X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid)); if (oid == X509Extensions.BasicConstraints.Id) { BasicConstraints bc = BasicConstraints.GetInstance(ext); Print(extab + "Basic Constraints Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " CA:" + bc.IsCA().ToString()); if (bc.PathLenConstraint != null) { Print(extab + " Path Length:" + bc.PathLenConstraint.ToString()); } else { Print(extab + " Path Length:Null"); } } else if (oid == X509Extensions.KeyUsage.Id) { KeyUsage keyu = KeyUsage.GetInstance(ext); Print(extab + "Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Usages:" + keyu.ToString()); } else if (oid == X509Extensions.ExtendedKeyUsage.Id) { ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext); Print(extab + "Extended Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Extended Key Usages:"); foreach (DerObjectIdentifier id in keyu.GetAllUsages()) { Print(extab + " " + id.Id); } } else if (oid == X509Extensions.SubjectKeyIdentifier.Id) { SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext); Print(extab + "Subject Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.AuthorityKeyIdentifier.Id) { AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext); Print(extab + "Authority Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.SubjectAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Subject Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.IssuerAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Issuer Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.AuthorityInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Authority Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.SubjectInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Subject Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.CrlDistributionPoints.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); CrlDistPoint keyu = CrlDistPoint.GetInstance(asn1Object); Print(extab + "Crl Distribution Points Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Distribution Points:"); foreach (DistributionPoint acc in keyu.GetDistributionPoints()) { if (acc.Reasons != null) { Print(extab + " Reasons:" + acc.Reasons.GetString()); } else { Print(extab + " Reasons:Null"); } if (acc.CrlIssuer != null) { Print(extab + " Crl Issuer:"); foreach (GeneralName gen in acc.CrlIssuer.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + ": " + gen.Name); } } else { Print(extab + " Crl Issuer:Null"); } Print(extab + " Distribution Point Name:"); if (acc.DistributionPointName.PointType == DistributionPointName.FullName) { GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name); foreach (GeneralName gen in sgen.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else { Print(extab + " Not Supported by OCT"); } } } } // Signature Print(" Signature Algorithm: " + cer.SignatureAlgorithm.FriendlyName + " " + (CERT.GetSignature().Length * 8) + " bit"); Print(CERT.GetSignature(), " "); Print(" SHA1 Fingerprint : "); Print(Sha1(CERT.GetEncoded()), " "); Print(" SHA224 Fingerprint : "); Print(Sha224(CERT.GetEncoded()), " "); Print(" SHA256 Fingerprint : "); Print(Sha256(CERT.GetEncoded()), " "); Print(" SHA384 Fingerprint : "); Print(Sha384(CERT.GetEncoded()), " "); Print(" SHA512 Fingerprint : "); Print(Sha512(CERT.GetEncoded()), " "); Print(" MD5 Fingerprint : "); Print(MD5(CERT.GetEncoded()), " "); Print("Issuer Base64:" + Convert.ToBase64String(CERT.IssuerDN.GetDerEncoded())); Print("Subject Base64:" + Convert.ToBase64String(CERT.SubjectDN.GetDerEncoded())); Print("Serial Base64:" + Convert.ToBase64String(CERT.SerialNumber.ToByteArray())); if (outputfile == "stdout") { Console.Read(); } else { str.Close(); } }
/// <inheritdoc/> public Tuple <X509Certificate, RsaPrivateCrtKeyParameters> GetLocalCertificate(ApplicationDescription applicationDescription) { string applicationUri = applicationDescription.ApplicationUri; if (string.IsNullOrEmpty(applicationUri)) { throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'."); } string subjectName = null; string hostName = null; UriBuilder appUri = new UriBuilder(applicationUri); if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host)) { var path = appUri.Path.Trim('/'); if (!string.IsNullOrEmpty(path)) { subjectName = $"CN={path},DC={appUri.Host}"; hostName = appUri.Host; } } if (appUri.Scheme == "urn") { var parts = appUri.Path.Split(new[] { ':' }, 2); if (parts.Length == 2) { subjectName = $"CN={parts[1]},DC={parts[0]}"; hostName = parts[0]; } } if (subjectName == null) { throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'."); } var crt = default(X509Certificate); var key = default(RsaPrivateCrtKeyParameters); var crtInfo = new FileInfo(Path.Combine(this.pkiDirectoryPath, "own", "certs", "client.crt")); var keyInfo = new FileInfo(Path.Combine(this.pkiDirectoryPath, "own", "private", "client.key")); if (crtInfo.Exists && keyInfo.Exists) { using (var crtStream = crtInfo.OpenRead()) { crt = this.certParser.ReadCertificate(crtStream); if (crt != null) { var asn1OctetString = crt.GetExtensionValue(X509Extensions.SubjectAlternativeName); if (asn1OctetString != null) { var asn1Object = X509ExtensionUtilities.FromExtensionValue(asn1OctetString); GeneralNames gns = GeneralNames.GetInstance(asn1Object); if (gns.GetNames().Any(n => n.TagNo == GeneralName.UniformResourceIdentifier && n.Name.ToString() == applicationUri)) { using (var keyStream = new StreamReader(keyInfo.OpenRead())) { var keyReader = new PemReader(keyStream); var keyPair = keyReader.ReadObject() as AsymmetricCipherKeyPair; if (keyPair != null) { key = keyPair.Private as RsaPrivateCrtKeyParameters; } } } } } } } if (crt != null && key != null) { this.logger?.LogTrace($"Found certificate with subject alt name '{applicationUri}'."); return(new Tuple <X509Certificate, RsaPrivateCrtKeyParameters>(crt, key)); } if (!this.CreateLocalCertificateIfNotExist) { return(null); } // Create new certificate var subjectDN = new X509Name(subjectName); // Create a keypair. RsaKeyPairGenerator kg = new RsaKeyPairGenerator(); kg.Init(new KeyGenerationParameters(this.rng, 2048)); AsymmetricCipherKeyPair kp = kg.GenerateKeyPair(); key = kp.Private as RsaPrivateCrtKeyParameters; // Create a certificate. X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); var subjectSN = BigInteger.ProbablePrime(120, this.rng); cg.SetSerialNumber(subjectSN); cg.SetSubjectDN(subjectDN); cg.SetIssuerDN(subjectDN); cg.SetNotBefore(DateTime.Now); cg.SetNotAfter(DateTime.Now.AddYears(25)); cg.SetPublicKey(kp.Public); cg.AddExtension( X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); cg.AddExtension( X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public))); cg.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subjectDN)), subjectSN)); cg.AddExtension( X509Extensions.SubjectAlternativeName, false, new GeneralNames(new[] { new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri), new GeneralName(GeneralName.DnsName, hostName) })); cg.AddExtension( X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment)); cg.AddExtension( X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth)); crt = cg.Generate(new Asn1SignatureFactory("SHA256WITHRSA", key, this.rng)); this.logger?.LogTrace($"Created certificate with subject alt name '{applicationUri}'."); if (!keyInfo.Directory.Exists) { Directory.CreateDirectory(keyInfo.DirectoryName); } else if (keyInfo.Exists) { keyInfo.Delete(); } using (var keystream = new StreamWriter(keyInfo.OpenWrite())) { var pemwriter = new PemWriter(keystream); pemwriter.WriteObject(key); } if (!crtInfo.Directory.Exists) { Directory.CreateDirectory(crtInfo.DirectoryName); } else if (crtInfo.Exists) { crtInfo.Delete(); } using (var crtstream = new StreamWriter(crtInfo.OpenWrite())) { var pemwriter = new PemWriter(crtstream); pemwriter.WriteObject(crt); } return(new Tuple <X509Certificate, RsaPrivateCrtKeyParameters>(crt, key)); }