Beispiel #1
0
 public FirmaXades.Clients.CertificateStatus ProcessOcspResponse(byte[] binaryResp)
 {
     if (binaryResp.Length != 0)
     {
         OcspResp ocspResp = new OcspResp(binaryResp);
         FirmaXades.Clients.CertificateStatus result = FirmaXades.Clients.CertificateStatus.Unknown;
         if (ocspResp.Status != 0)
         {
             throw new Exception("Unknow status '" + ocspResp.Status + "'.");
         }
         BasicOcspResp basicOcspResp = (BasicOcspResp)ocspResp.GetResponseObject();
         if (basicOcspResp.Responses.Length == 1)
         {
             SingleResp singleResp = basicOcspResp.Responses[0];
             object     certStatus = singleResp.GetCertStatus();
             if (certStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
             {
                 result = FirmaXades.Clients.CertificateStatus.Good;
             }
             else if (certStatus is RevokedStatus)
             {
                 result = FirmaXades.Clients.CertificateStatus.Revoked;
             }
             else if (certStatus is UnknownStatus)
             {
                 result = FirmaXades.Clients.CertificateStatus.Unknown;
             }
         }
         return(result);
     }
     return(FirmaXades.Clients.CertificateStatus.Unknown);
 }
Beispiel #2
0
        public BasicOcspResp GetOcspStatus(OcspReq ocspRequest)
        {
            byte[]   reqArray = ocspRequest.GetEncoded();
            var      uris     = GetOcspUris();
            OcspResp resp;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uris[0]);
                request.Method = "POST";
                var requestStream = request.GetRequestStream();
                request.ContentLength = reqArray.Length;
                request.ContentType   = "application/ocsp-request";
                request.Accept        = "application/ocsp-response";
                requestStream.Write(reqArray, 0, reqArray.Length);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    using (Stream stream = response.GetResponseStream())
                    {
                        resp = new OcspResp(stream);
                    }
                return((BasicOcspResp)resp.GetResponseObject());
            }
            catch
            {
                return(null);
            }
        }
Beispiel #3
0
 /// <summary>Gets OCSP response.</summary>
 /// <remarks>
 /// Gets OCSP response. If
 /// <see cref="OCSPVerifier"/>
 /// was set, the response will be checked.
 /// </remarks>
 /// <param name="checkCert">to certificate to check</param>
 /// <param name="rootCert">the parent certificate</param>
 /// <param name="url">to get the verification</param>
 public virtual BasicOcspResp GetBasicOCSPResp(X509Certificate checkCert, X509Certificate rootCert, String
                                               url)
 {
     try {
         OcspResp ocspResponse = GetOcspResponse(checkCert, rootCert, url);
         if (ocspResponse == null)
         {
             return(null);
         }
         if (ocspResponse.Status != Org.BouncyCastle.Asn1.Ocsp.OcspResponseStatus.Successful)
         {
             return(null);
         }
         BasicOcspResp basicResponse = (BasicOcspResp)ocspResponse.GetResponseObject();
         if (verifier != null)
         {
             verifier.IsValidResponse(basicResponse, rootCert);
         }
         return(basicResponse);
     }
     catch (Exception ex) {
         LOGGER.Error(ex.Message);
     }
     return(null);
 }
Beispiel #4
0
        /// <summary>Gets OCSP responses from the Document Security Store.</summary>
        /// <returns>a list of BasicOCSPResp objects</returns>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        public virtual IList <BasicOcspResp> GetOCSPResponsesFromDSS()
        {
            IList <BasicOcspResp> ocsps = new List <BasicOcspResp>();

            if (dss == null)
            {
                return(ocsps);
            }
            PdfArray ocsparray = dss.GetAsArray(PdfName.OCSPs);

            if (ocsparray == null)
            {
                return(ocsps);
            }
            for (int i = 0; i < ocsparray.Size(); i++)
            {
                PdfStream stream       = ocsparray.GetAsStream(i);
                OcspResp  ocspResponse = new OcspResp(stream.GetBytes());
                if (ocspResponse.Status == 0)
                {
                    try {
                        ocsps.Add((BasicOcspResp)ocspResponse.GetResponseObject());
                    }
                    catch (OcspException e) {
                        throw new GeneralSecurityException(e.ToString());
                    }
                }
            }
            return(ocsps);
        }
