org.bouncycastle.cert.ocsp.OCSPException Java Examples

The following examples show how to use org.bouncycastle.cert.ocsp.OCSPException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OcspRequestBuilder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce
 * and CA's will (should) reject subsequent requests that have the same nonce value.
 */
public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
    SecureRandom generator = checkNotNull(this.generator, "generator");
    DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
    X509Certificate certificate = checkNotNull(this.certificate, "certificate");
    X509Certificate issuer = checkNotNull(this.issuer, "issuer");

    BigInteger serial = certificate.getSerialNumber();

    CertificateID certId = new CertificateID(calculator,
            new X509CertificateHolder(issuer.getEncoded()), serial);

    OCSPReqBuilder builder = new OCSPReqBuilder();
    builder.addRequest(certId);

    byte[] nonce = new byte[8];
    generator.nextBytes(nonce);

    Extension[] extensions = new Extension[] {
            new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                    new DEROctetString(nonce)) };

    builder.setRequestExtensions(new Extensions(extensions));

    return builder.build();
}
 
Example #2
Source File: PAdESOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectOCSPArchivalValues(AttributeTable attributes) {
	final ASN1Encodable attValue = DSSASN1Utils.getAsn1Encodable(attributes, OID.adbe_revocationInfoArchival);
	if (attValue !=null) {	
		RevocationInfoArchival revocationArchival = PAdESUtils.getRevocationInfoArchivals(attValue);
		if (revocationArchival != null) {
			for (final OCSPResponse ocspResponse : revocationArchival.getOcspVals()) {
				final OCSPResp ocspResp = new OCSPResp(ocspResponse);
				try {
					BasicOCSPResp basicOCSPResponse = (BasicOCSPResp) ocspResp.getResponseObject();
					addBinary(OCSPResponseBinary.build(basicOCSPResponse), RevocationOrigin.ADBE_REVOCATION_INFO_ARCHIVAL);
				} catch (OCSPException e) {
					LOG.warn("Error while extracting OCSPResponse from Revocation Info Archivals (ADBE) : {}", e.getMessage());
				}					
			}
		}
	}
}
 
Example #3
Source File: OcspClientBouncyCastle.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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) throws OCSPException, IOException, OperatorException, CertificateEncodingException {
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    
    JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
    DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
    DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(digestCalculator, new JcaX509CertificateHolder(issuerCert), serialNumber);
    
    // basic request generation with nonce
    OCSPReqBuilder gen = new OCSPReqBuilder();
    
    gen.addRequest(id);
    
    // create details for nonce extension
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()));
    gen.setRequestExtensions(new Extensions(new Extension[]{ext}));
    
    return gen.build();
}
 
Example #4
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a OCSP Request
 *
 * @param pairIssuerSubject a pair of issuer and subject certificates
 * @return OCSPReq object
 */
private OCSPReq createRequest(
    SFPair<Certificate, Certificate> pairIssuerSubject) throws IOException
{
  Certificate issuer = pairIssuerSubject.left;
  Certificate subject = pairIssuerSubject.right;
  OCSPReqBuilder gen = new OCSPReqBuilder();
  try
  {
    DigestCalculator digest = new SHA1DigestCalculator();
    X509CertificateHolder certHolder = new X509CertificateHolder(issuer.getEncoded());
    CertificateID certId = new CertificateID(
        digest, certHolder, subject.getSerialNumber().getValue());
    gen.addRequest(certId);
    return gen.build();
  }
  catch (OCSPException ex)
  {
    throw new IOException("Failed to build a OCSPReq.", ex);
  }
}
 
Example #5
Source File: OnlineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private byte[] buildOCSPRequest(final CertificateID certId, BigInteger nonce) throws DSSException {
	try {
		final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
		ocspReqBuilder.addRequest(certId);
		/*
		 * The nonce extension is used to bind a request to a response to
		 * prevent replay attacks. RFC 6960 (OCSP) section 4.1.2 such
		 * extensions SHOULD NOT be flagged as critical
		 */
		if (nonce != null) {
			DEROctetString encodedNonceValue = new DEROctetString(
					new DEROctetString(nonce.toByteArray()).getEncoded());
			Extension extension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, encodedNonceValue);
			Extensions extensions = new Extensions(extension);
			ocspReqBuilder.setRequestExtensions(extensions);
		}
		final OCSPReq ocspReq = ocspReqBuilder.build();
		final byte[] ocspReqData = ocspReq.getEncoded();
		return ocspReqData;
	} catch (OCSPException | IOException e) {
		throw new DSSException("Cannot build OCSP Request", e);
	}
}
 
