use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project poi by apache.
the class PkiTestUtils method createOcspResp.
public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
// request
//create a nonce to avoid replay attack
BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
Extensions exts = new Extensions(ext);
OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
ocspReqBuilder.addRequest(certId);
ocspReqBuilder.setRequestExtensions(exts);
OCSPReq ocspReq = ocspReqBuilder.build();
SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
basicOCSPRespBuilder.setResponseExtensions(exts);
// request processing
Req[] requestList = ocspReq.getRequestList();
for (Req ocspRequest : requestList) {
CertificateID certificateID = ocspRequest.getCertID();
CertificateStatus certificateStatus = CertificateStatus.GOOD;
if (revoked) {
certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
}
basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
}
// basic response generation
X509CertificateHolder[] chain = null;
if (!ocspResponderCertificate.equals(issuerCertificate)) {
// TODO: HorribleProxy can't convert array input params yet
chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
}
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
return ocspResp;
}
use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project Openfire by igniterealtime.
the class OCSPChecker method check.
@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {
Log.debug("OCSPChecker: check called");
InputStream in = null;
OutputStream out = null;
try {
// Examine OCSP properties
X509Certificate responderCert = null;
// defaults to issuers cert
boolean haveResponderCert = true;
X500Principal responderSubjectName = null;
boolean haveIssuerCert = false;
// If we set the subject name, we need to find the certificate
if (ocspServerSubject != null) {
haveResponderCert = false;
responderSubjectName = new X500Principal(ocspServerSubject);
}
X509Certificate issuerCert = null;
X509Certificate currCert = (X509Certificate) cert;
// Set the issuer certificate if we were passed a chain
if (certIndex != 0) {
issuerCert = certs[certIndex];
haveIssuerCert = true;
if (haveResponderCert) {
responderCert = certs[certIndex];
}
}
if (!haveIssuerCert || !haveResponderCert) {
if (!haveResponderCert) {
Log.debug("OCSPChecker: Looking for responder's certificate");
}
if (!haveIssuerCert) {
Log.debug("OCSPChecker: Looking for issuer's certificate");
}
// Extract the anchor certs
Iterator anchors = pkixParams.getTrustAnchors().iterator();
if (!anchors.hasNext()) {
throw new CertPathValidatorException("Must specify at least one trust anchor");
}
X500Principal certIssuerName = currCert.getIssuerX500Principal();
while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) {
TrustAnchor anchor = (TrustAnchor) anchors.next();
X509Certificate anchorCert = anchor.getTrustedCert();
X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal();
// Check if this anchor cert is the issuer cert
if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) {
issuerCert = anchorCert;
haveIssuerCert = true;
// If we have not set the responderCert at this point, set it to the issuer
if (haveResponderCert && responderCert == null) {
responderCert = anchorCert;
Log.debug("OCSPChecker: Responder's certificate = issuer certificate");
}
}
// Check if this anchor cert is the responder cert
if (!haveResponderCert) {
if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) {
responderCert = anchorCert;
haveResponderCert = true;
}
}
}
if (issuerCert == null) {
// No trust anchor was found matching the issuer
throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN());
}
// Check cert stores if responder cert has not yet been found
if (!haveResponderCert) {
Log.debug("OCSPChecker: Searching cert stores for responder's certificate");
if (responderSubjectName != null) {
X509CertSelector filter = new X509CertSelector();
filter.setSubject(responderSubjectName.getName());
List<CertStore> certStores = pkixParams.getCertStores();
for (CertStore certStore : certStores) {
Iterator i = certStore.getCertificates(filter).iterator();
if (i.hasNext()) {
responderCert = (X509Certificate) i.next();
haveResponderCert = true;
break;
}
}
}
}
}
// Could not find the responder cert
if (!haveResponderCert) {
throw new CertPathValidatorException("Cannot find the responder's certificate.");
}
// Construct an OCSP Request
OCSPReqBuilder gen = new OCSPReqBuilder();
CertificateID certID = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber());
gen.addRequest(certID);
OCSPReq ocspRequest = gen.build();
URL url;
if (ocspServerUrl != null) {
try {
url = new URL(ocspServerUrl);
} catch (MalformedURLException e) {
throw new CertPathValidatorException(e);
}
} else {
throw new CertPathValidatorException("Must set OCSP Server URL");
}
HttpURLConnection con = (HttpURLConnection) url.openConnection();
Log.debug("OCSPChecker: connecting to OCSP service at: " + url);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "application/ocsp-request");
con.setRequestProperty("Accept", "application/ocsp-response");
byte[] bytes = ocspRequest.getEncoded();
con.setRequestProperty("Content-length", String.valueOf(bytes.length));
out = con.getOutputStream();
out.write(bytes);
out.flush();
// Check the response
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
}
in = con.getInputStream();
OCSPResp ocspResponse = new OCSPResp(in);
BigInteger serialNumber = currCert.getSerialNumber();
BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();
try {
if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(responderCert.getPublicKey()))) {
throw new CertPathValidatorException("OCSP response is not verified");
}
} catch (Exception e) {
throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex);
}
SingleResp[] singleResp = brep.getResponses();
boolean foundResponse = false;
for (SingleResp resp : singleResp) {
CertificateID respCertID = resp.getCertID();
if (respCertID.equals(certID)) {
Object status = resp.getCertStatus();
if (status == CertificateStatus.GOOD) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good");
foundResponse = true;
break;
} else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked");
throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex);
} else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown");
throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex);
} else {
Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized");
throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex);
}
}
}
// Check that response applies to the cert that was supplied
if (!foundResponse) {
throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request.");
}
} catch (CertPathValidatorException cpve) {
throw cpve;
} catch (Exception e) {
throw new CertPathValidatorException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
throw new CertPathValidatorException(ioe);
}
}
if (out != null) {
try {
out.close();
} catch (IOException ioe) {
throw new CertPathValidatorException(ioe);
}
}
}
}
use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project oxAuth by GluuFederation.
the class OCSPCertificateVerifier method generateOCSPRequest.
private OCSPReq generateOCSPRequest(CertificateID certificateId) throws OCSPException, OperatorCreationException, CertificateEncodingException {
OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();
ocspReqGenerator.addRequest(certificateId);
OCSPReq ocspReq = ocspReqGenerator.build();
return ocspReq;
}
use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project nifi by apache.
the class OcspCertificateValidator method getOcspStatus.
/**
* Gets the OCSP status for the specified subject and issuer certificates.
*
* @param ocspStatusKey status key
* @return ocsp status
*/
private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) {
final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate();
final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate();
// initialize the default status
final OcspStatus ocspStatus = new OcspStatus();
ocspStatus.setVerificationStatus(VerificationStatus.Unknown);
ocspStatus.setValidationStatus(ValidationStatus.Unknown);
try {
// prepare the request
final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber();
final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
final CertificateID certificateId = new CertificateID(calculatorProviderBuilder.get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber);
// generate the request
final OCSPReqBuilder requestGenerator = new OCSPReqBuilder();
requestGenerator.addRequest(certificateId);
// Create a nonce to avoid replay attack
BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, new DEROctetString(nonce.toByteArray()));
requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext }));
final OCSPReq ocspRequest = requestGenerator.build();
// perform the request
final Response response = getClientResponse(ocspRequest);
// ensure the request was completed successfully
if (Response.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus()));
return ocspStatus;
}
// interpret the response
OCSPResp ocspResponse = new OCSPResp(response.readEntity(InputStream.class));
// verify the response status
switch(ocspResponse.getStatus()) {
case OCSPRespBuilder.SUCCESSFUL:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful);
break;
case OCSPRespBuilder.INTERNAL_ERROR:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError);
break;
case OCSPRespBuilder.MALFORMED_REQUEST:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest);
break;
case OCSPRespBuilder.SIG_REQUIRED:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired);
break;
case OCSPRespBuilder.TRY_LATER:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater);
break;
case OCSPRespBuilder.UNAUTHORIZED:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized);
break;
default:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown);
break;
}
// only proceed if the response was successful
if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
logger.warn(String.format("OCSP request was unsuccessful (%s).", ocspStatus.getResponseStatus().toString()));
return ocspStatus;
}
// ensure the appropriate response object
final Object ocspResponseObject = ocspResponse.getResponseObject();
if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) {
logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject));
return ocspStatus;
}
// get the response object
final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
// attempt to locate the responder certificate
final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts();
if (responderCertificates.length != 1) {
logger.warn(String.format("Unexpected number of OCSP responder certificates: %s", responderCertificates.length));
return ocspStatus;
}
// get the responder certificate
final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate(responderCertificates[0], issuerCertificate);
if (trustedResponderCertificate != null) {
// verify the response
if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(trustedResponderCertificate.getPublicKey()))) {
ocspStatus.setVerificationStatus(VerificationStatus.Verified);
} else {
ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
}
} else {
ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
}
// validate the response
final SingleResp[] responses = basicOcspResponse.getResponses();
for (SingleResp singleResponse : responses) {
final CertificateID responseCertificateId = singleResponse.getCertID();
final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber();
if (responseSerialNumber.equals(subjectSerialNumber)) {
Object certStatus = singleResponse.getCertStatus();
// interpret the certificate status
if (CertificateStatus.GOOD == certStatus) {
ocspStatus.setValidationStatus(ValidationStatus.Good);
} else if (certStatus instanceof RevokedStatus) {
ocspStatus.setValidationStatus(ValidationStatus.Revoked);
} else {
ocspStatus.setValidationStatus(ValidationStatus.Unknown);
}
}
}
} catch (final OCSPException | IOException | ProcessingException | OperatorCreationException e) {
logger.error(e.getMessage(), e);
} catch (CertificateException e) {
e.printStackTrace();
}
return ocspStatus;
}
use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project xipki by xipki.
the class OcspBenchRequestor method buildRequest.
// method ask
private byte[] buildRequest(BigInteger[] serialNumbers) throws OcspRequestorException {
boolean canCache = (serialNumbers.length == 1) && !requestOptions.isUseNonce();
if (canCache) {
byte[] request = requests.get(serialNumbers[0]);
if (request != null) {
return request;
}
}
OCSPReqBuilder reqBuilder = new OCSPReqBuilder();
if (requestOptions.isUseNonce() || extensions != null) {
List<Extension> extns = new ArrayList<>(2);
if (requestOptions.isUseNonce()) {
Extension extn = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nextNonce(requestOptions.getNonceLen())));
extns.add(extn);
}
if (extensions != null) {
for (Extension extn : extensions) {
extns.add(extn);
}
}
reqBuilder.setRequestExtensions(new Extensions(extns.toArray(extnType)));
}
try {
for (BigInteger serialNumber : serialNumbers) {
CertID certId = new CertID(issuerhashAlg, issuerNameHash, issuerKeyHash, new ASN1Integer(serialNumber));
reqBuilder.addRequest(new CertificateID(certId));
}
byte[] request = reqBuilder.build().getEncoded();
if (canCache) {
requests.put(serialNumbers[0], request);
}
return request;
} catch (OCSPException | IOException ex) {
throw new OcspRequestorException(ex.getMessage(), ex);
}
}
Aggregations