Ejemplo n.º 1
0
 /**
  * Gets an encoded byte array with OCSP validation. The method should not throw an exception.
  * @param checkCert to certificate to check
  * @param rootCert the parent certificate
  * @param the url to get the verification. It it's null it will be taken
  * from the check cert or from other implementation specific source
  * @return  a byte array with the validation or null if the validation could not be obtained
  */
 public virtual byte[] GetEncoded(X509Certificate checkCert, X509Certificate rootCert, String url)
 {
     try {
         BasicOcspResp basicResponse = GetBasicOCSPResp(checkCert, rootCert, url);
         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"));
                 }
             }
         }
     }
     catch (Exception ex) {
         if (LOGGER.IsLogging(Level.ERROR))
         {
             LOGGER.Error(ex.Message);
         }
     }
     return(null);
 }
Ejemplo n.º 2
0
        public virtual byte[] MakeOcspResponse(byte[] requestBytes)
        {
            OcspReq ocspRequest = new OcspReq(requestBytes);

            Req[] requestList = ocspRequest.GetRequestList();

            X509Extension extNonce = ocspRequest.RequestExtensions.GetExtension(OcspObjectIdentifiers.PkixOcspNonce);

            if (extNonce != null)
            {
                // TODO ensure
                X509Extensions responseExtensions = new X509Extensions(new Dictionary <DerObjectIdentifier, X509Extension>()
                {
                    { OcspObjectIdentifiers.PkixOcspNonce, extNonce }
                });
                responseBuilder.SetResponseExtensions(responseExtensions);
            }

            foreach (Req req in requestList)
            {
                responseBuilder.AddResponse(req.GetCertID(), certificateStatus, thisUpdate.ToUniversalTime(), nextUpdate.ToUniversalTime(), null);
            }
            DateTime      time         = DateTimeUtil.GetCurrentUtcTime();
            BasicOcspResp ocspResponse = responseBuilder.Generate(new Asn1SignatureFactory(SIGN_ALG, (AsymmetricKeyParameter)issuerPrivateKey), new X509Certificate[] { issuerCert }, time);

            // return new OCSPRespBuilder().build(ocspResult, ocspResponse).getEncoded();
            return(ocspResponse.GetEncoded());
        }
Ejemplo n.º 3
0
 /// <param name="ocspResp"></param>
 /// <returns></returns>
 public virtual bool Match(BasicOcspResp ocspResp)
 {
     try
     {
         IDigest digest = DigestUtilities.GetDigest(algorithm);
         byte[]  oscpBytes;
         if (matchOnlyBasicOCSPResponse)
         {
             oscpBytes = ocspResp.GetEncoded();
         }
         else
         {
             oscpBytes = OCSPUtils.FromBasicToResp(ocspResp).GetEncoded();
         }
         digest.BlockUpdate(oscpBytes, 0, oscpBytes.Length);
         byte[] computedValue = DigestUtilities.DoFinal(digest);
         LOG.Info("Compare " + Hex.ToHexString(digestValue) + " to computed value " +
                  Hex.ToHexString(computedValue) + " of BasicOcspResp produced at " + ocspResp
                  .ProducedAt);
         return(Arrays.Equals(digestValue, computedValue));
     }
     catch (NoSuchAlgorithmException ex)
     {
         throw new RuntimeException("Maybe BouncyCastle provider is not installed ?", ex);
     }
     catch (IOException ex)
     {
         throw new RuntimeException(ex);
     }
 }
Ejemplo n.º 4
0
 /// <summary>Gets an encoded byte array with OCSP validation.</summary>
 /// <remarks>Gets an encoded byte array with OCSP validation. The method should not throw an exception.</remarks>
 /// <param name="checkCert">to certificate to check</param>
 /// <param name="rootCert">the parent certificate</param>
 /// <param name="url">
 /// to get the verification. It it's null it will be taken
 /// from the check cert or from other implementation specific source
 /// </param>
 /// <returns>a byte array with the validation or null if the validation could not be obtained</returns>
 public virtual byte[] GetEncoded(X509Certificate checkCert, X509Certificate rootCert, String url)
 {
     try {
         BasicOcspResp basicResponse = GetBasicOCSPResp(checkCert, rootCert, url);
         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 System.IO.IOException(iText.IO.LogMessageConstant.OCSP_STATUS_IS_REVOKED);
                     }
                     else
                     {
                         throw new System.IO.IOException(iText.IO.LogMessageConstant.OCSP_STATUS_IS_UNKNOWN);
                     }
                 }
             }
         }
     }
     catch (Exception ex) {
         LOGGER.Error(ex.Message);
     }
     return(null);
 }