Beispiel #5
0
        public static BasicOcspResp GetInvalidOcspResp()
        {
            var bytes    = File.ReadAllBytes(@"Data\InvalidOCSP.txt");
            var ocspResp = new OcspResp(bytes);

            return((BasicOcspResp)ocspResp.GetResponseObject());
        }
Beispiel #6
0
        private X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer, IEnumerable <string> ocspServers, FirmaXades.Crypto.DigestMethod digestMethod)
        {
            bool          byKey = false;
            List <string> list  = new List <string>();

            Org.BouncyCastle.X509.X509Certificate eeCert          = client.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate x509Certificate = issuer.ToBouncyX509Certificate();
            OcspClient ocspClient = new OcspClient();
            string     authorityInformationAccessOcspUrl = ocspClient.GetAuthorityInformationAccessOcspUrl(x509Certificate);

            if (!string.IsNullOrEmpty(authorityInformationAccessOcspUrl))
            {
                list.Add(authorityInformationAccessOcspUrl);
            }
            foreach (string ocspServer in ocspServers)
            {
                list.Add(ocspServer);
            }
            foreach (string item in list)
            {
                byte[] array = ocspClient.QueryBinary(eeCert, x509Certificate, item);
                switch (ocspClient.ProcessOcspResponse(array))
                {
                case FirmaXades.Clients.CertificateStatus.Revoked:
                    throw new Exception("Certificado revocado");

                case FirmaXades.Clients.CertificateStatus.Good:
                {
                    OcspResp      ocspResp      = new OcspResp(array);
                    byte[]        encoded       = ocspResp.GetEncoded();
                    BasicOcspResp basicOcspResp = (BasicOcspResp)ocspResp.GetResponseObject();
                    string        str           = Guid.NewGuid().ToString();
                    OCSPRef       oCSPRef       = new OCSPRef();
                    oCSPRef.OCSPIdentifier.UriAttribute = "#OcspValue" + str;
                    DigestUtil.SetCertDigest(encoded, digestMethod, oCSPRef.CertDigest);
                    ResponderID responderId   = basicOcspResp.ResponderId.ToAsn1Object();
                    string      responderName = GetResponderName(responderId, ref byKey);
                    if (!byKey)
                    {
                        oCSPRef.OCSPIdentifier.ResponderID = RevertIssuerName(responderName);
                    }
                    else
                    {
                        oCSPRef.OCSPIdentifier.ResponderID = responderName;
                        oCSPRef.OCSPIdentifier.ByKey       = true;
                    }
                    oCSPRef.OCSPIdentifier.ProducedAt = basicOcspResp.ProducedAt.ToLocalTime();
                    unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.OCSPRefs.OCSPRefCollection.Add(oCSPRef);
                    OCSPValue oCSPValue = new OCSPValue();
                    oCSPValue.PkiData = encoded;
                    oCSPValue.Id      = "OcspValue" + str;
                    unsignedProperties.UnsignedSignatureProperties.RevocationValues.OCSPValues.OCSPValueCollection.Add(oCSPValue);
                    return((from cert in basicOcspResp.GetCerts()
                            select new X509Certificate2(cert.GetEncoded())).ToArray());
                }
                }
            }
            throw new Exception("El certificado no ha podido ser validado");
        }
