private OcspReq GenerateOcspRequest(CertificateID id) { OcspReqGenerator ocspReqGenerator = new OcspReqGenerator(); ocspReqGenerator.AddRequest(id); BigInteger bigInteger = BigInteger.ValueOf(default(DateTime).Ticks); var arrayList = new List <object>(); Hashtable hashtable = new Hashtable(); arrayList.Add(OcspObjectIdentifiers.PkixOcsp); Asn1OctetString value = new DerOctetString(new DerOctetString(new byte[10] { 1, 3, 6, 1, 5, 5, 7, 48, 1, 1 })); hashtable.Add(OcspObjectIdentifiers.PkixOcsp, new X509Extension(false, value)); ocspReqGenerator.SetRequestExtensions(new X509Extensions(arrayList, hashtable)); return(ocspReqGenerator.Generate()); }
private OcspReq GenerateOcspRequest(CertificateID id, GeneralName requestorName, System.Security.Cryptography.X509Certificates.X509Certificate2 signCertificate) { OcspReqGenerator ocspRequestGenerator = new OcspReqGenerator(); ocspRequestGenerator.AddRequest(id); if (requestorName != null) { ocspRequestGenerator.SetRequestorName(requestorName); } ArrayList oids = new ArrayList(); Hashtable values = new Hashtable(); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); _nonceAsn1OctetString = new DerOctetString(new DerOctetString(BigInteger.ValueOf(DateTime.Now.Ticks).ToByteArray())); values.Add(OcspObjectIdentifiers.PkixOcspNonce, new X509Extension(false, _nonceAsn1OctetString)); ocspRequestGenerator.SetRequestExtensions(new X509Extensions(oids, values)); if (signCertificate != null) { return(ocspRequestGenerator.Generate((RSACryptoServiceProvider)signCertificate.PrivateKey, CertUtil.GetCertChain(signCertificate))); } else { return(ocspRequestGenerator.Generate()); } }
public void RequestValidWithNonce() { OcspReqGenerator request_generator = new OcspReqGenerator(); //request_generator.AddRequest OcspReq request_valid; }
private static OcspReq GenerateOCSPRequest(X509Certificate signerCert, X509Certificate checkerCert, X509Certificate issuerCert, AsymmetricKeyParameter checkerKey) { // Generate the id for the certificate we are looking for CertificateID id = new CertificateID(CertificateID.HashSha1, issuerCert, signerCert.SerialNumber); // basic request generation with nonce OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest(id); // create details for nonce extension ArrayList oids = new ArrayList(); ArrayList values = new ArrayList(); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(PdfEncryption.CreateDocumentId()).GetEncoded()))); gen.SetRequestExtensions(new X509Extensions(oids, values)); X509Certificate [] chain = new X509Certificate[2]; chain[0] = checkerCert; chain[1] = signerCert; gen.SetRequestorName(checkerCert.SubjectDN); return(gen.Generate(checkerCert.SigAlgOid, checkerKey, chain)); }
private static byte[] CreateOcspPackage(X509Certificate cert, X509Certificate cacert) { var gen = new OcspReqGenerator(); try { var certId = new CertificateID(CertificateID.HashSha1, cacert, cert.SerialNumber); gen.AddRequest(certId); gen.SetRequestExtensions(CreateExtension()); OcspReq req = gen.Generate(); return(req.GetEncoded()); } catch (OcspException e) { Debug.WriteLine(e.StackTrace); } catch (IOException e) { Debug.WriteLine(e.StackTrace); } return(null); }
static OcspReqAndId CreateOcspRequest(Asn1OctetString issuerNameHash, Asn1OctetString issuerKeyHash, string serialNumber) { var hashAlgorithm = new AlgorithmIdentifier(X509ObjectIdentifiers.IdSha1, DerNull.Instance); var derSerialNumber = new DerInteger(new BigInteger(serialNumber)); var id = new CertID(hashAlgorithm, issuerNameHash, issuerKeyHash, derSerialNumber); var generator = new OcspReqGenerator(); generator.AddRequest(new CertificateID(id)); return(new OcspReqAndId(generator.Generate(), id)); }
/** * Generates an OCSP request using BouncyCastle. * @param issuerCert certificate of the issues * @param serialNumber serial number * @return an OCSP request * @throws OCSPException * @throws IOException */ private static OcspReq GenerateOCSPRequest(Org.BouncyCastle.X509.X509Certificate issuerCert, BigInteger serialNumber) { // Generate the id for the certificate we are looking for CertificateID id = new CertificateID(CertificateID.HashSha1, issuerCert, serialNumber); // basic request generation with nonce. // a nonce is generated from cryptographic random number generators. OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest(id); byte[] sampleNonce = new byte[16]; Random rand = new Random(); rand.NextBytes(sampleNonce); // create details for nonce extension ArrayList oids = new ArrayList(); ArrayList values = new ArrayList(); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(sampleNonce))); gen.SetRequestExtensions(new X509Extensions(oids, values)); // Generate request var req = gen.Generate(); // is the request signed? if (req.IsSigned) { Debug.WriteLine("is signed!"); } Org.BouncyCastle.X509.X509Certificate[] certs = req.GetCerts(); // Check if certs are not null if (certs != null) { Debug.WriteLine("No certs!"); } Req[] requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Debug.WriteLine("id not found!"); } return(req); }
internal static OcspReq GenerateOcspRequestWithNonce(CertificateID id) { OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest(id); // create details for nonce extension IDictionary extensions = new Hashtable(); extensions[OcspObjectIdentifiers.PkixOcspNonce] = new X509Extension(false, new DerOctetString(new DerOctetString(PdfEncryption.GenerateNewDocumentId()).GetEncoded())); gen.SetRequestExtensions(new X509Extensions(extensions)); return(gen.Generate()); }
public ValidationResponse ValidateCertificate(string serialNumber, X509Certificate2 issuer, String urlOCSP) { try { OcspReqGenerator ocspReqGenerator = new OcspReqGenerator(); ocspReqGenerator.AddRequest(new CertificateID(CertificateID.HashSha1, Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuer), new BigInteger(serialNumber, 16))); // Extensions IList oidList = new ArrayList(); IList valueList = new ArrayList(); // nonce byte[] nonce = new byte[16]; Random rand = new Random(); rand.NextBytes(nonce); oidList.Add(OcspObjectIdentifiers.PkixOcspNonce); valueList.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(nonce))); ocspReqGenerator.SetRequestExtensions(new X509Extensions(oidList, valueList)); // requestor name ocspReqGenerator.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name(issuer.Subject))); OcspReq ocspReq = ocspReqGenerator.Generate(); OcspResp ocspResponse = new OcspResp(transferHttpDataService.SendOcspRequest(urlOCSP, ocspReq.GetEncoded())); if (ocspResponse.Status == OcspResponseStatus.Successful) { BasicOcspResp ocspBasicResponse = (BasicOcspResp)ocspResponse.GetResponseObject(); if (ocspBasicResponse.Responses[0].GetCertStatus() == Org.BouncyCastle.Ocsp.CertificateStatus.Good) { return(new ValidationResponse(ValidationExtensions.Enums.CertificateStatus.VALID)); } else if (ocspBasicResponse.Responses[0].GetCertStatus().GetType() == typeof(RevokedStatus)) { return(new ValidationResponse(ValidationExtensions.Enums.CertificateStatus.REVOKED)); } // Default case //else if (ocspBasicResponse.Responses[0].GetCertStatus().GetType() == typeof(UnknownStatus)) //{ } } } catch (System.Exception) { } return(new ValidationResponse(ValidationExtensions.Enums.CertificateStatus.UNKNOWN)); }
private static byte[] GetOcspPackage(BigInteger serialNr, X509Certificate cacert) { OcspReqGenerator gen = new OcspReqGenerator(); try { CertificateID certId = new CertificateID(CertificateID.HashSha1, cacert, serialNr); gen.AddRequest(certId); gen.SetRequestExtensions(GetExtentions()); var req = gen.Generate(); return(req.GetEncoded()); } catch (OcspException e) { throw new CertificateValidationException(e.Message, e); } }
public OcspReq CreateOcspReq() { CertificateID id = new CertificateID(CertificateID.HashSha1, _Issuer, _Certificate.SerialNumber); var gen = new OcspReqGenerator(); gen.AddRequest(id); BigInteger.TryParse(Math.Floor((DateTime.UtcNow - Jan1st1970).TotalSeconds).ToString(), out BigInteger nonce); var ext = new Dictionary <DerObjectIdentifier, X509Extension> { { OcspObjectIdentifiers.PkixOcspNonce, new X509Extension(false, new DerOctetString(nonce.ToByteArray())) } }; gen.SetRequestExtensions(new X509Extensions(ext)); return(gen.Generate()); }
private OcspReq GenerateOcspRequest(CertificateID id) { OcspReqGenerator ocspRequestGenerator = new OcspReqGenerator(); ocspRequestGenerator.AddRequest(id); ArrayList oids = new ArrayList(); Hashtable values = new Hashtable(); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); _nonceAsn1OctetString = new DerOctetString(new DerOctetString(BigInteger.ValueOf(DateTime.Now.Ticks).ToByteArray())); values.Add(OcspObjectIdentifiers.PkixOcspNonce, new X509Extension(false, _nonceAsn1OctetString)); ocspRequestGenerator.SetRequestExtensions(new X509Extensions(oids, values)); return(ocspRequestGenerator.Generate()); }
private OcspReq GenerateOcspRequest(BcX509Certificate issuerCertificate, BigInteger serialNumber) { CertificateID id = new CertificateID(CertificateID.HashSha1, issuerCertificate, serialNumber); OcspReqGenerator generator = new OcspReqGenerator(); generator.AddRequest(id); Dictionary <DerObjectIdentifier, X509Extension> dictionary = new Dictionary <DerObjectIdentifier, X509Extension> { { OcspObjectIdentifiers.PkixOcspNonce, new X509Extension(false, new DerOctetString(BigInteger.ValueOf(DateTime.UtcNow.Ticks).ToByteArray())) } }; generator.SetRequestExtensions(new X509Extensions(dictionary)); return(generator.Generate()); }
/** * Generates an OCSP request using BouncyCastle. * @param issuerCert certificate of the issues * @param serialNumber serial number * @return an OCSP request * @throws OCSPException * @throws IOException */ private static OcspReq GenerateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) { // Generate the id for the certificate we are looking for CertificateID id = new CertificateID(CertificateID.HashSha1, issuerCert, serialNumber); // basic request generation with nonce OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest(id); // create details for nonce extension IDictionary extensions = new Hashtable(); extensions[OcspObjectIdentifiers.PkixOcspNonce] = new X509Extension(false, new DerOctetString(new DerOctetString(PdfEncryption.CreateDocumentId()).GetEncoded())); gen.SetRequestExtensions(new X509Extensions(extensions)); return(gen.Generate()); }
private OcspReq GenerateOcspRequest(CertificateID id) { OcspReqGenerator ocspRequestGenerator = new OcspReqGenerator(); ocspRequestGenerator.AddRequest(id); BigInteger nonce = BigInteger.ValueOf(new DateTime().Ticks); ArrayList oids = new ArrayList(); Hashtable values = new Hashtable(); oids.Add(OcspObjectIdentifiers.PkixOcsp); Asn1OctetString asn1 = new DerOctetString(new DerOctetString(new byte[] { 1, 3, 6, 1, 5, 5, 7, 48, 1, 1 })); values.Add(OcspObjectIdentifiers.PkixOcsp, new X509Extension(false, asn1)); ocspRequestGenerator.SetRequestExtensions(new X509Extensions(oids, values)); return(ocspRequestGenerator.Generate()); }
private static OcspReq GenerateOcspRequest(X509Certificate issuerCert, BigInteger serialNumber) { var ocspRequestGenerator = new OcspReqGenerator(); var id = new CertificateID(CertificateID.HashSha1, issuerCert, serialNumber); ocspRequestGenerator.AddRequest(id); var oids = new List <DerObjectIdentifier>(); var values = new Hashtable(); oids.Add(OcspObjectIdentifiers.PkixOcsp); Asn1OctetString asn1 = new DerOctetString(new DerOctetString(new byte[] { 1, 3, 6, 1, 5, 5, 7, 48, 1, 1 })); values.Add(OcspObjectIdentifiers.PkixOcsp, new X509Extension(false, asn1)); ocspRequestGenerator.SetRequestExtensions(new X509Extensions(oids, values)); return(ocspRequestGenerator.Generate()); }
/// <summary> /// Generates an OCSP request using BouncyCastle. /// @throws OCSPException /// @throws IOException /// </summary> /// <param name="issuerCert">certificate of the issues</param> /// <param name="serialNumber">serial number</param> /// <returns>OCSP request</returns> private static OcspReq generateOcspRequest(X509Certificate issuerCert, BigInteger serialNumber) { // Generate the id for the certificate we are looking for var id = new CertificateID(CertificateID.HashSha1, issuerCert, serialNumber); // basic request generation with nonce var gen = new OcspReqGenerator(); gen.AddRequest(id); // create details for nonce extension var oids = new List <object>(); var values = new List <object>(); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(PdfEncryption.CreateDocumentId()).GetEncoded()))); gen.SetRequestExtensions(new X509Extensions(oids, values)); return(gen.Generate()); }
/// <exception cref="System.IO.IOException"></exception> public BasicOcspResp GetOcspResponse(X509Certificate certificate, X509Certificate issuerCertificate) { try { this.OcspUri = GetAccessLocation(certificate, X509ObjectIdentifiers.OcspAccessMethod); LOG.Info("OCSP URI: " + this.OcspUri); if (this.OcspUri == null) { return(null); } OcspReqGenerator ocspReqGenerator = new OcspReqGenerator(); CertificateID certId = new CertificateID(CertificateID.HashSha1, issuerCertificate , certificate.SerialNumber); ocspReqGenerator.AddRequest(certId); OcspReq ocspReq = ocspReqGenerator.Generate(); byte[] ocspReqData = ocspReq.GetEncoded(); OcspResp ocspResp = new OcspResp(HttpDataLoader.Post(this.OcspUri, new MemoryStream (ocspReqData))); try { return((BasicOcspResp)ocspResp.GetResponseObject()); } catch (ArgumentNullException) { // Encountered a case when the OCSPResp is initialized with a null OCSP response... // (and there are no nullity checks in the OCSPResp implementation) return(null); } } catch (CannotFetchDataException) { return(null); } catch (OcspException e) { LOG.Error("OCSP error: " + e.Message); return(null); } }
public override void PerformTest() { string signDN = "O=Bouncy Castle, C=AU"; AsymmetricCipherKeyPair signKP = OcspTestUtil.MakeKeyPair(); X509Certificate testCert = OcspTestUtil.MakeCertificate(signKP, signDN, signKP, signDN); string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU"; GeneralName origName = new GeneralName(new X509Name(origDN)); // // general id value for our test issuer cert and a serial number. // CertificateID id = new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One); // // basic request generation // OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); OcspReq req = gen.Generate(); if (req.IsSigned) { Fail("signed but shouldn't be"); } X509Certificate[] certs = req.GetCerts(); if (certs != null) { Fail("null certs expected, but not found"); } Req[] requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // request generation with signing // X509Certificate[] chain = new X509Certificate[1]; gen = new OcspReqGenerator(); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withRSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } certs = req.GetCerts(); if (certs == null) { Fail("null certs found"); } if (certs.Length != 1 || !testCert.Equals(certs[0])) { Fail("incorrect certs found in request"); } // // encoding test // byte[] reqEnc = req.GetEncoded(); OcspReq newReq = new OcspReq(reqEnc); if (!newReq.Verify(signKP.Public)) { Fail("newReq signature failed to Verify"); } // // request generation with signing and nonce // chain = new X509Certificate[1]; gen = new OcspReqGenerator(); IList oids = new ArrayList(); IList values = new ArrayList(); byte[] sampleNonce = new byte[16]; Random rand = new Random(); rand.NextBytes(sampleNonce); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(sampleNonce)))); gen.SetRequestExtensions(new X509Extensions(oids, values)); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withRSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } // // extension check. // ISet extOids = req.GetCriticalExtensionOids(); if (extOids.Count != 0) { Fail("wrong number of critical extensions in OCSP request."); } extOids = req.GetNonCriticalExtensionOids(); if (extOids.Count != 1) { Fail("wrong number of non-critical extensions in OCSP request."); } Asn1OctetString extValue = req.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce); Asn1Object extObj = X509ExtensionUtilities.FromExtensionValue(extValue); if (!(extObj is Asn1OctetString)) { Fail("wrong extension type found."); } byte[] compareNonce = ((Asn1OctetString) extObj).GetOctets(); if (!AreEqual(compareNonce, sampleNonce)) { Fail("wrong extension value found."); } // // request list check // requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // response parsing - test 1 // OcspResp response = new OcspResp(testResp1); if (response.Status != 0) { Fail("response status not zero."); } BasicOcspResp brep = (BasicOcspResp) response.GetResponseObject(); chain = brep.GetCerts(); if (!brep.Verify(chain[0].GetPublicKey())) { Fail("response 1 failed to Verify."); } // // test 2 // SingleResp[] singleResp = brep.Responses; response = new OcspResp(testResp2); if (response.Status != 0) { Fail("response status not zero."); } brep = (BasicOcspResp)response.GetResponseObject(); chain = brep.GetCerts(); if (!brep.Verify(chain[0].GetPublicKey())) { Fail("response 2 failed to Verify."); } singleResp = brep.Responses; // // simple response generation // OCSPRespGenerator respGen = new OCSPRespGenerator(); OcspResp resp = respGen.Generate(OCSPRespGenerator.Successful, response.GetResponseObject()); if (!resp.GetResponseObject().Equals(response.GetResponseObject())) { Fail("response fails to match"); } doTestECDsa(); doTestRsa(); doTestIrregularVersionReq(); }
private void doTestECDsa() { string signDN = "O=Bouncy Castle, C=AU"; AsymmetricCipherKeyPair signKP = OcspTestUtil.MakeECKeyPair(); X509Certificate testCert = OcspTestUtil.MakeECDsaCertificate(signKP, signDN, signKP, signDN); string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU"; GeneralName origName = new GeneralName(new X509Name(origDN)); // // general id value for our test issuer cert and a serial number. // CertificateID id = new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One); // // basic request generation // OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest(id); OcspReq req = gen.Generate(); if (req.IsSigned) { Fail("signed but shouldn't be"); } X509Certificate[] certs = req.GetCerts(); if (certs != null) { Fail("null certs expected, but not found"); } Req[] requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // request generation with signing // X509Certificate[] chain = new X509Certificate[1]; gen = new OcspReqGenerator(); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); gen.AddRequest(new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withECDSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } certs = req.GetCerts(); if (certs == null) { Fail("null certs found"); } if (certs.Length != 1 || !certs[0].Equals(testCert)) { Fail("incorrect certs found in request"); } // // encoding test // byte[] reqEnc = req.GetEncoded(); OcspReq newReq = new OcspReq(reqEnc); if (!newReq.Verify(signKP.Public)) { Fail("newReq signature failed to Verify"); } // // request generation with signing and nonce // chain = new X509Certificate[1]; gen = new OcspReqGenerator(); IList oids = new ArrayList(); IList values = new ArrayList(); byte[] sampleNonce = new byte[16]; Random rand = new Random(); rand.NextBytes(sampleNonce); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(sampleNonce)))); gen.SetRequestExtensions(new X509Extensions(oids, values)); gen.AddRequest(new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withECDSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } // // extension check. // ISet extOids = req.GetCriticalExtensionOids(); if (extOids.Count != 0) { Fail("wrong number of critical extensions in OCSP request."); } extOids = req.GetNonCriticalExtensionOids(); if (extOids.Count != 1) { Fail("wrong number of non-critical extensions in OCSP request."); } Asn1OctetString extValue = req.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce); Asn1Encodable extObj = X509ExtensionUtilities.FromExtensionValue(extValue); if (!(extObj is Asn1OctetString)) { Fail("wrong extension type found."); } if (!AreEqual(((Asn1OctetString)extObj).GetOctets(), sampleNonce)) { Fail("wrong extension value found."); } // // request list check // requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // response generation // BasicOcspRespGenerator respGen = new BasicOcspRespGenerator(signKP.Public); respGen.AddResponse(id, CertificateStatus.Good); respGen.Generate("SHA1withECDSA", signKP.Private, chain, DateTime.UtcNow); }
/// <summary> /// Verifies the certificate chain via OCSP /// </summary> /// <returns> /// <c>true</c>, if certificate is revoked, <c>false</c> otherwise. /// </returns> /// <param name='chain'> /// The certificate chain. /// </param> private static bool VerifyCertificateOCSP(System.Security.Cryptography.X509Certificates.X509Chain chain) { List <X509Certificate> certsList = new List <X509Certificate> (); List <Uri> certsUrls = new List <Uri> (); bool bCertificateIsRevoked = false; try { //Get the OCSP URLS to be validated for each certificate. foreach (System.Security.Cryptography.X509Certificates.X509ChainElement cert in chain.ChainElements) { X509Certificate BCCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificate); if (BCCert.CertificateStructure.TbsCertificate.Extensions != null) { X509Extension ext = BCCert.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.AuthorityInfoAccess); if (ext != null) { AccessDescription[] certUrls = AuthorityInformationAccess.GetInstance(ext).GetAccessDescriptions(); Uri url = (certUrls != null && certUrls.Length > 0 && certUrls [0].AccessLocation.Name.ToString().StartsWith("http://")) ? new Uri(certUrls [0].AccessLocation.Name.ToString()) : null; certsList.Add(BCCert); if (!certsUrls.Contains(url)) { certsUrls.Add(url); } } } } if (certsUrls.Count > 0) { //create requests for each cert List <OcspReq> RequestList = new List <OcspReq>(); OcspReqGenerator OCSPRequestGenerator; for (int i = 0; i < (certsList.Count - 1); i++) { OCSPRequestGenerator = new OcspReqGenerator(); BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks); List <DerObjectIdentifier> oids = new List <DerObjectIdentifier> (); oids.Add(Org.BouncyCastle.Asn1.Ocsp.OcspObjectIdentifiers.PkixOcspNonce); List <X509Extension> values = new List <X509Extension> (); values.Add(new X509Extension(false, new DerOctetString(nonce.ToByteArray()))); OCSPRequestGenerator.SetRequestExtensions(new X509Extensions(oids, values)); CertificateID ID = new CertificateID(CertificateID.HashSha1, certsList [i + 1], certsList [i].SerialNumber); OCSPRequestGenerator.AddRequest(ID); RequestList.Add(OCSPRequestGenerator.Generate()); } //send requests to the OCSP server and read the response for (int i = 0; i < certsUrls.Count && !bCertificateIsRevoked; i++) { for (int j = 0; j < RequestList.Count && !bCertificateIsRevoked; j++) { HttpWebRequest requestToOCSPServer = (HttpWebRequest)WebRequest.Create(certsUrls [i]); requestToOCSPServer.Method = "POST"; requestToOCSPServer.ContentType = "application/ocsp-request"; requestToOCSPServer.Accept = "application/ocsp-response"; requestToOCSPServer.ReadWriteTimeout = 15000; // 15 seconds waiting to stablish connection requestToOCSPServer.Timeout = 100000; // 100 seconds timeout reading response byte[] bRequestBytes = RequestList[j].GetEncoded(); using (Stream requestStream = requestToOCSPServer.GetRequestStream()) { requestStream.Write(bRequestBytes, 0, bRequestBytes.Length); requestStream.Flush(); } HttpWebResponse serverResponse = (HttpWebResponse)requestToOCSPServer.GetResponse(); OcspResp OCSPResponse = new OcspResp(serverResponse.GetResponseStream()); BasicOcspResp basicOCSPResponse = (BasicOcspResp)OCSPResponse.GetResponseObject(); //get the status from the response if (basicOCSPResponse != null) { foreach (SingleResp singleResponse in basicOCSPResponse.Responses) { object certStatus = singleResponse.GetCertStatus(); if (certStatus is RevokedStatus) { bCertificateIsRevoked = true; } } } } } } else { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. No OCSP url service found. Cannot verify revocation."); } } catch (Exception e) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Unhandled exception during revocation checking: " + e.Message); bCertificateIsRevoked = true; } if (bCertificateIsRevoked) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation. Certificate is revoked"); } return(bCertificateIsRevoked); }
public override void PerformTest() { string signDN = "O=Bouncy Castle, C=AU"; AsymmetricCipherKeyPair signKP = OcspTestUtil.MakeKeyPair(); X509Certificate testCert = OcspTestUtil.MakeCertificate(signKP, signDN, signKP, signDN); string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU"; GeneralName origName = new GeneralName(new X509Name(origDN)); // // general id value for our test issuer cert and a serial number. // CertificateID id = new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One); // // basic request generation // OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); OcspReq req = gen.Generate(); if (req.IsSigned) { Fail("signed but shouldn't be"); } X509Certificate[] certs = req.GetCerts(); if (certs != null) { Fail("null certs expected, but not found"); } Req[] requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // request generation with signing // X509Certificate[] chain = new X509Certificate[1]; gen = new OcspReqGenerator(); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withRSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } certs = req.GetCerts(); if (certs == null) { Fail("null certs found"); } if (certs.Length != 1 || !testCert.Equals(certs[0])) { Fail("incorrect certs found in request"); } // // encoding test // byte[] reqEnc = req.GetEncoded(); OcspReq newReq = new OcspReq(reqEnc); if (!newReq.Verify(signKP.Public)) { Fail("newReq signature failed to Verify"); } // // request generation with signing and nonce // chain = new X509Certificate[1]; gen = new OcspReqGenerator(); IList oids = new ArrayList(); IList values = new ArrayList(); byte[] sampleNonce = new byte[16]; Random rand = new Random(); rand.NextBytes(sampleNonce); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(sampleNonce)))); gen.SetRequestExtensions(new X509Extensions(oids, values)); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withRSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } // // extension check. // ISet extOids = req.GetCriticalExtensionOids(); if (extOids.Count != 0) { Fail("wrong number of critical extensions in OCSP request."); } extOids = req.GetNonCriticalExtensionOids(); if (extOids.Count != 1) { Fail("wrong number of non-critical extensions in OCSP request."); } Asn1OctetString extValue = req.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce); Asn1Object extObj = X509ExtensionUtilities.FromExtensionValue(extValue); if (!(extObj is Asn1OctetString)) { Fail("wrong extension type found."); } byte[] compareNonce = ((Asn1OctetString)extObj).GetOctets(); if (!AreEqual(compareNonce, sampleNonce)) { Fail("wrong extension value found."); } // // request list check // requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // response parsing - test 1 // OcspResp response = new OcspResp(testResp1); if (response.Status != 0) { Fail("response status not zero."); } BasicOcspResp brep = (BasicOcspResp)response.GetResponseObject(); chain = brep.GetCerts(); if (!brep.Verify(chain[0].GetPublicKey())) { Fail("response 1 failed to Verify."); } // // test 2 // SingleResp[] singleResp = brep.Responses; response = new OcspResp(testResp2); if (response.Status != 0) { Fail("response status not zero."); } brep = (BasicOcspResp)response.GetResponseObject(); chain = brep.GetCerts(); if (!brep.Verify(chain[0].GetPublicKey())) { Fail("response 2 failed to Verify."); } singleResp = brep.Responses; // // simple response generation // OCSPRespGenerator respGen = new OCSPRespGenerator(); OcspResp resp = respGen.Generate(OCSPRespGenerator.Successful, response.GetResponseObject()); if (!resp.GetResponseObject().Equals(response.GetResponseObject())) { Fail("response fails to match"); } doTestECDsa(); doTestRsa(); doTestIrregularVersionReq(); }
private void doTestECDsa() { string signDN = "O=Bouncy Castle, C=AU"; AsymmetricCipherKeyPair signKP = OcspTestUtil.MakeECKeyPair(); X509Certificate testCert = OcspTestUtil.MakeECDsaCertificate(signKP, signDN, signKP, signDN); string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU"; GeneralName origName = new GeneralName(new X509Name(origDN)); // // general id value for our test issuer cert and a serial number. // CertificateID id = new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One); // // basic request generation // OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest(id); OcspReq req = gen.Generate(); if (req.IsSigned) { Fail("signed but shouldn't be"); } X509Certificate[] certs = req.GetCerts(); if (certs != null) { Fail("null certs expected, but not found"); } Req[] requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // request generation with signing // X509Certificate[] chain = new X509Certificate[1]; gen = new OcspReqGenerator(); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); gen.AddRequest(new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withECDSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } certs = req.GetCerts(); if (certs == null) { Fail("null certs found"); } if (certs.Length != 1 || !certs[0].Equals(testCert)) { Fail("incorrect certs found in request"); } // // encoding test // byte[] reqEnc = req.GetEncoded(); OcspReq newReq = new OcspReq(reqEnc); if (!newReq.Verify(signKP.Public)) { Fail("newReq signature failed to Verify"); } // // request generation with signing and nonce // chain = new X509Certificate[1]; gen = new OcspReqGenerator(); IList oids = new ArrayList(); IList values = new ArrayList(); byte[] sampleNonce = new byte[16]; Random rand = new Random(); rand.NextBytes(sampleNonce); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(sampleNonce)))); gen.SetRequestExtensions(new X509Extensions(oids, values)); gen.AddRequest(new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withECDSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } // // extension check. // ISet extOids = req.GetCriticalExtensionOids(); if (extOids.Count != 0) { Fail("wrong number of critical extensions in OCSP request."); } extOids = req.GetNonCriticalExtensionOids(); if (extOids.Count != 1) { Fail("wrong number of non-critical extensions in OCSP request."); } Asn1OctetString extValue = req.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce); Asn1Encodable extObj = X509ExtensionUtilities.FromExtensionValue(extValue); if (!(extObj is Asn1OctetString)) { Fail("wrong extension type found."); } if (!AreEqual(((Asn1OctetString)extObj).GetOctets(), sampleNonce)) { Fail("wrong extension value found."); } // // request list check // requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // response generation // BasicOcspRespGenerator respGen = new BasicOcspRespGenerator(signKP.Public); respGen.AddResponse(id, CertificateStatus.Good); respGen.Generate("SHA1withECDSA", signKP.Private, chain, DateTime.UtcNow); }
// todo: add unit test for OCSP (possible regressions with using RSA instead of RSACryptoServiceProvider) public static OcspReq Generate(this OcspReqGenerator ocspRegGenerator, RSA rsa, X509Chain chain) { Asn1EncodableVector requests = new Asn1EncodableVector(); DerObjectIdentifier signingAlgorithm = PkcsObjectIdentifiers.Sha1WithRsaEncryption; IList list = null; Type OcspReqGeneratorInfo_Type = typeof(OcspReqGenerator); FieldInfo ListInfo_m_parameters = OcspReqGeneratorInfo_Type.GetField("list", BindingFlags.NonPublic | BindingFlags.Instance); list = (IList)ListInfo_m_parameters.GetValue(ocspRegGenerator); Type RequestObjectType = OcspReqGeneratorInfo_Type.GetNestedType("RequestObject", BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo toRequestMethod = RequestObjectType.GetMethod("ToRequest"); foreach (object reqObj in list) { try { requests.Add((Request)toRequestMethod.Invoke(reqObj, null)); } catch (Exception e) { throw new OcspException("exception creating Request", e); } } GeneralName requestorName; FieldInfo GeneralNameInfo_m_parameters = OcspReqGeneratorInfo_Type.GetField("requestorName", BindingFlags.NonPublic | BindingFlags.Instance); requestorName = (GeneralName)GeneralNameInfo_m_parameters.GetValue(ocspRegGenerator); X509Extensions requestExtensions = null; FieldInfo requestExtensions_parameters = OcspReqGeneratorInfo_Type.GetField("requestExtensions", BindingFlags.NonPublic | BindingFlags.Instance); requestExtensions = (X509Extensions)requestExtensions_parameters.GetValue(ocspRegGenerator); TbsRequest tbsReq = new TbsRequest(requestorName, new DerSequence(requests), requestExtensions); Org.BouncyCastle.Asn1.Ocsp.Signature signature = null; if (signingAlgorithm != null) { if (requestorName == null) { throw new OcspException("requestorName must be specified if request is signed."); } DerBitString bitSig = null; try { byte[] encoded = tbsReq.GetEncoded(); byte[] signedData = rsa.SignData(encoded, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); bitSig = new DerBitString(signedData); } catch (Exception e) { throw new OcspException("exception processing TBSRequest: " + e, e); } AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance); if (chain != null && chain.ChainElements.Count > 0) { Asn1EncodableVector v = new Asn1EncodableVector(); try { for (int i = 0; i != chain.ChainElements.Count; i++) { v.Add( X509CertificateStructure.GetInstance( Asn1Object.FromByteArray(chain.ChainElements[i].Certificate.RawData))); } } catch (Exception e) { throw new OcspException("error processing certs", e); } signature = new Org.BouncyCastle.Asn1.Ocsp.Signature(sigAlgId, bitSig, new DerSequence(v)); } else { signature = new Org.BouncyCastle.Asn1.Ocsp.Signature(sigAlgId, bitSig); } } return(new OcspReq(new OcspRequest(tbsReq, signature))); }