Example #6
Source File: OnlineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private BigInteger getEmbeddedNonceValue(final OCSPResp ocspResp) {
	try {
		BasicOCSPResp basicOCSPResp = (BasicOCSPResp)ocspResp.getResponseObject();
		
		Extension extension = basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
		ASN1OctetString extnValue = extension.getExtnValue();
		ASN1Primitive value;
		try {
			value = ASN1Primitive.fromByteArray(extnValue.getOctets());
		} catch (IOException ex) {
			throw new OCSPException("Invalid encoding of nonce extension value in OCSP response", ex);
		}
		if (value instanceof DEROctetString) {
			return new BigInteger(((DEROctetString) value).getOctets());
		}
		throw new OCSPException("Nonce extension value in OCSP response is not an OCTET STRING");
	} catch (Exception e) {
		throw new DSSException(String.format("Unable to extract the nonce from the OCSPResponse! Reason : [%s]", e.getMessage()), e);
	}
}
 
Example #7
Source File: JdbcCacheOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected OCSPToken buildRevocationTokenFromResult(ResultSet rs, CertificateToken certificateToken, CertificateToken issuerCert) {
	try {
		final byte[] data = rs.getBytes(SQL_FIND_QUERY_DATA);
		final String url = rs.getString(SQL_FIND_QUERY_LOC);
		
		final OCSPResp ocspResp = new OCSPResp(data);
		BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResp.getResponseObject();
		SingleResp latestSingleResponse = DSSRevocationUtils.getLatestSingleResponse(basicResponse, certificateToken, issuerCert);
		OCSPToken ocspToken = new OCSPToken(basicResponse, latestSingleResponse, certificateToken, issuerCert);
		ocspToken.setSourceURL(url);
		ocspToken.setExternalOrigin(RevocationOrigin.CACHED);
		return ocspToken;
	} catch (SQLException | IOException | OCSPException e) {
		throw new RevocationException("An error occurred during an attempt to obtain a revocation token");
	}
}
 
Example #8
Source File: XiOCSPReqBuilder.java    From xipki with Apache License 2.0 5 votes vote down vote up
public OCSPRequest build(ContentSigner signer, Certificate[] chain) throws OCSPException {
  if (signer == null) {
    throw new IllegalArgumentException("no signer specified");
  }

  return generateRequest(signer, chain);
}
 
Example #9
Source File: OCSPCertificateVerifier.java    From oxAuth with MIT License 5 votes vote down vote up
private OCSPReq generateOCSPRequest(CertificateID certificateId) throws OCSPException, OperatorCreationException, CertificateEncodingException {
	OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();

	ocspReqGenerator.addRequest(certificateId);

	OCSPReq ocspReq = ocspReqGenerator.build();
	return ocspReq;
}
 
Example #10
Source File: OCSPFuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ETriState evalOCSPResponse (@Nonnull final OCSPResp aOCSPResponse) throws OCSPException
{
  final EOCSPResponseStatus eStatus = EOCSPResponseStatus.getFromValueOrNull (aOCSPResponse.getStatus ());
  if (eStatus == null)
    throw new OCSPException ("Unsupported status code " + aOCSPResponse.getStatus () + " received!");
  if (eStatus.isFailure ())
    throw new OCSPException ("Non-success status code " + aOCSPResponse.getStatus () + " received!");

  final Object aResponseObject = aOCSPResponse.getResponseObject ();
  if (aResponseObject instanceof BasicOCSPResp)
  {
    final BasicOCSPResp aBasicResponse = (BasicOCSPResp) aResponseObject;
    final SingleResp [] aResponses = aBasicResponse.getResponses ();
    // Assume we queried only one
    if (aResponses.length == 1)
    {
      final SingleResp aResponse = aResponses[0];
      final CertificateStatus aStatus = aResponse.getCertStatus ();
      if (aStatus == CertificateStatus.GOOD)
        return ETriState.TRUE;
      if (aStatus instanceof RevokedStatus)
        return ETriState.FALSE;
      // else status is unknown
    }
  }
  return ETriState.UNDEFINED;
}
 