Beispiel #7
0
        /**
         * @return  a byte array
         * @see com.lowagie.text.pdf.OcspClient#getEncoded()
         */
        public byte[] GetEncoded()
        {
            OcspReq request = GenerateOCSPRequest(rootCert, checkCert.SerialNumber);

            byte[]         array = request.GetEncoded();
            HttpWebRequest con   = (HttpWebRequest)WebRequest.Create(url);

            con.ContentLength = array.Length;
            con.ContentType   = "application/ocsp-request";
            con.Accept        = "application/ocsp-response";
            con.Method        = "POST";
            Stream outp = con.GetRequestStream();

            outp.Write(array, 0, array.Length);
            outp.Close();
            HttpWebResponse response = (HttpWebResponse)con.GetResponse();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new IOException(MessageLocalization.GetComposedMessage("invalid.http.response.1", (int)response.StatusCode));
            }
            Stream   inp          = response.GetResponseStream();
            OcspResp ocspResponse = new OcspResp(inp);

            inp.Close();
            response.Close();

            if (ocspResponse.Status != 0)
            {
                throw new IOException(MessageLocalization.GetComposedMessage("invalid.status.1", ocspResponse.Status));
            }
            BasicOcspResp basicResponse = (BasicOcspResp)ocspResponse.GetResponseObject();

            if (basicResponse != null)
            {
                SingleResp[] responses = basicResponse.Responses;
                if (responses.Length == 1)
                {
                    SingleResp resp   = responses[0];
                    Object     status = resp.GetCertStatus();
                    if (status == CertificateStatus.Good)
                    {
                        return(basicResponse.GetEncoded());
                    }
                    else if (status is Org.BouncyCastle.Ocsp.RevokedStatus)
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("ocsp.status.is.revoked"));
                    }
                    else
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("ocsp.status.is.unknown"));
                    }
                }
            }
            return(null);
        }
Beispiel #8
0
        static BasicOcspResp GetResponseObject(OcspResp ocspResp)
        {
            var response = (BasicOcspResp)ocspResp.GetResponseObject();

            if (response == null)
            {
                throw new OcspException("Did not return basic response");
            }
            return(response);
        }
        /// <summary>
        /// @see com.lowagie.text.pdf.OcspClient#getEncoded()
        /// </summary>
        /// <returns>	a byte array</returns>
        public byte[] GetEncoded()
        {
            OcspReq request = generateOcspRequest(_rootCert, _checkCert.SerialNumber);

            byte[]         array = request.GetEncoded();
            HttpWebRequest con   = (HttpWebRequest)WebRequest.Create(_url);

            con.ContentType = "application/ocsp-request";
            con.Accept      = "application/ocsp-response";
            con.Method      = "POST";
            Stream outp = con.GetRequestStreamAsync().Result;

            outp.Write(array, 0, array.Length);
            outp.Dispose();
            HttpWebResponse response = (HttpWebResponse)con.GetResponseAsync().Result;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new IOException($"Invalid HTTP response: {(int) response.StatusCode}");
            }
            Stream   inp          = response.GetResponseStream();
            OcspResp ocspResponse = new OcspResp(inp);

            inp.Dispose();
            response.Dispose();

            if (ocspResponse.Status != 0)
            {
                throw new IOException("Invalid status: " + ocspResponse.Status);
            }
            BasicOcspResp basicResponse = (BasicOcspResp)ocspResponse.GetResponseObject();

            if (basicResponse != null)
            {
                SingleResp[] responses = basicResponse.Responses;
                if (responses.Length == 1)
                {
                    SingleResp resp   = responses[0];
                    object     status = resp.GetCertStatus();
                    if (status == CertificateStatus.Good)
                    {
                        return(basicResponse.GetEncoded());
                    }
                    else if (status is RevokedStatus)
                    {
                        throw new IOException("OCSP Status is revoked!");
                    }
                    else
                    {
                        throw new IOException("OCSP Status is unknown!");
                    }
                }
            }
            return(null);
        }
Beispiel #10
0
 /// <summary>Convert a OcspResp in a BasicOcspResp</summary>
 /// <param name="ocspResp"></param>
 /// <returns></returns>
 public static BasicOcspResp FromRespToBasic(OcspResp ocspResp)
 {
     try
     {
         return((BasicOcspResp)ocspResp.GetResponseObject());
     }
     catch (OcspException e)
     {
         throw new RuntimeException(e);
     }
 }
Beispiel #11
0
        public virtual async Task <OcspResponse> SendOcspRequest(HttpWebRequest request)
        {
            OcspResp resp;

            using (WebResponse response = await request.GetResponseAsync())
                using (Stream stream = response.GetResponseStream())
                {
                    resp = new OcspResp(stream);
                    return(ParseOcspResponse((BasicOcspResp)resp.GetResponseObject()));
                }
        }
