public HttpResponseMessage Get(string smsNumber, string code) { RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 2048)); AsymmetricCipherKeyPair keys = r.GenerateKeyPair(); string publicKeyPath = Path.Combine(Path.GetTempPath(), "publicKey.key"); if (File.Exists(publicKeyPath)) { File.Delete(publicKeyPath); } using (TextWriter textWriter = new StreamWriter(publicKeyPath, false)) { PemWriter pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(keys.Public); pemWriter.Writer.Flush(); } string certSubjectName = "UShadow_RSA"; var certName = new X509Name("CN=" + certSubjectName); var serialNo = BigInteger.ProbablePrime(120, new Random()); X509V3CertificateGenerator gen2 = new X509V3CertificateGenerator(); gen2.SetSerialNumber(serialNo); gen2.SetSubjectDN(certName); gen2.SetIssuerDN(new X509Name(true, "CN=UShadow")); gen2.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(30, 0, 0, 0))); gen2.SetNotAfter(DateTime.Now.AddYears(2)); gen2.SetSignatureAlgorithm("sha512WithRSA"); gen2.SetPublicKey(keys.Public); Org.BouncyCastle.X509.X509Certificate newCert = gen2.Generate(keys.Private); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); X509CertificateEntry certEntry = new X509CertificateEntry(newCert); store.SetCertificateEntry(newCert.SubjectDN.ToString(), certEntry); AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private); store.SetKeyEntry(newCert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); using (MemoryStream ms = new MemoryStream()) { store.Save(ms, "Password".ToCharArray(), new SecureRandom()); var resp = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(ms.ToArray()) }; resp.Content.Headers.Add("Content-Type", "application/x-pkcs12"); return resp; } }
public static X509Certificate2 GenerateSelfSigned(TimeSpan lifetime) { Guid guid = Guid.NewGuid(); DateTime now = DateTime.UtcNow; SecureRandom rand = new SecureRandom(); //Generate a key pair RsaKeyPairGenerator keyGen = new RsaKeyPairGenerator(); keyGen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(rand, 1024)); AsymmetricCipherKeyPair key = keyGen.GenerateKeyPair(); //Generate a certificate X509Name dn = new X509Name("CN=" + guid.ToString()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetIssuerDN(dn); certGen.SetSerialNumber(new BigInteger(1, guid.ToByteArray())); certGen.SetSignatureAlgorithm("SHA1WITHRSA"); certGen.SetSubjectDN(dn); certGen.SetPublicKey(key.Public); certGen.SetNotBefore(now); certGen.SetNotAfter(now.Add(lifetime)); Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(key.Private); //Save it as pkcs12 MemoryStream p12Stream = new MemoryStream(); Pkcs12Store p12 = new Pkcs12Store(); p12.SetKeyEntry("sts", new AsymmetricKeyEntry(key.Private), new X509CertificateEntry[] { new X509CertificateEntry(bcCert) }); p12.Save(p12Stream, p12TmpPwd.ToCharArray(), rand); //Load the pkcs12 as .Net Certificate return new X509Certificate2(p12Stream.ToArray(), p12TmpPwd, X509KeyStorageFlags.DefaultKeySet); }
public static X509Certificate GenCert(CertInfo info) { RsaKeyPairGenerator _rsa = new RsaKeyPairGenerator(); SecureRandom _random = new SecureRandom(); _rsa.Init(new KeyGenerationParameters(_random, info.rsa_strength)); AsymmetricCipherKeyPair _pair = _rsa.GenerateKeyPair(); X509Name _cert_name = new X509Name("CN=" + info.name); BigInteger _serialnumber = BigInteger.ProbablePrime(120, new Random()); X509V3CertificateGenerator _cert = new X509V3CertificateGenerator(); _cert.SetSerialNumber(_serialnumber); _cert.SetSubjectDN(_cert_name); _cert.SetIssuerDN(_cert_name); _cert.SetNotBefore(info.begin_date); _cert.SetNotAfter(info.expire_date); _cert.SetSignatureAlgorithm("SHA1withRSA"); _cert.SetPublicKey(_pair.Public); _cert.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_pair.Public), new GeneralNames(new GeneralName(_cert_name)), _serialnumber)); _cert.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth })); return _cert.Generate(_pair.Private); }
private bool MatchesDN( X509Name 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 (X509Name.GetInstance(gn.Name).Equivalent(subject)) { return true; } } catch (Exception) { } } } return false; }
public virtual IList<CertificateAndContext> GetCertificateBySubjectName(X509Name subjectName) { IList<CertificateAndContext> list = new AList<CertificateAndContext>(); try { string url = GetAccessLocation(certificate, X509ObjectIdentifiers.IdADCAIssuers); if (url != null) { X509CertificateParser parser = new X509CertificateParser(); X509Certificate cert = parser.ReadCertificate(httpDataLoader.Get(url)); if (cert.SubjectDN.Equals(subjectName)) { list.Add(new CertificateAndContext()); } } } catch (CannotFetchDataException) { return new List<CertificateAndContext>(); } catch (CertificateException) { return new List<CertificateAndContext>(); } return list; }
public IssuerAndSerialNumber( X509Name name, DerInteger certSerialNumber) { this.name = name; this.certSerialNumber = certSerialNumber; }
/// <summary> /// Generate a cert/key pair /// </summary> private void GenerateCertKeyPair() { // Generate RSA key pair RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); keyPair = r.GenerateKeyPair(); // Generate the X509 certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Name dnName = new X509Name("CN=NVIDIA GameStream Client"); certGen.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond)); certGen.SetSubjectDN(dnName); certGen.SetIssuerDN(dnName); // use the same // Expires in 20 years certGen.SetNotBefore(DateTime.Now); certGen.SetNotAfter(DateTime.Now.AddYears(20)); certGen.SetPublicKey(keyPair.Public); certGen.SetSignatureAlgorithm("SHA1withRSA"); try { cert = certGen.Generate(keyPair.Private); } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); } Task.Run(async () => await SaveCertKeyPair()).Wait(); }
public IssuerAndSerialNumber( X509Name name, BigInteger serialNumber) { this.name = name; this.serialNumber = new DerInteger(serialNumber); }
public IssuerAndSerialNumber( X509Name name, DerInteger serialNumber) { this.name = name; this.serialNumber = serialNumber; }
/// <summary> /// Generates a user certificate /// </summary> /// <param name="subject">X509Name subject name </param> /// <param name="issuer">X509Name issuer name</param> /// <param name="iValidity">validity in days</param> /// <param name="publicKey">publickey</param> /// <param name="privateKey">private key of the issuer</param> /// <param name="signatureType">signature type</param> /// <param name="keyusages">keyusages, <see>Org.BouncyCastle.Asn1.X509.KeyUsage</see></param> /// <param name="extendedKeyUsages">extendedKeyUsages <see>Org.BouncyCastle.Asn1.X509.KeyPurposeID</see></param> /// <returns>brand new generated X509Certificate</returns> public static X509Certificate GenerateUserCertificate(X509Name subject, X509Name issuer, int iValidity, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, String signatureType, int keyusages, ExtendedKeyUsage extendedKeyUsages) { return GenerateCertificate(subject, issuer, iValidity, publicKey, privateKey, signatureType, keyusages, extendedKeyUsages, false, 0); }
public ResponderID( X509Name id) { if (id == null) throw new ArgumentNullException("id"); this.id = id; }
internal TbsCertificateStructure( Asn1Sequence seq) { int seqStart = 0; this.seq = seq; // // some certficates don't include a version number - we assume v1 // if (seq[0] is DerTaggedObject) { version = DerInteger.GetInstance((Asn1TaggedObject)seq[0], true); } else { seqStart = -1; // field 0 is missing! version = new DerInteger(0); } serialNumber = DerInteger.GetInstance(seq[seqStart + 1]); signature = AlgorithmIdentifier.GetInstance(seq[seqStart + 2]); issuer = X509Name.GetInstance(seq[seqStart + 3]); // // before and after dates // Asn1Sequence dates = (Asn1Sequence)seq[seqStart + 4]; startDate = Time.GetInstance(dates[0]); endDate = Time.GetInstance(dates[1]); subject = X509Name.GetInstance(seq[seqStart + 5]); // // public key info. // subjectPublicKeyInfo = SubjectPublicKeyInfo.GetInstance(seq[seqStart + 6]); for (int extras = seq.Count - (seqStart + 6) - 1; extras > 0; extras--) { DerTaggedObject extra = (DerTaggedObject) seq[seqStart + 6 + extras]; switch (extra.TagNo) { case 1: issuerUniqueID = DerBitString.GetInstance(extra, false); break; case 2: subjectUniqueID = DerBitString.GetInstance(extra, false); break; case 3: extensions = X509Extensions.GetInstance(extra); break; } } }
/** * Constructor for CRLEntries of indirect CRLs. If <code>isIndirect</code> * is <code>false</code> {@link #getCertificateIssuer()} will always * return <code>null</code>, <code>previousCertificateIssuer</code> is * ignored. If this <code>isIndirect</code> is specified and this CrlEntry * has no certificate issuer CRL entry extension * <code>previousCertificateIssuer</code> is returned by * {@link #getCertificateIssuer()}. * * @param c * TbsCertificateList.CrlEntry object. * @param isIndirect * <code>true</code> if the corresponding CRL is a indirect * CRL. * @param previousCertificateIssuer * Certificate issuer of the previous CrlEntry. */ public X509CrlEntry( CrlEntry c, bool isIndirect, X509Name previousCertificateIssuer) { this.c = c; this.isIndirect = isIndirect; this.previousCertificateIssuer = previousCertificateIssuer; }
/// <summary> /// Generates a CA certificate. /// </summary> /// <param name="subject">X509Name subject name </param> /// <param name="iValidity">validity in days</param> /// <param name="publicKey">publickey</param> /// <param name="privateKey">private key of the issuer</param> /// <param name="signatureType">signature type</param> /// <param name="keyusages">keyusages, <see>Org.BouncyCastle.Asn1.X509.KeyUsage</see></param> /// <param name="extendedKeyUsages">extendedKeyUsages <see>Org.BouncyCastle.Asn1.X509.KeyPurposeID</see></param> /// <param name="pathLenConstraint"> </param> /// <returns>brand new generated X509Certificate</returns> public static X509Certificate GenerateCACertificate(X509Name subject, int iValidity, AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey, String signatureType, int keyusages, ExtendedKeyUsage extendedKeyUsages, int pathLenConstraint) { return GenerateCertificate(subject, subject, iValidity, publicKey, privateKey, signatureType, keyusages, extendedKeyUsages, true, pathLenConstraint); }
private IssuerAndSerialNumber( Asn1Sequence seq) { if (seq.Count != 2) throw new ArgumentException(@"Wrong number of elements in sequence", "seq"); this.name = X509Name.GetInstance(seq[0]); this.certSerialNumber = DerInteger.GetInstance(seq[1]); }
public AttributeCertificateHolder( X509Name issuerName, BigInteger serialNumber) { holder = new Holder( new IssuerSerial( GenerateGeneralNames(issuerName), new DerInteger(serialNumber))); }
public Pkcs10CertificationRequestDelaySigned( string signatureAlgorithm, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter signingKey) : base(signatureAlgorithm, subject, publicKey, attributes, signingKey) { }
public ServiceLocator( X509Name issuer, Asn1Object locator) { if (issuer == null) throw new ArgumentNullException("issuer"); this.issuer = issuer; this.locator = locator; }
private ServiceLocator( Asn1Sequence seq) { this.issuer = X509Name.GetInstance(seq[0]); if (seq.Count > 1) { this.locator = seq[1].ToAsn1Object(); } }
public static X509Certificate2 GenerateSelfSignedCert() { var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var certificateGenerator = new X509V3CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); const string signatureAlgorithm = "SHA1WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); var subjectDN = new X509Name("CN=simpletorrent"); var issuerDN = subjectDN; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); var notBefore = DateTime.UtcNow.Date.AddHours(-24); var notAfter = notBefore.AddYears(1000); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); const int strength = 4096; var keyGenerationParameters = new KeyGenerationParameters(random, strength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = subjectKeyPair; var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random); var store = new Pkcs12Store(); string friendlyName = certificate.SubjectDN.ToString(); var certificateEntry = new X509CertificateEntry(certificate); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry }); string password = "******"; var stream = new MemoryStream(); store.Save(stream, password.ToCharArray(), random); //mono bug #1660 fix -> convert to definite-length encoding byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray()); var convertedCertificate = new X509Certificate2( pfx, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return convertedCertificate; }
public static byte[] GenerateDsaCertificateAsPkcs12( string friendlyName, string subjectName, string country, DateTime validStartDate, DateTime validEndDate, string password, Org.BouncyCastle.X509.X509Certificate caCert, AsymmetricKeyParameter caPrivateKey) { var keys = GenerateDsaKeys(); #region build certificate var certGen = new X509V3CertificateGenerator(); // build name attributes var nameOids = new ArrayList(); nameOids.Add(Org.BouncyCastle.Asn1.X509.X509Name.CN); nameOids.Add(X509Name.O); nameOids.Add(X509Name.C); var nameValues = new ArrayList(); nameValues.Add(friendlyName); nameValues.Add(subjectName); nameValues.Add(country); var subjectDN = new X509Name(nameOids, nameValues); // certificate fields certGen.SetSerialNumber(BigInteger.ValueOf(1)); certGen.SetIssuerDN(caCert.SubjectDN); certGen.SetNotBefore(validStartDate); certGen.SetNotAfter(validEndDate); certGen.SetSubjectDN(subjectDN); certGen.SetPublicKey(keys.Public); certGen.SetSignatureAlgorithm("SHA1withDSA"); // extended information certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.GetPublicKey())); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keys.Public)); #endregion // generate x509 certificate var cert = certGen.Generate(caPrivateKey); //ert.Verify(caCert.GetPublicKey()); var chain = new Dictionary<string, Org.BouncyCastle.X509.X509Certificate>(); //chain.Add("CertiFirmas CA", caCert); var caCn = caCert.SubjectDN.GetValues(X509Name.CN)[0].ToString(); chain.Add(caCn, caCert); // store the file return GeneratePkcs12(keys, cert, friendlyName, password, chain); }
public RespID( X509Name name) { try { this.id = new ResponderID(name); } catch (Exception e) { throw new ArgumentException("can't decode name.", e); } }
/** * Set the requestor name to the passed in X509Principal * * @param requestorName a X509Principal representing the requestor name. */ public void SetRequestorName( X509Name requestorName) { try { this.requestorName = new GeneralName(GeneralName.DirectoryName, requestorName); } catch (Exception e) { throw new ArgumentException("cannot encode principal", e); } }
/// <summary> /// Add the Authority Key Identifier. According to http://www.alvestrand.no/objectid/2.5.29.35.html, this /// identifies the public key to be used to verify the signature on this certificate. /// In a certificate chain, this corresponds to the "Subject Key Identifier" on the *issuer* certificate. /// The Bouncy Castle documentation, at http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation, /// shows how to create this from the issuing certificate. Since we're creating a self-signed certificate, we have to do this slightly differently. /// </summary> /// <param name="certificateGenerator"></param> /// <param name="issuerDN"></param> /// <param name="issuerKeyPair"></param> /// <param name="issuerSerialNumber"></param> private static void AddAuthorityKeyIdentifier(X509V3CertificateGenerator certificateGenerator, X509Name issuerDN, AsymmetricCipherKeyPair issuerKeyPair, BigInteger issuerSerialNumber) { var authorityKeyIdentifierExtension = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber); certificateGenerator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifierExtension); }
public Authority(string authority) { _issuer = new X509Name(new CommonName(authority).Name); _authSerial = GetSerialNumber(); CreateKeyPair(); _certGen = new X509V3CertificateGenerator(); _certGen.SetSubjectDN(_issuer); _certGen.SetSerialNumber(_authSerial); X509Certificate = GenerateCertificate(); _creatingAuthCert = false; }
GenerateCertificate(string subjectName, out AsymmetricCipherKeyPair kp) { var kpgen = new RsaKeyPairGenerator(); // certificate strength 1024 bits kpgen.Init(new KeyGenerationParameters( new SecureRandom(new CryptoApiRandomGenerator()), 1024)); kp = kpgen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); var serialNo = BigInteger.ProbablePrime(120, new Random()); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(certName); gen.SetNotAfter(DateTime.Now.AddYears(100)); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetSignatureAlgorithm("SHA1withRSA"); gen.SetPublicKey(kp.Public); gen.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(certName)), serialNo)); /* 1.3.6.1.5.5.7.3.1 - id_kp_serverAuth 1.3.6.1.5.5.7.3.2 - id_kp_clientAuth 1.3.6.1.5.5.7.3.3 - id_kp_codeSigning 1.3.6.1.5.5.7.3.4 - id_kp_emailProtection 1.3.6.1.5.5.7.3.5 - id-kp-ipsecEndSystem 1.3.6.1.5.5.7.3.6 - id-kp-ipsecTunnel 1.3.6.1.5.5.7.3.7 - id-kp-ipsecUser 1.3.6.1.5.5.7.3.8 - id_kp_timeStamping 1.3.6.1.5.5.7.3.9 - OCSPSigning */ gen.AddExtension( X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth })); var newCert = gen.Generate(kp.Private); return newCert; }
public IList<CertificateAndContext> GetCertificateBySubjectName(X509Name subjectName ) { IList<CertificateAndContext> list = new AList<CertificateAndContext>(); foreach (X509Certificate cert in GetCertificates()) { if (subjectName.Equals(cert.SubjectDN)) { CertificateAndContext cc = new CertificateAndContext(cert); cc.SetCertificateSource(sourceType); list.AddItem(cc); } } return list; }
/// <summary>The default constructor for CRLRef.</summary> /// <remarks>The default constructor for CRLRef.</remarks> /// <param name="cmsRef"></param> /// <exception cref="Sharpen.ParseException">Sharpen.ParseException</exception> public CRLRef(CrlValidatedID cmsRef) { try { crlIssuer = cmsRef.CrlIdentifier.CrlIssuer; crlIssuedTime = cmsRef.CrlIdentifier.CrlIssuedTime; crlNumber = cmsRef.CrlIdentifier.CrlNumber; algorithm = cmsRef.CrlHash.HashAlgorithm.ObjectID.Id; digestValue = cmsRef.CrlHash.GetHashValue(); } catch (ParseException ex) { throw new RuntimeException(ex); } }
public CertificationRequestInfo( X509Name subject, SubjectPublicKeyInfo pkInfo, Asn1Set attributes) { this.subject = subject; this.subjectPKInfo = pkInfo; this.attributes = attributes; if (subject == null || version == null || subjectPKInfo == null) { throw new ArgumentException( "Not all mandatory fields set in CertificationRequestInfo generator."); } }
public static X509Certificate2 GenerateNewCertificate(string name) { var kpGen = new RsaKeyPairGenerator(); kpGen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024)); AsymmetricCipherKeyPair keyPair = kpGen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); var certificateName = new X509Name("CN=" + name); BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random()); gen.SetSerialNumber(serialNumber); gen.SetSubjectDN(certificateName); gen.SetIssuerDN(certificateName); gen.SetNotAfter(DateTime.Now.AddYears(100)); gen.SetNotBefore(DateTime.Now.AddDays(-1)); gen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); gen.SetPublicKey(keyPair.Public); gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public), new GeneralNames(new GeneralName(certificateName)), serialNumber)); X509Certificate newCert = gen.Generate(keyPair.Private); var newStore = new Pkcs12Store(); var certEntry = new X509CertificateEntry(newCert); newStore.SetCertificateEntry( Environment.MachineName, certEntry ); newStore.SetKeyEntry( Environment.MachineName, new AsymmetricKeyEntry(keyPair.Private), new[] {certEntry} ); var memoryStream = new MemoryStream(); newStore.Save( memoryStream, new char[0], new SecureRandom(new CryptoApiRandomGenerator()) ); return new X509Certificate2(memoryStream.ToArray()); }
internal TbsCertificateStructure( Asn1Sequence seq) { int seqStart = 0; this.seq = seq; // // some certficates don't include a version number - we assume v1 // if (seq[0] is DerTaggedObject) { version = DerInteger.GetInstance((Asn1TaggedObject)seq[0], true); } else { seqStart = -1; // field 0 is missing! version = new DerInteger(0); } bool isV1 = false; bool isV2 = false; if (version.Value.Equals(BigInteger.Zero)) { isV1 = true; } else if (version.Value.Equals(BigInteger.One)) { isV2 = true; } else if (!version.Value.Equals(BigInteger.Two)) { throw new ArgumentException("version number not recognised"); } serialNumber = DerInteger.GetInstance(seq[seqStart + 1]); signature = AlgorithmIdentifier.GetInstance(seq[seqStart + 2]); issuer = X509Name.GetInstance(seq[seqStart + 3]); // // before and after dates // Asn1Sequence dates = (Asn1Sequence)seq[seqStart + 4]; startDate = Time.GetInstance(dates[0]); endDate = Time.GetInstance(dates[1]); subject = X509Name.GetInstance(seq[seqStart + 5]); // // public key info. // subjectPublicKeyInfo = SubjectPublicKeyInfo.GetInstance(seq[seqStart + 6]); int extras = seq.Count - (seqStart + 6) - 1; if (extras != 0 && isV1) { throw new ArgumentException("version 1 certificate contains extra data"); } while (extras > 0) { DerTaggedObject extra = (DerTaggedObject)seq[seqStart + 6 + extras]; switch (extra.TagNo) { case 1: { issuerUniqueID = DerBitString.GetInstance(extra, false); break; } case 2: { subjectUniqueID = DerBitString.GetInstance(extra, false); break; } case 3: { if (isV2) { throw new ArgumentException("version 2 certificate cannot contain extensions"); } extensions = X509Extensions.GetInstance(Asn1Sequence.GetInstance(extra, true)); break; } default: { throw new ArgumentException("Unknown tag encountered in structure: " + extra.TagNo); } } extras--; } }
private string createValidIssuerName(X509Certificate2 certificate) { try { var x509Name = new BCx509.X509Name(certificate.IssuerName.Name); var oids = x509Name.GetOidList(); var vals = x509Name.GetValueList(); for (int x = 0; x < oids.Count; x++) { var oid = oids[x] as DerObjectIdentifier; // verificar oid de email if (oid.Id == BCx509.X509Name.EmailAddress.Id) { var val = vals[x] as string; // codificar a hex si es necesario if (val != null && val.Length > 0 && val[0] != '#') { var str = new DerIA5String(val); var eStr = str.GetEncoded(); val = "#" + BCEncoders.Hex.ToHexString(eStr); } vals[x] = val; } } var oidSymbols = new Hashtable(); oidSymbols.Add(BCx509.X509Name.C, "C"); oidSymbols.Add(BCx509.X509Name.O, "O"); oidSymbols.Add(BCx509.X509Name.T, "T"); oidSymbols.Add(BCx509.X509Name.OU, "OU"); oidSymbols.Add(BCx509.X509Name.CN, "CN"); oidSymbols.Add(BCx509.X509Name.L, "L"); oidSymbols.Add(BCx509.X509Name.ST, "ST"); oidSymbols.Add(BCx509.X509Name.SerialNumber, "SERIALNUMBER"); //oidSymbols.Add(BCx509.X509Name.EmailAddress, "E"); // ignorar oidSymbols.Add(BCx509.X509Name.DC, "DC"); oidSymbols.Add(BCx509.X509Name.UID, "UID"); oidSymbols.Add(BCx509.X509Name.Street, "STREET"); oidSymbols.Add(BCx509.X509Name.Surname, "SURNAME"); oidSymbols.Add(BCx509.X509Name.GivenName, "GIVENNAME"); oidSymbols.Add(BCx509.X509Name.Initials, "INITIALS"); oidSymbols.Add(BCx509.X509Name.Generation, "GENERATION"); oidSymbols.Add(BCx509.X509Name.UnstructuredAddress, "unstructuredAddress"); oidSymbols.Add(BCx509.X509Name.UnstructuredName, "unstructuredName"); oidSymbols.Add(BCx509.X509Name.UniqueIdentifier, "UniqueIdentifier"); oidSymbols.Add(BCx509.X509Name.DnQualifier, "DN"); oidSymbols.Add(BCx509.X509Name.Pseudonym, "Pseudonym"); oidSymbols.Add(BCx509.X509Name.PostalAddress, "PostalAddress"); oidSymbols.Add(BCx509.X509Name.NameAtBirth, "NameAtBirth"); oidSymbols.Add(BCx509.X509Name.CountryOfCitizenship, "CountryOfCitizenship"); oidSymbols.Add(BCx509.X509Name.CountryOfResidence, "CountryOfResidence"); oidSymbols.Add(BCx509.X509Name.Gender, "Gender"); oidSymbols.Add(BCx509.X509Name.PlaceOfBirth, "PlaceOfBirth"); oidSymbols.Add(BCx509.X509Name.DateOfBirth, "DateOfBirth"); oidSymbols.Add(BCx509.X509Name.PostalCode, "PostalCode"); oidSymbols.Add(BCx509.X509Name.BusinessCategory, "BusinessCategory"); oidSymbols.Add(BCx509.X509Name.TelephoneNumber, "TelephoneNumber"); var components = new ArrayList(); StringBuilder ava = null; for (int i = 0; i < oids.Count; i++) { ava = new StringBuilder(); appendValue(ava, oidSymbols, (DerObjectIdentifier)oids[i], (string)vals[i]); components.Add(ava); } var buf = new StringBuilder(); if (components.Count > 0) { buf.Append(components[0].ToString()); for (int i = 1; i < components.Count; ++i) { buf.Append(','); buf.Append(components[i].ToString()); } } return(buf.ToString()); } catch { return(certificate.IssuerName.Name); } }
// http://stackoverflow.com/questions/36942094/how-can-i-generate-a-self-signed-cert-without-using-obsolete-bouncycastle-1-7-0 public static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateX509Cert2(string certName) { var keypairgen = new Org.BouncyCastle.Crypto.Generators.RsaKeyPairGenerator(); keypairgen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters( new Org.BouncyCastle.Security.SecureRandom( new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator() ) , 1024 //, 512 ) ); Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair(); // --- Until here we generate a keypair var random = new Org.BouncyCastle.Security.SecureRandom( new Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator() ); // SHA1WITHRSA // SHA256WITHRSA // SHA384WITHRSA // SHA512WITHRSA // SHA1WITHECDSA // SHA224WITHECDSA // SHA256WITHECDSA // SHA384WITHECDSA // SHA512WITHECDSA Org.BouncyCastle.Crypto.ISignatureFactory signatureFactory = new Org.BouncyCastle.Crypto.Operators.Asn1SignatureFactory("SHA512WITHRSA", keypair.Private, random) ; var gen = new Org.BouncyCastle.X509.X509V3CertificateGenerator(); var CN = new Org.BouncyCastle.Asn1.X509.X509Name("CN=" + certName); var SN = Org.BouncyCastle.Math.BigInteger.ProbablePrime(120, new Random()); gen.SetSerialNumber(SN); gen.SetSubjectDN(CN); gen.SetIssuerDN(CN); gen.SetNotAfter(DateTime.Now.AddYears(1)); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetPublicKey(keypair.Public); // -- Are these necessary ? // public static readonly DerObjectIdentifier AuthorityKeyIdentifier = new DerObjectIdentifier("2.5.29.35"); // OID value: 2.5.29.35 // OID description: id-ce-authorityKeyIdentifier // This extension may be used either as a certificate or CRL extension. // It identifies the public key to be used to verify the signature on this certificate or CRL. // It enables distinct keys used by the same CA to be distinguished (e.g., as key updating occurs). // http://stackoverflow.com/questions/14930381/generating-x509-certificate-using-bouncy-castle-java gen.AddExtension( Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityKeyIdentifier.Id, false, new Org.BouncyCastle.Asn1.X509.AuthorityKeyIdentifier( Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public), new Org.BouncyCastle.Asn1.X509.GeneralNames(new Org.BouncyCastle.Asn1.X509.GeneralName(CN)), SN )); // OID value: 1.3.6.1.5.5.7.3.1 // OID description: Indicates that a certificate can be used as an SSL server certificate. gen.AddExtension( Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage.Id, false, new Org.BouncyCastle.Asn1.X509.ExtendedKeyUsage( new System.Collections.Generic.List <object>() { new Org.BouncyCastle.Asn1.DerObjectIdentifier("1.3.6.1.5.5.7.3.1") } ) ); gen.AddExtension( new Org.BouncyCastle.Asn1.DerObjectIdentifier("2.5.29.19"), false, new Org.BouncyCastle.Asn1.X509.BasicConstraints(false) // true if it is allowed to sign other certs ); gen.AddExtension( new Org.BouncyCastle.Asn1.DerObjectIdentifier("2.5.29.15"), true, new Org.BouncyCastle.X509.X509KeyUsage( Org.BouncyCastle.X509.X509KeyUsage.DigitalSignature | Org.BouncyCastle.X509.X509KeyUsage.NonRepudiation | Org.BouncyCastle.X509.X509KeyUsage.KeyEncipherment | Org.BouncyCastle.X509.X509KeyUsage.DataEncipherment) ); // -- End are these necessary ? Org.BouncyCastle.X509.X509Certificate bouncyCert = gen.Generate(signatureFactory); // Org.BouncyCastle.X509.X509Certificate bouncyCert = gen.Generate(keypair.Private); bouncyCert.GetPublicKey(); byte[] ba = bouncyCert.GetEncoded(); using (System.IO.TextWriter textWriter = new System.IO.StringWriter()) { Org.BouncyCastle.OpenSsl.PemWriter pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter); pemWriter.WriteObject(bouncyCert); pemWriter.WriteObject(keypair.Private); pemWriter.Writer.Flush(); string privateKey = textWriter.ToString(); System.Console.WriteLine(privateKey); } // End Using textWriter string certFile = @"D:\mycert.cert"; using (System.IO.FileStream fs = System.IO.File.OpenWrite(certFile)) { using (System.IO.TextWriter textWriter = new System.IO.StreamWriter(fs)) { Org.BouncyCastle.OpenSsl.PemWriter pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter); pemWriter.WriteObject(bouncyCert); pemWriter.WriteObject(keypair.Private); pemWriter.Writer.Flush(); string privateKey = textWriter.ToString(); System.Console.WriteLine(privateKey); } // End Using textWriter } // End Using fs // https://github.com/dotnet/corefx/blob/master/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs // https://github.com/dotnet/corefx/blob/master/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs // System.Security.Cryptography.X509Certificates.X509Certificate2 msCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(ba); System.Security.Cryptography.X509Certificates.X509Certificate2 msCert = new System.Security.Cryptography.X509Certificates .X509Certificate2(ba, null , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.PersistKeySet | // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.MachineKeySet | // System.Security.Cryptography.X509Certificates.X509KeyStorageFlag.Exportable ); msCert = new X509Certificate2(certFile, null, X509KeyStorageFlags.MachineKeySet); object obj = msCert.GetRSAPrivateKey(); System.Console.WriteLine(obj); if (msCert.HasPrivateKey) { Console.WriteLine(msCert.HasPrivateKey); } return(msCert); }
public GeneralName(X509Name directoryName) { this.obj = directoryName; this.tag = 4; }
/** * Use this constructor if you want to verify a signature using * the sub-filter adbe.pkcs7.detached or adbe.pkcs7.sha1. * @param contentsKey the /Contents key * @param tsp set to true if there's a PAdES LTV time stamp. * @param provider the provider or <code>null</code> for the default provider */ public PdfPKCS7(byte[] contentsKey, bool tsp) { isTsp = tsp; Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // Asn1Object pkcs; try { pkcs = din.ReadObject(); } catch { throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object")); } if (!(pkcs is Asn1Sequence)) { throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence")); } Asn1Sequence signedData = (Asn1Sequence)pkcs; DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0]; if (!objId.Id.Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA)) { throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data")); } Asn1Sequence content = (Asn1Sequence)((Asn1TaggedObject)signedData[1]).GetObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((DerInteger)content[0]).Value.IntValue; // the digestAlgorithms digestalgos = new Dictionary <string, object>(); IEnumerator e = ((Asn1Set)content[1]).GetEnumerator(); while (e.MoveNext()) { Asn1Sequence s = (Asn1Sequence)e.Current; DerObjectIdentifier o = (DerObjectIdentifier)s[0]; digestalgos[o.Id] = null; } // the certificates and crls X509CertificateParser cf = new X509CertificateParser(); certs = new List <X509Certificate>(); foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) { certs.Add(cc); } crls = new List <X509Crl>(); // the possible ID_PKCS7_DATA Asn1Sequence rsaData = (Asn1Sequence)content[2]; if (rsaData.Count > 1) { Asn1OctetString rsaDataContent = (Asn1OctetString)((Asn1TaggedObject)rsaData[1]).GetObject(); RSAdata = rsaDataContent.GetOctets(); } // the signerInfos int next = 3; while (content[next] is Asn1TaggedObject) { ++next; } Asn1Set signerInfos = (Asn1Set)content[next]; if (signerInfos.Count != 1) { throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time")); } Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0]; // the positions that we care are // 0 - version // 1 - the signing certificate issuer and serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((DerInteger)signerInfo[0]).Value.IntValue; // Get the signing certificate Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1]; Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]); BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value; foreach (X509Certificate cert in certs) { if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber)) { signCert = cert; break; } } if (signCert == null) { throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1", issuer.ToString() + " / " + serialNumber.ToString(16))); } CalcSignCertificateChain(); digestAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id; next = 3; if (signerInfo[next] is Asn1TaggedObject) { Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next]; Asn1Set sseq = Asn1Set.GetInstance(tagsig, false); sigAttr = sseq.GetEncoded(Asn1Encodable.Der); for (int k = 0; k < sseq.Count; ++k) { Asn1Sequence seq2 = (Asn1Sequence)sseq[k]; if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_MESSAGE_DIGEST)) { Asn1Set sset = (Asn1Set)seq2[1]; digestAttr = ((DerOctetString)sset[0]).GetOctets(); } else if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_ADBE_REVOCATION)) { Asn1Set setout = (Asn1Set)seq2[1]; Asn1Sequence seqout = (Asn1Sequence)setout[0]; for (int j = 0; j < seqout.Count; ++j) { Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j]; if (tg.TagNo == 1) { Asn1Sequence seqin = (Asn1Sequence)tg.GetObject(); FindOcsp(seqin); } if (tg.TagNo == 0) { Asn1Sequence seqin = (Asn1Sequence)tg.GetObject(); FindCRL(seqin); } } } } if (digestAttr == null) { throw new ArgumentException(MessageLocalization.GetComposedMessage("authenticated.attribute.is.missing.the.digest")); } ++next; } digestEncryptionAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id; digest = ((Asn1OctetString)signerInfo[next++]).GetOctets(); if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) { Asn1TaggedObject taggedObject = (Asn1TaggedObject)signerInfo[next]; Asn1Set unat = Asn1Set.GetInstance(taggedObject, false); Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat); Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]; if (ts != null && ts.AttrValues.Count > 0) { Asn1Set attributeValues = ts.AttrValues; Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]); Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence); this.timeStampToken = new TimeStampToken(contentInfo); } } if (isTsp) { Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfoTsp = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(signedData); this.timeStampToken = new TimeStampToken(contentInfoTsp); TimeStampTokenInfo info = timeStampToken.TimeStampInfo; String algOID = info.MessageImprintAlgOid; messageDigest = DigestUtilities.GetDigest(algOID); } else { if (RSAdata != null || digestAttr != null) { messageDigest = GetHashClass(); encContDigest = GetHashClass(); } sig = SignerUtilities.GetSigner(GetDigestAlgorithm()); sig.Init(false, signCert.GetPublicKey()); } }
static void Main(string[] args) { string subjectName = "testsubject"; var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var certificateGenerator = new X509V3CertificateGenerator(); var serialNumber = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); const string signatureAlgorithm = "SHA256WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); var subjectDN = new Org.BouncyCastle.Asn1.X509.X509Name(subjectName); var issuerDN = subjectDN; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); const int strength = 2048; var keyGenerationParameters = new KeyGenerationParameters(random, strength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var issuerKeyPair = subjectKeyPair; var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random); PdfReader reader = new PdfReader(this.inputPDF); ////var kpgen = new RsaKeyPairGenerator(); ////kpgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024)); ////var kp = kpgen.GenerateKeyPair(); ////var gen = new X509V3CertificateGenerator(); ////var certName = new Org.BouncyCastle.Asn1.X509.X509Name("CN=" + subjectName); ////var serialNo = BigInteger.ProbablePrime(120, new Random()); ////gen.SetSerialNumber(serialNo); ////gen.SetSubjectDN(certName); ////gen.SetIssuerDN(certName); ////gen.SetNotAfter(DateTime.Now.AddYears(100)); ////gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); ////gen.SetSignatureAlgorithm("MD5WithRSA"); ////gen.SetPublicKey(kp.Public); ////gen.AddExtension( //// X509Extensions.AuthorityKeyIdentifier.Id, //// false, //// new AuthorityKeyIdentifier( //// SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), //// new GeneralNames(new GeneralName(certName)), //// serialNo)); ////gen.AddExtension( //// X509Extensions.ExtendedKeyUsage.Id, //// false, //// new ExtendedKeyUsage(new ArrayList() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") })); ////var newCert = gen.Generate(kp.Private); ////DotNetUtilities.ToX509Certificate(newCert).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, "password"); }
/// <summary> /// Validates the cert with the provided ocsp responses. /// </summary> /// <param name="certificate">The cert to validate</param> /// <param name="issuer">The issuer of the cert to validate</param> /// <param name="validationTime">The time on which the cert was needed to validated</param> /// <param name="ocspResponses">The list of ocsp responses to use</param> /// <returns>The OCSP response that was used, <c>null</c> if none was found</returns> /// <exception cref="RevocationException{T}">When the certificate was revoked on the provided time</exception> /// <exception cref="RevocationUnknownException">When the certificate (or the OCSP) can't be validated</exception> public static BCAO.BasicOcspResponse Verify(this X509Certificate2 certificate, X509Certificate2 issuer, DateTime validationTime, IList <BCAO.BasicOcspResponse> ocspResponses) { DateTime minTime = validationTime - ClockSkewness; DateTime maxTime = validationTime + ClockSkewness; BCX.X509Certificate certificateBC = DotNetUtilities.FromX509Certificate(certificate); BCX.X509Certificate issuerBC = DotNetUtilities.FromX509Certificate(issuer); ValueWithRef <BCO.SingleResp, ValueWithRef <BCO.BasicOcspResp, BCAO.BasicOcspResponse> > singleOcspRespLeaf = ocspResponses .Select((rsp) => new ValueWithRef <BCO.BasicOcspResp, BCAO.BasicOcspResponse>(new BCO.BasicOcspResp(rsp), rsp)) //convert, but keep the original .SelectMany((r) => r.Value.Responses.Select(sr => new ValueWithRef <BCO.SingleResp, ValueWithRef <BCO.BasicOcspResp, BCAO.BasicOcspResponse> >(sr, r))) //get the single respononses, but keep the parent .Where((sr) => sr.Value.GetCertID().SerialNumber.Equals(certificateBC.SerialNumber) && sr.Value.GetCertID().MatchesIssuer(issuerBC)) //is it for this cert? .Where((sr) => sr.Value.ThisUpdate >= minTime || (sr.Value.NextUpdate != null && sr.Value.NextUpdate.Value >= minTime)) //was it issued on time? .OrderByDescending((sr) => sr.Value.ThisUpdate) //newest first .FirstOrDefault(); if (singleOcspRespLeaf == null) { return(null); } BCO.SingleResp singleOcspResp = singleOcspRespLeaf.Value; BCO.BasicOcspResp basicOcspResp = singleOcspRespLeaf.Reference.Value; BCAO.BasicOcspResponse basicOcspResponse = singleOcspRespLeaf.Reference.Reference; //get the signer name BCAX.X509Name responderName = basicOcspResp.ResponderId.ToAsn1Object().Name; if (responderName == null) { trace.TraceEvent(TraceEventType.Error, 0, "OCSP response for {0} does not have a ResponderID", certificate.Subject); throw new RevocationUnknownException("OCSP response for {0} does not have a ResponderID"); } //Get the signer certificate var selector = new BCS.X509CertStoreSelector(); selector.Subject = responderName; BCX.X509Certificate ocspSignerBc = (BCX.X509Certificate)basicOcspResp .GetCertificates("Collection").GetMatches(selector) .Cast <BCX.X509Certificate>().FirstOrDefault(); if (ocspSignerBc == null) { throw new RevocationUnknownException("The OCSP is signed by a unknown certificate"); } //verify the response signature if (!basicOcspResp.Verify(ocspSignerBc.GetPublicKey())) { throw new RevocationUnknownException("The OCSP has an invalid signature"); } //OCSP must be issued by same issuer an the certificate that it validates. try { if (!ocspSignerBc.IssuerDN.Equals(issuerBC.SubjectDN)) { throw new ApplicationException(); } ocspSignerBc.Verify(issuerBC.GetPublicKey()); } catch (Exception e) { throw new RevocationUnknownException("The OCSP signer was not issued by the proper CA", e); } //verify if the OCSP signer certificate is stil valid if (!ocspSignerBc.IsValid(basicOcspResp.ProducedAt)) { throw new RevocationUnknownException("The OCSP signer was not valid at the time the ocsp was issued"); } //check if the signer may issue OCSP IList ocspSignerExtKeyUsage = ocspSignerBc.GetExtendedKeyUsage(); if (!ocspSignerExtKeyUsage.Contains("1.3.6.1.5.5.7.3.9")) { throw new RevocationUnknownException("The OCSP is signed by a certificate that isn't allowed to sign OCSP"); } //finally, check if the certificate is revoked or not var revokedStatus = (BCO.RevokedStatus)singleOcspResp.GetCertStatus(); if (revokedStatus != null) { trace.TraceEvent(TraceEventType.Verbose, 0, "OCSP response for {0} indicates that the certificate is revoked on {1}", certificate.Subject, revokedStatus.RevocationTime); if (maxTime >= revokedStatus.RevocationTime) { throw new RevocationException <BCAO.BasicOcspResponse>(basicOcspResponse, "The certificate was revoked on " + revokedStatus.RevocationTime.ToString("o")); } } return(basicOcspResponse); }
/** * test for equivalence - note: case is ignored. */ public bool Equivalent( X509Name other) { if (other == null) { return(false); } if (other == this) { return(true); } int orderingSize = ordering.Count; if (orderingSize != other.ordering.Count) { return(false); } bool[] indexes = new bool[orderingSize]; int start, end, delta; if (ordering[0].Equals(other.ordering[0])) // guess forward { start = 0; end = orderingSize; delta = 1; } else // guess reversed - most common problem { start = orderingSize - 1; end = -1; delta = -1; } for (int i = start; i != end; i += delta) { bool found = false; DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i]; string value = (string)values[i]; for (int j = 0; j < orderingSize; j++) { if (indexes[j]) { continue; } DerObjectIdentifier oOid = (DerObjectIdentifier)other.ordering[j]; if (oid.Equals(oOid)) { string oValue = (string)other.values[j]; if (equivalentStrings(value, oValue)) { indexes[j] = true; found = true; break; } } } if (!found) { return(false); } } return(true); }
public GeneralName(X509Name directoryName) { obj = directoryName; tag = 4; }
public void SetIssuer(X509Name issuer) { this.issuer = issuer; }
public bool Equals( X509Name other) { return(Equivalent(other)); }
public bool Equals( X509Name other) { throw new NotImplementedException(); // return Equivalent(other); }
public void SetSubject( X509Name subject) { this.subject = subject; }