Example #11
Source File: OCSPFuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static OCSPReq generateOCSPRequest (final X509Certificate aIssuerCert,
                                           final BigInteger aCheckSerialNumber) throws OCSPException
{
  try
  {
    final DigestCalculatorProvider aDigestCalculatorProvider = new JcaDigestCalculatorProviderBuilder ().setProvider (PBCProvider.getProvider ())
                                                                                                        .build ();
    final DigestCalculator aDigestCalculator = aDigestCalculatorProvider.get (CertificateID.HASH_SHA1);

    // CertID structure is used to uniquely identify certificates that are the
    // subject of an OCSP request or response and has an ASN.1 definition.
    // CertID structure is defined in RFC 2560
    final CertificateID aCertificateID = new JcaCertificateID (aDigestCalculator, aIssuerCert, aCheckSerialNumber);

    // create details for nonce extension. The nonce extension is used to bind
    // a request to a response to prevent replay attacks. As the name implies,
    // the nonce value is something that the client should only use once
    // within a reasonably small period.
    final BigInteger aNonce = BigInteger.valueOf (System.nanoTime ());

    // to create the request Extension
    final Extensions aExtensions = new Extensions (new Extension (OCSPObjectIdentifiers.id_pkix_ocsp_nonce,
                                                                  false,
                                                                  new DEROctetString (aNonce.toByteArray ())));

    // basic request generation with nonce
    final OCSPReqBuilder aBuilder = new OCSPReqBuilder ();
    aBuilder.addRequest (aCertificateID);
    // Extension to the whole request
    aBuilder.setRequestExtensions (aExtensions);
    return aBuilder.build ();
  }
  catch (final OperatorCreationException | CertificateEncodingException ex)
  {
    throw new IllegalStateException (ex);
  }
}
 
Example #12
Source File: XadesCSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private byte[] convertToOCSPResp(OCSPData data) throws IOException, OCSPException {
   BasicOCSPResp basicResp = new BasicOCSPResp(BasicOCSPResponse.getInstance(ASN1Primitive.fromByteArray(data.getOcspResponse())));
   return (new OCSPRespBuilder()).build(0, basicResp).getEncoded();
}
 
Example #13
Source File: XadesCSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private byte[] convertToOCSPResp(OCSPData data) throws IOException, OCSPException {
   BasicOCSPResp basicResp = new BasicOCSPResp(BasicOCSPResponse.getInstance(ASN1Primitive.fromByteArray(data.getOcspResponse())));
   return (new OCSPRespBuilder()).build(0, basicResp).getEncoded();
}
 
Example #14
Source File: XadesCSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private byte[] convertToOCSPResp(OCSPData data) throws IOException, OCSPException {
   BasicOCSPResp basicResp = new BasicOCSPResp(BasicOCSPResponse.getInstance(ASN1Primitive.fromByteArray(data.getOcspResponse())));
   return (new OCSPRespBuilder()).build(0, basicResp).getEncoded();
}
 
Example #15
Source File: XadesCSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private byte[] convertToOCSPResp(OCSPData data) throws IOException, OCSPException {
   BasicOCSPResp basicResp = new BasicOCSPResp(BasicOCSPResponse.getInstance(ASN1Primitive.fromByteArray(data.getOcspResponse())));
   return (new OCSPRespBuilder()).build(0, basicResp).getEncoded();
}
 
