org.bouncycastle.cert.ocsp.CertificateID Java Examples

The following examples show how to use org.bouncycastle.cert.ocsp.CertificateID. 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: 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 #3
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks if OCSP revocation refers to the document signing certificate.
 * @return true if it checks false otherwise
 * @since	2.1.6
 */
public boolean isRevocationValid() {
    if (basicResp == null)
        return false;
    if (signCerts.size() < 2)
        return false;
    try {
        X509Certificate[] cs = (X509Certificate[])getSignCertificateChain();
        SingleResp sr = basicResp.getResponses()[0];
        CertificateID cid = sr.getCertID();
        X509Certificate sigcer = getSigningCertificate();
        X509Certificate isscer = cs[1];
        CertificateID tis = new CertificateID(
           new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(isscer), sigcer.getSerialNumber());
        return tis.equals(cid);
    }
    catch (Exception ex) {
    }
    return false;
}
 
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: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * fix for certId.equals methods that doesn't work very well.
 *
 * @param certId
 *            {@code CertificateID}
 * @param singleResp
 *            {@code SingleResp}
 * @return true if the certificate matches this included in
 *         {@code SingleResp}
 */
public static boolean matches(final CertificateID certId, final SingleResp singleResp) {

	final CertificateID singleRespCertID = singleResp.getCertID();
	final ASN1ObjectIdentifier singleRespCertIDHashAlgOID = singleRespCertID.getHashAlgOID();
	final byte[] singleRespCertIDIssuerKeyHash = singleRespCertID.getIssuerKeyHash();
	final byte[] singleRespCertIDIssuerNameHash = singleRespCertID.getIssuerNameHash();
	final BigInteger singleRespCertIDSerialNumber = singleRespCertID.getSerialNumber();

	final ASN1ObjectIdentifier certIdHashAlgOID = certId.getHashAlgOID();
	final byte[] certIdIssuerKeyHash = certId.getIssuerKeyHash();
	final byte[] certIdIssuerNameHash = certId.getIssuerNameHash();
	final BigInteger certIdSerialNumber = certId.getSerialNumber();

	// certId.equals fails in comparing the algoIdentifier because
	// AlgoIdentifier params in null in one case and DERNull in another case
	return singleRespCertIDHashAlgOID.equals(certIdHashAlgOID) && Arrays.equals(singleRespCertIDIssuerKeyHash, certIdIssuerKeyHash)
			&& Arrays.equals(singleRespCertIDIssuerNameHash, certIdIssuerNameHash) && singleRespCertIDSerialNumber.equals(certIdSerialNumber);
}
 
Example #7
Source File: DSSRevocationUtilsTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testGetOCSPCertificateIDAndMatch() throws IOException {
	CertificateToken certificate = DSSUtils.loadCertificate(new File("src/test/resources/citizen_ca.cer"));
	CertificateToken issuer = DSSUtils.loadCertificate(new File("src/test/resources/belgiumrs2.crt"));
	assertTrue(certificate.isSignedBy(issuer));

	CertificateID certificateID = DSSRevocationUtils.getOCSPCertificateID(certificate, issuer, DigestAlgorithm.SHA256);
	assertNotNull(certificateID);

	BasicOCSPResp basicOCSPResp = DSSRevocationUtils.loadOCSPBase64Encoded(
			"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");

	SingleResp[] responses = basicOCSPResp.getResponses();

	assertFalse(DSSRevocationUtils.matches(certificateID, responses[0]));
}
 
Example #8
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * CertificateID to string
 *
 * @param certificateID CertificateID
 * @return a string representation of CertificateID
 */
private static String CertificateIDToString(CertificateID certificateID)
{
  return String.format("CertID. NameHash: %s, KeyHash: %s, Serial Number: %s",
                       byteToHexString(certificateID.getIssuerNameHash()),
                       byteToHexString(certificateID.getIssuerKeyHash()),
                       MessageFormat.format("{0,number,#}",
                                            certificateID.getSerialNumber()));

}
 
Example #9
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static List<SingleResp> getSingleResponses(BasicOCSPResp basicResponse, CertificateToken certificate, CertificateToken issuer) {
	List<SingleResp> result = new ArrayList<>();
	SingleResp[] responses = getSingleResps(basicResponse);
	for (final SingleResp singleResp : responses) {
		DigestAlgorithm usedDigestAlgorithm = getUsedDigestAlgorithm(singleResp);
		final CertificateID certId = getOCSPCertificateID(certificate, issuer, usedDigestAlgorithm);
		if (DSSRevocationUtils.matches(certId, singleResp)) {
			result.add(singleResp);
		}
	}
	return result;
}
 
