use of org.bouncycastle.asn1.ocsp.OCSPRequest 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.asn1.ocsp.OCSPRequest in project xipki by xipki.
the class AbstractOcspRequestor method ask.
@Override
public OCSPResp ask(X509Certificate issuerCert, BigInteger[] serialNumbers, URL responderUrl, RequestOptions requestOptions, RequestResponseDebug debug) throws OcspResponseException, OcspRequestorException {
ParamUtil.requireNonNull("issuerCert", issuerCert);
ParamUtil.requireNonNull("requestOptions", requestOptions);
ParamUtil.requireNonNull("responderUrl", responderUrl);
byte[] nonce = null;
if (requestOptions.isUseNonce()) {
nonce = nextNonce(requestOptions.getNonceLen());
}
OCSPRequest ocspReq = buildRequest(issuerCert, serialNumbers, nonce, requestOptions);
byte[] encodedReq;
try {
encodedReq = ocspReq.getEncoded();
} catch (IOException ex) {
throw new OcspRequestorException("could not encode OCSP request: " + ex.getMessage(), ex);
}
RequestResponsePair msgPair = null;
if (debug != null) {
msgPair = new RequestResponsePair();
debug.add(msgPair);
if (debug.saveRequest()) {
msgPair.setRequest(encodedReq);
}
}
byte[] encodedResp;
try {
encodedResp = send(encodedReq, responderUrl, requestOptions);
} catch (IOException ex) {
throw new ResponderUnreachableException("IOException: " + ex.getMessage(), ex);
}
if (msgPair != null && debug.saveResponse()) {
msgPair.setResponse(encodedResp);
}
OCSPResp ocspResp;
try {
ocspResp = new OCSPResp(encodedResp);
} catch (IOException ex) {
throw new InvalidOcspResponseException("IOException: " + ex.getMessage(), ex);
}
Object respObject;
try {
respObject = ocspResp.getResponseObject();
} catch (OCSPException ex) {
throw new InvalidOcspResponseException("responseObject is invalid");
}
if (ocspResp.getStatus() != 0) {
return ocspResp;
}
if (!(respObject instanceof BasicOCSPResp)) {
return ocspResp;
}
BasicOCSPResp basicOcspResp = (BasicOCSPResp) respObject;
if (nonce != null) {
Extension nonceExtn = basicOcspResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
if (nonceExtn == null) {
throw new OcspNonceUnmatchedException(nonce, null);
}
byte[] receivedNonce = nonceExtn.getExtnValue().getOctets();
if (!Arrays.equals(nonce, receivedNonce)) {
throw new OcspNonceUnmatchedException(nonce, receivedNonce);
}
}
SingleResp[] singleResponses = basicOcspResp.getResponses();
if (singleResponses == null || singleResponses.length == 0) {
String msg = StringUtil.concat("response with no singleResponse is returned, expected is ", Integer.toString(serialNumbers.length));
throw new OcspTargetUnmatchedException(msg);
}
final int countSingleResponses = singleResponses.length;
if (countSingleResponses != serialNumbers.length) {
String msg = StringUtil.concat("response with ", Integer.toString(countSingleResponses), " singleResponse", (countSingleResponses > 1 ? "s" : ""), " is returned, expected is ", Integer.toString(serialNumbers.length));
throw new OcspTargetUnmatchedException(msg);
}
Request reqAt0 = Request.getInstance(ocspReq.getTbsRequest().getRequestList().getObjectAt(0));
CertID certId = reqAt0.getReqCert();
ASN1ObjectIdentifier issuerHashAlg = certId.getHashAlgorithm().getAlgorithm();
byte[] issuerKeyHash = certId.getIssuerKeyHash().getOctets();
byte[] issuerNameHash = certId.getIssuerNameHash().getOctets();
if (serialNumbers.length == 1) {
SingleResp singleResp = singleResponses[0];
CertificateID cid = singleResp.getCertID();
boolean issuerMatch = issuerHashAlg.equals(cid.getHashAlgOID()) && Arrays.equals(issuerKeyHash, cid.getIssuerKeyHash()) && Arrays.equals(issuerNameHash, cid.getIssuerNameHash());
if (!issuerMatch) {
throw new OcspTargetUnmatchedException("the issuer is not requested");
}
BigInteger serialNumber = cid.getSerialNumber();
if (!serialNumbers[0].equals(serialNumber)) {
throw new OcspTargetUnmatchedException("the serialNumber is not requested");
}
} else {
List<BigInteger> tmpSerials1 = Arrays.asList(serialNumbers);
List<BigInteger> tmpSerials2 = new ArrayList<>(tmpSerials1);
for (int i = 0; i < countSingleResponses; i++) {
SingleResp singleResp = singleResponses[i];
CertificateID cid = singleResp.getCertID();
boolean issuerMatch = issuerHashAlg.equals(cid.getHashAlgOID()) && Arrays.equals(issuerKeyHash, cid.getIssuerKeyHash()) && Arrays.equals(issuerNameHash, cid.getIssuerNameHash());
if (!issuerMatch) {
throw new OcspTargetUnmatchedException("the issuer specified in singleResponse[" + i + "] is not requested");
}
BigInteger serialNumber = cid.getSerialNumber();
if (!tmpSerials2.remove(serialNumber)) {
if (tmpSerials1.contains(serialNumber)) {
throw new OcspTargetUnmatchedException("serialNumber " + LogUtil.formatCsn(serialNumber) + "is contained in at least two singleResponses");
} else {
throw new OcspTargetUnmatchedException("serialNumber " + LogUtil.formatCsn(serialNumber) + " specified in singleResponse[" + i + "] is not requested");
}
}
}
// end for
}
return ocspResp;
}
use of org.bouncycastle.asn1.ocsp.OCSPRequest 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.asn1.ocsp.OCSPRequest in project xipki by xipki.
the class OcspRequest method getInstance.
public static OcspRequest getInstance(OCSPRequest req) throws EncodingException {
TBSRequest tbsReq0 = req.getTbsRequest();
org.bouncycastle.asn1.x509.Extensions extensions0 = tbsReq0.getRequestExtensions();
Set<String> criticalExtensionOids = new HashSet<>();
if (extensions0 != null) {
for (ASN1ObjectIdentifier oid : extensions0.getCriticalExtensionOIDs()) {
criticalExtensionOids.add(oid.getId());
}
}
ASN1Sequence requestList0 = tbsReq0.getRequestList();
final int n = requestList0.size();
List<CertID> requestList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
Request singleReq0 = Request.getInstance(requestList0.getObjectAt(i));
org.bouncycastle.asn1.ocsp.CertID certId0 = singleReq0.getReqCert();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(certId0.getHashAlgorithm().getEncoded());
out.write(certId0.getIssuerNameHash().getEncoded());
out.write(certId0.getIssuerKeyHash().getEncoded());
} catch (IOException ex) {
throw new EncodingException(ex.getMessage(), ex);
}
byte[] encodedIssuer = out.toByteArray();
RequestIssuer issuer = new RequestIssuer(encodedIssuer, 0, encodedIssuer.length);
CertID certId = new CertID(issuer, certId0.getSerialNumber().getValue());
requestList.add(certId);
}
List<ExtendedExtension> extensions = new LinkedList<>();
if (extensions0 != null) {
ASN1ObjectIdentifier[] extOids = extensions0.getExtensionOIDs();
for (ASN1ObjectIdentifier oid : extOids) {
org.bouncycastle.asn1.x509.Extension extension0 = extensions0.getExtension(oid);
byte[] encoded;
try {
encoded = extension0.getEncoded();
} catch (IOException ex) {
throw new EncodingException("error encoding Extension", ex);
}
extensions.add(ExtendedExtension.getInstance(encoded, 0, encoded.length));
}
}
return new OcspRequest(tbsReq0.getVersion().getValue().intValue(), requestList, extensions);
}
use of org.bouncycastle.asn1.ocsp.OCSPRequest in project xipki by xipki.
the class Foo method createRequest.
private static byte[] createRequest(Control control) throws Exception {
GeneralName requestorName = control.withRequestName ? new GeneralName(new X500Name("CN=requestor1")) : null;
AlgorithmIdentifier algId1 = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE);
CertID certId1 = new CertID(algId1, new DEROctetString(newBytes(20, (byte) 0x11)), new DEROctetString(newBytes(20, (byte) 0x12)), new ASN1Integer(BigInteger.valueOf(0x1234)));
Request request1 = new Request(certId1, null);
AlgorithmIdentifier algId2 = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1);
CertID certId2 = new CertID(algId2, new DEROctetString(newBytes(20, (byte) 0x21)), new DEROctetString(newBytes(20, (byte) 0x22)), new ASN1Integer(BigInteger.valueOf(0x1235)));
Request request2 = new Request(certId2, new Extensions(new Extension(ObjectIdentifiers.id_ad_timeStamping, false, newBytes(30, (byte) 0x33))));
// CHECKSTYLE:SKIP
ASN1Sequence requestList = new DERSequence(new ASN1Encodable[] { request1, request2 });
Extensions requestExtensions = null;
if (control.withNonce || control.withPrefSigAlgs) {
int size = 0;
if (control.withNonce) {
size++;
}
if (control.withPrefSigAlgs) {
size++;
}
Extension[] arrays = new Extension[size];
int offset = 0;
if (control.withNonce) {
arrays[offset++] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, control.extensionCritical, newBytes(20, (byte) 0x44));
}
if (control.withPrefSigAlgs) {
AlgorithmIdentifier sigAlg1 = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE);
AlgorithmIdentifier sigAlg2 = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
ASN1Sequence seq = new DERSequence(new ASN1Encodable[] { sigAlg1, sigAlg2 });
arrays[offset++] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_pref_sig_algs, control.extensionCritical, seq.getEncoded());
}
requestExtensions = new Extensions(arrays);
}
ASN1EncodableVector vec = new ASN1EncodableVector();
if (control.version != 0) {
vec.add(new DERTaggedObject(true, 0, new ASN1Integer(BigInteger.valueOf(control.version))));
}
if (requestorName != null) {
vec.add(new DERTaggedObject(true, 1, requestorName));
}
vec.add(requestList);
if (requestExtensions != null) {
vec.add(new DERTaggedObject(true, 2, requestExtensions));
}
TBSRequest tbsRequest = TBSRequest.getInstance(new DERSequence(vec));
Signature sig = null;
if (control.withSignature) {
sig = new Signature(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption), new DERBitString(newBytes(256, (byte) 0xFF)));
}
return new OCSPRequest(tbsRequest, sig).getEncoded();
}
Aggregations