Example #16
Source File: OCSPRespBuilder.java    From xipki with Apache License 2.0 4 votes vote down vote up
public byte[] buildOCSPResponse(ConcurrentContentSigner signer,
    TaggedCertSequence taggedCertSequence, Date producedAt)
    throws OCSPException, NoIdleSignerException {
  ResponseData responseData = new ResponseData(0,
      responderId, producedAt, list, responseExtensions);

  byte[] tbs = new byte[responseData.getEncodedLength()];
  responseData.write(tbs, 0);

  ConcurrentBagEntrySigner signer0 = signer.borrowSigner();

  byte[] signature;
  byte[] sigAlgId;

  try {
    XiContentSigner csigner0 = signer0.value();
    OutputStream sigOut = csigner0.getOutputStream();
    try {
      sigOut.write(tbs);
      sigOut.close();
    } catch (IOException ex) {
      throw new OCSPException("exception signing TBSRequest: " + ex.getMessage(), ex);
    }

    signature = csigner0.getSignature();
    sigAlgId = csigner0.getEncodedAlgorithmIdentifier();
  } finally {
    signer.requiteSigner(signer0);
  }

  // ----- Get the length -----
  // BasicOCSPResponse.signature
  int signatureBodyLen = signature.length + 1;
  int signatureLen = getLen(signatureBodyLen);

  // BasicOCSPResponse
  int basicResponseBodyLen = tbs.length + sigAlgId.length + signatureLen;
  if (taggedCertSequence != null) {
    basicResponseBodyLen += taggedCertSequence.getEncodedLength();
  }
  int basicResponseLen = getLen(basicResponseBodyLen);

  // OCSPResponse.[0].responseBytes
  int responseBytesBodyLen = responseTypeBasic.length
      + getLen(basicResponseLen); // Header of OCTET STRING
  int responseBytesLen = getLen(responseBytesBodyLen);

  // OCSPResponse.[0]
  int taggedResponseBytesLen = getLen(responseBytesLen);

  // OCSPResponse
  int ocspResponseBodyLen = successfulStatus.length + taggedResponseBytesLen;
  int ocspResponseLen = getLen(ocspResponseBodyLen);

  // encode
  byte[] out = new byte[ocspResponseLen];
  int offset = 0;
  offset += ASN1Type.writeHeader((byte) 0x30, ocspResponseBodyLen, out, offset);
  // OCSPResponse.responseStatus
  offset += arraycopy(successfulStatus, out, offset);

  // OCSPResponse.[0]
  offset += ASN1Type.writeHeader((byte) 0xA0, responseBytesLen, out, offset);

  // OCSPResponse.[0]responseBytes
  offset += ASN1Type.writeHeader((byte) 0x30, responseBytesBodyLen, out, offset);

  // OCSPResponse.[0]responseBytes.responseType
  offset += arraycopy(responseTypeBasic, out, offset);

  // OCSPResponse.[0]responseBytes.responseType
  offset += ASN1Type.writeHeader((byte) 0x04, basicResponseLen, out, offset); // OCET STRING

  // BasicOCSPResponse
  offset += ASN1Type.writeHeader((byte) 0x30, basicResponseBodyLen, out, offset);
  // BasicOCSPResponse.tbsResponseData
  offset += arraycopy(tbs, out, offset);

  // BasicOCSPResponse.signatureAlgorithm
  offset += arraycopy(sigAlgId, out, offset);

  // BasicOCSPResponse.signature
  offset += ASN1Type.writeHeader((byte) 0x03, signatureBodyLen, out, offset);
  out[offset++] = 0x00; // skipping bits
  offset += arraycopy(signature, out, offset);

  if (taggedCertSequence != null) {
    offset += taggedCertSequence.write(out, offset);
  }
  return out;
}
 
Example #17
Source File: XadesCSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private byte[] convertToOCSPResp(OCSPData data) throws IOException, OCSPException {
   BasicOCSPResp basicResp = new BasicOCSPResp(BasicOCSPResponse.getInstance(ASN1Primitive.fromByteArray(data.getOcspResponse())));
   return (new OCSPRespBuilder()).build(0, basicResp).getEncoded();
}
 
Example #18
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Returns the {@code CertificateID} for the given certificate and its
 * issuer's certificate.
 *
 * @param cert
 *            {@code CertificateToken} for which the id is created
 * @param issuerCert
 *            {@code CertificateToken} issuer certificate of the {@code cert}
 * @param digestAlgorithm
 *            {@code DigestAlgorithm} to be used for CertificateID hash calculation
 * @return {@code CertificateID}
 */
public static CertificateID getOCSPCertificateID(final CertificateToken cert, final CertificateToken issuerCert, 
		final DigestAlgorithm digestAlgorithm) {
	try {
		final BigInteger serialNumber = cert.getSerialNumber();
		final DigestCalculator digestCalculator = getDigestCalculator(digestAlgorithm);
		final X509CertificateHolder x509CertificateHolder = DSSASN1Utils.getX509CertificateHolder(issuerCert);
		return new CertificateID(digestCalculator, x509CertificateHolder, serialNumber);
	} catch (OCSPException e) {
		throw new DSSException("Unable to create CertificateID", e);
	}
}
 
Example #19
Source File: XiOCSPReqBuilder.java    From xipki with Apache License 2.0 2 votes vote down vote up
/**
 * Generate an unsigned request.
 *
 * @return the OCSPRequest
 * @throws OCSPException
 *           If OCSP request cannot be built.
 */
public OCSPRequest build() throws OCSPException {
  return generateRequest(null, null);
}