Ejemplo n.º 5
0
        static void CheckValidityOfResponse(CertID id, BasicOcspResp responseObject, Ca ca)
        {
            var inputStream  = new MemoryStream(responseObject.GetEncoded());
            var asn1Sequence = (Asn1Sequence) new Asn1InputStream(inputStream).ReadObject();

            var response = BasicOcspResponse.GetInstance(asn1Sequence);

            var ocspChain = CreateOcspCertificateChain(ca);

            if (ocspChain.Length == 0)
            {
                throw new OcspException("OCSP certificate chain is invalid");
            }
            var ocesOcspCertificate = OcesCertificateFactory.Instance.Generate(CompleteOcspChain(response, ocspChain));

            CheckBasicOcspResp(id, responseObject, ocesOcspCertificate, ca);

            var signingCertificate = new X509CertificateParser().ReadCertificate(response.Certs[0].GetEncoded());
            var issuingCertificate = new X509CertificateParser().ReadCertificate(ocspChain[0].GetRawCertData());

            signingCertificate.Verify(issuingCertificate.GetPublicKey());
            if (!responseObject.Verify(signingCertificate.GetPublicKey()))
            {
                throw new OcspException("Signature is invalid");
            }
        }
Ejemplo n.º 6
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);
        }
        /// <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);
        }
Ejemplo n.º 8
0
 /// <summary>Convert a BasicOcspResp in OcspResp (connection status is set to SUCCESSFUL).
 ///     </summary>
 /// <remarks>Convert a BasicOcspResp in OcspResp (connection status is set to SUCCESSFUL).
 ///     </remarks>
 /// <param name="basicOCSPResp"></param>
 /// <returns></returns>
 public static OcspResp FromBasicToResp(BasicOcspResp basicOCSPResp)
 {
     try
     {
         return(FromBasicToResp(basicOCSPResp.GetEncoded()));
     }
     catch (IOException e)
     {
         throw new RuntimeException(e);
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Create a reference on a OcspResp
        /// </summary>
        private static OcspResponsesID MakeOcspResponsesID(BasicOcspResp ocspResp)
        {
            byte[] digestValue = DigestUtilities.CalculateDigest
                                     (X509ObjectIdentifiers.IdSha1, ocspResp.GetEncoded());
            OtherHash       hash       = new OtherHash(digestValue);
            OcspResponsesID ocsprespid = new OcspResponsesID(new OcspIdentifier(ocspResp.ResponderId
                                                                                .ToAsn1Object(), ocspResp.ProducedAt), hash);

            logger.Info("Incorporate OcspResponseId[hash=" + Hex.ToHexString(digestValue) +
                        ",producedAt=" + ocspResp.ProducedAt);
            return(ocsprespid);
        }
Ejemplo n.º 10
0
        public virtual bool Match(BasicOcspResp ocspResp)
        {
            IDigest digest = DigestUtilities.GetDigest(algorithm);

            byte[] oscpBytes;
            if (matchOnlyBasicOCSPResponse)
            {
                oscpBytes = ocspResp.GetEncoded();
            }
            else
            {
                oscpBytes = OCSPUtils.FromBasicToResp(ocspResp).GetEncoded();
            }
            digest.BlockUpdate(oscpBytes, 0, oscpBytes.Length);
            byte[] computedValue = DigestUtilities.DoFinal(digest);
            logger.Info("Compare " + Hex.ToHexString(digestValue) + " to computed value " +
                        Hex.ToHexString(computedValue) + " of BasicOcspResp produced at " + ocspResp
                        .ProducedAt);
            return(digestValue.SequenceEqual(computedValue));
        }
Ejemplo n.º 11
0
            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));
            }
Ejemplo n.º 12
0
 public OcspResp Generate(int status, object response)
 {
     if (response == null)
     {
         return(new OcspResp(new OcspResponse(new OcspResponseStatus(status), null)));
     }
     if (response is BasicOcspResp)
     {
         BasicOcspResp   basicOcspResp = (BasicOcspResp)response;
         Asn1OctetString response2;
         try
         {
             response2 = new DerOctetString(basicOcspResp.GetEncoded());
         }
         catch (Exception e)
         {
             throw new OcspException("can't encode object.", e);
         }
         ResponseBytes responseBytes = new ResponseBytes(OcspObjectIdentifiers.PkixOcspBasic, response2);
         return(new OcspResp(new OcspResponse(new OcspResponseStatus(status), responseBytes)));
     }
     throw new OcspException("unknown response object");
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Convert a BasicOcspResp in OcspResp (connection status is set to SUCCESSFUL).
 /// </summary>
 public static OcspResp FromBasicToResp(BasicOcspResp basicOCSPResp)
 {
     return(FromBasicToResp(basicOCSPResp.GetEncoded()));
 }