Beispiel #12
0
        private OcspStatus VerifyResponse(byte[] response)
        {
            OcspResp   r           = new OcspResp(response);
            OcspStatus cStatusEnum = OcspStatus.Unknown;

            switch (r.Status)
            {
            case OcspRespStatus.Successful:
                var or = (BasicOcspResp)r.GetResponseObject();

                Debug.WriteLine(or.Responses.Length);

                if (or.Responses.Length == 1)
                {
                    SingleResp resp = or.Responses[0];

                    var certificateStatus = resp.GetCertStatus();

                    if (certificateStatus == null || certificateStatus == CertificateStatus.Good)
                    {
                        cStatusEnum = OcspStatus.Good;
                    }
                    else if (certificateStatus is RevokedStatus)
                    {
                        cStatusEnum = OcspStatus.Revoked;
                    }
                    else if (certificateStatus is UnknownStatus)
                    {
                        cStatusEnum = OcspStatus.Unknown;
                    }
                }
                break;

            case OcspResponseStatus.InternalError:
            case OcspResponseStatus.TryLater:
                cStatusEnum = OcspStatus.ServerError;
                break;

            case OcspResponseStatus.MalformedRequest:
            case OcspResponseStatus.SignatureRequired:
            case OcspResponseStatus.Unauthorized:
                cStatusEnum = OcspStatus.ClientError;
                break;

            default:
                Debug.WriteLine($"Unknow status '{r.Status}'.");
                cStatusEnum = OcspStatus.Unknown;
                break;
            }

            return(cStatusEnum);
        }
Beispiel #13
0
        /// <summary>
        /// Procesa la respuesta del servidor OCSP y devuelve el estado del certificado
        /// </summary>
        /// <param name="binaryResp"></param>
        /// <returns></returns>
        public CertificateStatus ProcessOcspResponse(byte[] binaryResp, bool checkNonce)
        {
            if (binaryResp.Length == 0)
            {
                return(CertificateStatus.Unknown);
            }

            OcspResp          r       = new OcspResp(binaryResp);
            CertificateStatus cStatus = CertificateStatus.Unknown;

            if (r.Status == OcspRespStatus.Successful)
            {
                BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();

                if (checkNonce)
                {
                    if (or.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce).ToString() !=
                        _nonceAsn1OctetString.ToString())
                    {
                        throw new Exception("Bad nonce value");
                    }
                }

                if (or.Responses.Length == 1)
                {
                    SingleResp resp = or.Responses[0];

                    object certificateStatus = resp.GetCertStatus();

                    if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
                    {
                        cStatus = CertificateStatus.Good;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus)
                    {
                        cStatus = CertificateStatus.Revoked;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus)
                    {
                        cStatus = CertificateStatus.Unknown;
                    }
                }
            }
            else
            {
                throw new Exception("Unknow status '" + r.Status + "'.");
            }

            return(cStatus);
        }
Beispiel #14
0
        private CertificateStatus processOcspResponse(X509Certificate clientCert, X509Certificate issuerCert, byte[] binaryResp, out string respMsg)
        {
            OcspResp          r       = new OcspResp(binaryResp);
            CertificateStatus cStatus = CertificateStatus.unknown;

            switch (r.Status)
            {
            case OcspRespStatus.Successful:

                BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();
                validateResponse(or, issuerCert);
                respMsg = string.Empty;

                if (or.Responses.Length == 1)
                {
                    SingleResp resp = or.Responses[0];

                    validateCertificateId(issuerCert, clientCert, resp.GetCertID());
                    validateThisUpdate(resp);
                    validateNextUpdate(resp);

                    Object certificateStatus = resp.GetCertStatus();

                    if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
                    {
                        cStatus = CertificateStatus.good;
                        respMsg = "Certificado Válido";
                    }
                    else if (certificateStatus is RevokedStatus)
                    {
                        cStatus = CertificateStatus.revoked;
                        respMsg = "Certificado Revocado";
                    }
                    else if (certificateStatus is UnknownStatus)
                    {
                        cStatus = CertificateStatus.unknown;
                        respMsg = "Certificado Desconocido";
                    }
                }
                break;

            default:
                respMsg = "No se ha podido procesar la respuesta OCSP";
                //throw new Exception("Status Desconocido '" + r.Status + "'.");
                return(cStatus);
            }

            return(cStatus);
        }