Example #10
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 #11
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 #12
Source File: OnlineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public OCSPToken getRevocationToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken,
		List<String> alternativeUrls) {
	Objects.requireNonNull(dataLoader, "DataLoader is not provided !");

	final String dssIdAsString = certificateToken.getDSSIdAsString();
	LOG.trace("--> OnlineOCSPSource queried for {}", dssIdAsString);
	if (Utils.isCollectionNotEmpty(alternativeUrls)) {
		LOG.info("OCSP alternative urls : {}", alternativeUrls);
	}

	final List<String> ocspAccessLocations = DSSASN1Utils.getOCSPAccessLocations(certificateToken);
	if (Utils.isCollectionEmpty(ocspAccessLocations) && Utils.isCollectionEmpty(alternativeUrls)) {
		LOG.warn("No OCSP location found for {}", dssIdAsString);
		return null;
	}
	ocspAccessLocations.addAll(alternativeUrls);

	final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(certificateToken, issuerCertificateToken, certIDDigestAlgorithm);

	BigInteger nonce = null;
	if (nonceSource != null) {
		nonce = nonceSource.getNonce();
	}

	final byte[] content = buildOCSPRequest(certId, nonce);

	int nbTries = ocspAccessLocations.size();
	for (String ocspAccessLocation : ocspAccessLocations) {
		nbTries--;
		try {
			final byte[] ocspRespBytes = dataLoader.post(ocspAccessLocation, content);
			if (!Utils.isArrayEmpty(ocspRespBytes)) {
				final OCSPResp ocspResp = new OCSPResp(ocspRespBytes);
				verifyNonce(ocspResp, nonce);
				OCSPRespStatus status = OCSPRespStatus.fromInt(ocspResp.getStatus());
				if (OCSPRespStatus.SUCCESSFUL.equals(status)) {
					BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResp.getResponseObject();
					SingleResp latestSingleResponse = DSSRevocationUtils.getLatestSingleResponse(basicResponse, certificateToken, issuerCertificateToken);
					OCSPToken ocspToken = new OCSPToken(basicResponse, latestSingleResponse, certificateToken, issuerCertificateToken);
					ocspToken.setSourceURL(ocspAccessLocation);
					ocspToken.setExternalOrigin(RevocationOrigin.EXTERNAL);
					return ocspToken;
				} else {
					LOG.warn("Ignored OCSP Response from URL '{}' : status -> {}", ocspAccessLocation, status);
				}
			} else {
				LOG.warn("OCSP Data Loader for certificate {} responded with an empty byte array!", certificateToken.getDSSIdAsString());
			}
		} catch (Exception e) {
			if (nbTries == 0) {
				throw new DSSException("Unable to retrieve OCSP response", e);
			} else {
				LOG.warn("Unable to retrieve OCSP response with URL '{}' : {}", ocspAccessLocation, e.getMessage());
			}
		}
	}

	return null;
}
 
Example #13
Source File: OCSPCertificateVerifier.java    From oxAuth with MIT License 4 votes vote down vote up
@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {
	X509Certificate issuer = issuers.get(0);
	ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN);

	try {
		Principal subjectX500Principal = certificate.getSubjectX500Principal();

		String ocspUrl = getOCSPUrl(certificate);
		if (ocspUrl == null) {
			log.error("OCSP URL for '" + subjectX500Principal + "' is empty");
			return status;
		}

		log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'");

		DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1);
		CertificateID certificateId = new CertificateID(digestCalculator, new JcaX509CertificateHolder(certificate), certificate.getSerialNumber());

		// Generate OCSP request
		OCSPReq ocspReq = generateOCSPRequest(certificateId);

		// Get OCSP response from server
		OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq);
		if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
			log.error("OCSP response is invalid!");
			status.setValidity(CertificateValidity.INVALID);
			return status;
		}

		boolean foundResponse = false;
		BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
		SingleResp[] singleResps = basicOCSPResp.getResponses();
		for (SingleResp singleResp : singleResps) {
			CertificateID responseCertificateId = singleResp.getCertID();
			if (!certificateId.equals(responseCertificateId)) {
				continue;
			}

			foundResponse = true;

			log.debug("OCSP validationDate: " + validationDate);
			log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
			log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());

			status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt());

			Object certStatus = singleResp.getCertStatus();
			if (certStatus == CertificateStatus.GOOD) {
				log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'");
				status.setValidity(CertificateValidity.VALID);
			} else {
				if (singleResp.getCertStatus() instanceof RevokedStatus) {
					log.warn("OCSP status is revoked for: " + subjectX500Principal);
					if (validationDate.before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
						log.warn("OCSP revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate);
						status.setValidity(CertificateValidity.VALID);
					} else {
						Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime();
						log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since " + revocationDate);
						status.setRevocationDate(revocationDate);
						status.setRevocationObjectIssuingTime(singleResp.getThisUpdate());
						status.setValidity(CertificateValidity.REVOKED);
					}
				}
			}
		}

		if (!foundResponse) {
			log.error("There is no matching OCSP response entries");
		}
	} catch (Exception ex) {
		log.error("OCSP exception: ", ex);
	}

	return status;
}
 
Example #14
Source File: OcspHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    final byte[] buffy = new byte[16384];
    try (InputStream requestStream = exchange.getInputStream()) {
        requestStream.read(buffy);
    }

    final OCSPReq request = new OCSPReq(buffy);
    final Req[] requested = request.getRequestList();

    final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);

    final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build()
            .get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1));

    final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator);

    if (nonce != null) {
        responseBuilder.setResponseExtensions(new Extensions(nonce));
    }

    for (final Req req : requested) {
        final CertificateID certId = req.getCertID();

        final BigInteger certificateSerialNumber = certId.getSerialNumber();
        responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber));
    }

    final ContentSigner contentSigner = new BcRSAContentSignerBuilder(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption),
            new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey);

    final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL,
            responseBuilder.build(contentSigner, chain, new Date()));

    final byte[] responseBytes = response.getEncoded();

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response");

    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));

    exchange.endExchange();
}
 
Example #15
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);
	}
}