Beispiel #15
0
        private static CertificateStatusType ProcessOcspResponse(X509Certificate eeCert, X509Certificate issuerCert, byte[] binaryResp)
        {
            var r       = new OcspResp(binaryResp);
            var cStatus = CertificateStatusType.Unknown;

            switch (r.Status)
            {
            case OcspRespStatus.Successful:
                var or = (BasicOcspResp)r.GetResponseObject();

                if (or.Responses.Length == 1)
                {
                    var resp = or.Responses[0];

                    IsValidCertificateId(issuerCert, eeCert, resp.GetCertID());

                    var certificateStatus = resp.GetCertStatus();

                    if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
                    {
                        cStatus = CertificateStatusType.Active;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus)
                    {
                        cStatus = CertificateStatusType.Revoked;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus)
                    {
                        cStatus = CertificateStatusType.Unknown;
                    }
                }
                break;

            case OcspRespStatus.Unauthorized:
                cStatus = CertificateStatusType.Unknown;
                break;

            case OcspRespStatus.TryLater:
                cStatus = CertificateStatusType.Unknown;
                break;

            default:
                cStatus = CertificateStatusType.Unknown;
                break;
            }

            return(cStatus);
        }
        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 CertificateStatus ProcessOcspResponse(X509Certificate eeCert, X509Certificate issuerCert, byte[] binaryResp)
        {
            OcspResp          r       = new OcspResp(binaryResp);
            CertificateStatus cStatus = CertificateStatus.Unknown;

            switch (r.Status)
            {
            case OcspRespStatus.Successful:
                BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();

                ValidateResponse(or, issuerCert);

                if (or.Responses.Length == 1)
                {
                    SingleResp resp = or.Responses[0];

                    ValidateCertificateId(issuerCert, eeCert, resp.GetCertID());
                    ValidateThisUpdate(resp);
                    ValidateNextUpdate(resp);

                    Object certificateStatus = resp.GetCertStatus();

                    if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
                    {
                        cStatus = CertificateStatus.Good;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus)
                    {
                        cStatus = CertificateStatus.Revoked;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus)
                    {
                        cStatus = CertificateStatus.Unknown;
                    }
                }
                break;

            default:
                throw new OCSPExpection("Unknown status '" + r.Status + "'.");
            }

            return(cStatus);
        }
Beispiel #18
0
        /// <summary>
        /// Procesa la respuesta del servidor OCSP y devuelve el estado del certificado
        /// </summary>
        /// <param name="eeCert"></param>
        /// <param name="issuerCert"></param>
        /// <param name="binaryResp"></param>
        /// <returns></returns>
        public CertificateStatus ProcessOcspResponse(X509Certificate eeCert, X509Certificate issuerCert, byte[] binaryResp)
        {
            if (binaryResp.Length == 0)
            {
                return(CertificateStatus.Unknown);
            }

            OcspResp          r       = new OcspResp(binaryResp);
            CertificateStatus cStatus = CertificateStatus.Unknown;

            if (r.Status == OcspRespStatus.Successful)
            {
                BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();

                if (or.Responses.Length == 1)
                {
                    SingleResp resp = or.Responses[0];

                    object certificateStatus = resp.GetCertStatus();

                    if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
                    {
                        cStatus = CertificateStatus.Good;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus)
                    {
                        cStatus = CertificateStatus.Revoked;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus)
                    {
                        cStatus = CertificateStatus.Unknown;
                    }
                }
            }
            else
            {
                throw new Exception("Unknow status '" + r.Status + "'.");
            }

            return(cStatus);
        }
Beispiel #19
0
        private CertificateStatus ProcesarRespuestaOcsp(X509Certificate in_Certificado, X509Certificate in_CertificadoEmisor, byte[] in_BytesRespuesta)
        {
            OcspResp          r      = new OcspResp(in_BytesRespuesta);
            CertificateStatus estado = CertificateStatus.Unknown;

            switch (r.Status)
            {
            case OcspRespStatus.Successful:
                BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();


                if (or.Responses.Length == 1)
                {
                    SingleResp resp = or.Responses[0];

                    ValidarCertificateId(in_CertificadoEmisor, in_Certificado, resp.GetCertID());
                    Object estadoCertificado = resp.GetCertStatus();

                    if (estadoCertificado == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
                    {
                        estado = CertificateStatus.Good;
                    }
                    else if (estadoCertificado is Org.BouncyCastle.Ocsp.RevokedStatus)
                    {
                        estado = CertificateStatus.Revoked;
                    }
                    else if (estadoCertificado is Org.BouncyCastle.Ocsp.UnknownStatus)
                    {
                        estado = CertificateStatus.Unknown;
                    }
                }
                break;

            default:
                throw new Exception("Status desconocido'" + r.Status + "'.");
            }

            return(estado);
        }
Beispiel #20
0
 public BasicOcspResp GetBasicOCSPResp(X509Certificate checkCert, X509Certificate rootCert, String url)
 {
     try {
         OcspResp ocspResponse = GetOcspResponse(checkCert, rootCert, url);
         if (ocspResponse == null)
         {
             return(null);
         }
         if (ocspResponse.Status != 0)
         {
             return(null);
         }
         return((BasicOcspResp)ocspResponse.GetResponseObject());
     }
     catch (Exception ex) {
         if (LOGGER.IsLogging(Level.ERROR))
         {
             LOGGER.Error(ex.Message);
         }
     }
     return(null);
 }
Beispiel #21
0
 /// <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 byte[] Sign(Stream data)
            {
                BasicOcspResp basicResp = (BasicOcspResp)ocspResp.GetResponseObject();

                byte[] oc = basicResp.GetEncoded();
                Collection <byte[]> ocspCollection = new Collection <byte[]>();

                ocspCollection.Add(oc);
                String   hashAlgorithm = "SHA256";
                PdfPKCS7 sgn           = new PdfPKCS7(null, chain, hashAlgorithm, false);

                byte[] hash = DigestAlgorithms.Digest(data, DigestAlgorithms.GetMessageDigest(hashAlgorithm));

                byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, PdfSigner.CryptoStandard.CADES, ocspCollection,
                                                               null);

                //create sha256 message digest
                using (SHA256 sha256 = SHA256.Create()) {
                    sh = sha256.ComputeHash(sh);
                }

                //create hex encoded sha256 message digest
                String hexencodedDigest = new BigInteger(1, sh).ToString(16).ToUpper();

                JObject signed = PDFSigningService.Sign(baseURL, id, hexencodedDigest, access);
                String  sig    = (String)signed.GetValue("signature");

                //decode hex signature
                byte[] dsg = Hex.Decode(sig);

                //include signature on PDF
                sgn.SetExternalDigest(dsg, null, "RSA");

                //create TimeStamp Client
                ITSAClient tsc = new DSSTSAClient(access);

                return(sgn.GetEncodedPKCS7(hash, PdfSigner.CryptoStandard.CADES, tsc, ocspCollection, null));
            }
Beispiel #23
0
        public byte[] GetEncoded()
        {
            ocspRequest = GenerateOCSPRequest(signerCert, checkerCert, issuerCert, checkerKey);
            byte[]         array = ocspRequest.GetEncoded();
            HttpWebRequest con   = (HttpWebRequest)WebRequest.Create(url);

            con.ContentLength = array.Length;
            con.ContentType   = "application/ocsp-request";
            con.Accept        = "application/ocsp-response";
            con.Method        = "POST";
            Stream outp = con.GetRequestStream();

            outp.Write(array, 0, array.Length);
            outp.Close();
            HttpWebResponse response = (HttpWebResponse)con.GetResponse();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                this.lastError = "Invalid HTTP response: " + (int)response.StatusCode;
                return(null);
            }

            Stream inp = response.GetResponseStream();

            ocspResponse = new OcspResp(inp);
            inp.Close();
            response.Close();

            int verify = VerifyOCSPResponse();

            if (verify != (int)CertStatus.GOOD)
            {
                return(null);
            }

            return(((BasicOcspResp)ocspResponse.GetResponseObject()).GetEncoded());
        }
Beispiel #24
0
        private CertificateStatus ProcessOcspResponse(X509Certificate eeCert, X509Certificate issuerCert, byte[] binaryResp)
        {
            OcspResp          r       = new OcspResp(binaryResp);
            CertificateStatus cStatus = null;

            switch (r.Status)
            {
            case OcspRespStatus.Successful:
                BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();

                if (or.Responses.Length == 1)
                {
                    SingleResp resp = or.Responses[0];

                    ValidateCertificateId(issuerCert, eeCert, resp.GetCertID());
                    Object certificateStatus = resp.GetCertStatus();
                    if (certificateStatus == Org.BouncyCastle.Ocsp.CertificateStatus.Good)
                    {
                        cStatus = CertificateStatus.Good;
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus)
                    {
                        throw new Exception(Resource.ErrorOscpRevocado);
                    }
                    else if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus)
                    {
                        throw new Exception(Resource.ErrorOscpDesconocido);
                    }
                }
                break;

            default:
                throw new Exception(Resource.ErrorOscpDesconocido);
            }

            return(cStatus);
        }
Beispiel #25
0
        private OcspCheckStatus ParseOcspResponse(byte[] raw)
        {
            OcspResp response = new OcspResp(raw);

            if (response.Status == OcspRespStatus.Unauthorized)
            {
                return(OcspCheckStatus.Unauthorized);
            }
            else if (response.Status != OcspResponseStatus.Successful)
            {
                return(OcspCheckStatus.Error);
            }

            var brep = (BasicOcspResp)response.GetResponseObject();

            SingleResp[] singleResps = brep.Responses;
            SingleResp   singleResp  = singleResps[0];
            Object       status      = singleResp.GetCertStatus();

            if (status == null)
            {
                return(OcspCheckStatus.Good);
            }

            if (status is RevokedStatus)
            {
                return(OcspCheckStatus.Revoked);
            }

            if (status is UnknownStatus)
            {
                return(OcspCheckStatus.Unknown);
            }

            return(OcspCheckStatus.Error);
        }
Beispiel #26
0
 /// <summary>
 /// Convert a OcspResp in a BasicOcspResp
 /// </summary>
 public static BasicOcspResp FromRespToBasic(OcspResp ocspResp)
 {
     return((BasicOcspResp)ocspResp.GetResponseObject());
 }
Beispiel #27
0
		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 X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer,
                                                             IEnumerable <OcspServer> ocspServers, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl)
        {
            bool byKey = false;
            List <OcspServer> finalOcspServers = new List <OcspServer>();

            Org.BouncyCastle.X509.X509Certificate clientCert = client.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate issuerCert = issuer.ToBouncyX509Certificate();

            OcspClient ocsp = new OcspClient();

            if (addCertificateOcspUrl)
            {
                string certOcspUrl = ocsp.GetAuthorityInformationAccessOcspUrl(issuerCert);

                if (!string.IsNullOrEmpty(certOcspUrl))
                {
                    finalOcspServers.Add(new OcspServer(certOcspUrl));
                }
            }

            foreach (var ocspServer in ocspServers)
            {
                finalOcspServers.Add(ocspServer);
            }

            foreach (var ocspServer in finalOcspServers)
            {
                byte[] resp = ocsp.QueryBinary(clientCert, issuerCert, ocspServer.Url, ocspServer.RequestorName,
                                               ocspServer.SignCertificate);

                FirmaXadesNet.Clients.CertificateStatus status = ocsp.ProcessOcspResponse(resp);

                if (status == FirmaXadesNet.Clients.CertificateStatus.Revoked)
                {
                    throw new Exception("Certificado revocado");
                }
                else if (status == FirmaXadesNet.Clients.CertificateStatus.Good)
                {
                    Org.BouncyCastle.Ocsp.OcspResp r = new OcspResp(resp);
                    byte[]        rEncoded           = r.GetEncoded();
                    BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();

                    string guidOcsp = Guid.NewGuid().ToString();

                    OCSPRef ocspRef = new OCSPRef();
                    ocspRef.OCSPIdentifier.UriAttribute = "#OcspValue" + guidOcsp;
                    DigestUtil.SetCertDigest(rEncoded, digestMethod, ocspRef.CertDigest);

                    ResponderID rpId = or.ResponderId.ToAsn1Object();
                    ocspRef.OCSPIdentifier.ResponderID = GetResponderName(rpId, ref byKey);
                    ocspRef.OCSPIdentifier.ByKey       = byKey;

                    ocspRef.OCSPIdentifier.ProducedAt = or.ProducedAt.ToLocalTime();
                    unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.OCSPRefs.OCSPRefCollection.Add(ocspRef);

                    OCSPValue ocspValue = new OCSPValue();
                    ocspValue.PkiData = rEncoded;
                    ocspValue.Id      = "OcspValue" + guidOcsp;
                    unsignedProperties.UnsignedSignatureProperties.RevocationValues.OCSPValues.OCSPValueCollection.Add(ocspValue);

                    return((from cert in or.GetCerts()
                            select new X509Certificate2(cert.GetEncoded())).ToArray());
                }
            }

            throw new Exception("El certificado no ha podido ser validado");
        }
Beispiel #29
0
        /// <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);
        }
Beispiel #30
0
        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();
        }
Beispiel #31
0
        /// <summary>
        /// Validate a certificate against its AIA OCSP.
        /// </summary>
        /// <param name="cert"></param>
        /// <param name="aia"></param>
        /// <returns></returns>
        CertStatus Validate(System.Security.Cryptography.X509Certificates.X509Certificate2 cert,
                            AIA aia)
        {
            string hash     = ComputeSHA1(System.Text.ASCIIEncoding.ASCII.GetBytes(aia.Issuer));
            string filePath = IssuerCachedFolder + hash;

            //Check if aki is cached
            if (!IsIssuerCached(aia.Issuer))
            {
                Download(aia.Issuer, filePath);
                if (!IsIssuerCached(aia.Issuer))
                {
                    return(CertStatus.Unknown(CertStatus.BadIssuer));
                }
            }

            var issuerTemp    = new System.Security.Cryptography.X509Certificates.X509Certificate2(filePath);
            var certParser    = new Org.BouncyCastle.X509.X509CertificateParser();
            var issuer        = certParser.ReadCertificate(issuerTemp.RawData);
            var cert2Validate = certParser.ReadCertificate(cert.RawData);

            var id = new Org.BouncyCastle.Ocsp.CertificateID(
                Org.BouncyCastle.Ocsp.CertificateID.HashSha1,
                issuer,
                cert2Validate.SerialNumber);

            byte[] reqEnc = GenerateOCSPRequest(id, cert2Validate);
            byte[] resp   = GetOCSPResponse(aia.Ocsp, reqEnc);

            //Extract the response
            OcspResp ocspResponse = new OcspResp(resp);

            BasicOcspResp basicOCSPResponse =
                (BasicOcspResp)ocspResponse.GetResponseObject();

            SingleResp singResp = basicOCSPResponse.Responses[0];

            //Validate ID
            var expectedId = singResp.GetCertID();

            if (!expectedId.SerialNumber.Equals(id.SerialNumber))
            {
                return(CertStatus.Unknown(CertStatus.BadSerial));
            }

            if (!Org.BouncyCastle.Utilities.Arrays.AreEqual(expectedId.GetIssuerNameHash(), id.GetIssuerNameHash()))
            {
                return(CertStatus.Unknown(CertStatus.IssuerNotMatch));
            }

            //Extract Status
            var certificateStatus = singResp.GetCertStatus();

            if (certificateStatus == null)
            {
                return(CertStatus.Good);
            }

            if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus)
            {
                int revocationReason = ((Org.BouncyCastle.Ocsp.RevokedStatus)certificateStatus).RevocationReason;
                var revocationDate   = ((Org.BouncyCastle.Ocsp.RevokedStatus)certificateStatus).RevocationTime;
                return(CertStatus.Revoked(revocationDate.ToString("o"), revocationReason));
            }

            if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus)
            {
                return(CertStatus.Unknown());
            }

            return(CertStatus.Unknown());
        }