Java源码示例:org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers

示例1
/**
 * 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();
}
 
示例2
/**
 * 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();
}
 
示例3
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);
	}
}
 
示例4
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);
	}
}
 
示例5
private void addBasicOcspRespFrom_id_pkix_ocsp_basic() {
	final Store otherRevocationInfo = cmsSignedData.getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
	final Collection otherRevocationInfoMatches = otherRevocationInfo.getMatches(null);
	for (final Object object : otherRevocationInfoMatches) {
		if (object instanceof ASN1Sequence) {
			final ASN1Sequence otherRevocationInfoMatch = (ASN1Sequence) object;
			final BasicOCSPResp basicOCSPResp = DSSRevocationUtils.getBasicOcspResp(otherRevocationInfoMatch);
			if (basicOCSPResp != null) {
				OCSPResponseBinary ocspResponseIdentifier = OCSPResponseBinary.build(basicOCSPResp);
				ocspResponseIdentifier.setAsn1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
				addBinary(ocspResponseIdentifier, RevocationOrigin.CMS_SIGNED_DATA);
			} else {
				LOG.warn("Unable to create an OCSP response from an objects. The entry is skipped.");
			}
		} else {
			LOG.warn("Unsupported object type for id_pkix_ocsp_basic (SHALL be an ASN1Sequence) : {}", object.getClass().getSimpleName());
		}
	}
}
 
示例6
/**
 * Indicates if the revocation data should be checked for an OCSP signing certificate.<br>
 * http://www.ietf.org/rfc/rfc2560.txt?number=2560<br>
 * A CA may specify that an OCSP client can trust a responder for the lifetime of the responder's certificate. The
 * CA does so by including the extension id-pkix-ocsp-nocheck. This SHOULD be a non-critical extension. The value of
 * the extension should be NULL.
 *
 * @param token
 *            the certificate to be checked
 * @return true if the certificate has the id_pkix_ocsp_nocheck extension
 */
public static boolean hasIdPkixOcspNoCheckExtension(CertificateToken token) {
	final byte[] extensionValue = token.getCertificate().getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId());
	if (extensionValue != null) {
		try {
			final ASN1Primitive derObject = toASN1Primitive(extensionValue);
			if (derObject instanceof DEROctetString) {
				return isDEROctetStringNull((DEROctetString) derObject);
			}
		} catch (Exception e) {
			LOG.debug("Exception when processing 'id_pkix_ocsp_no_check'", e);
		}
	}
	return false;
}
 
示例7
private void extractArchiveCutOff(SingleResp bestSingleResp) {
	Extension extension = bestSingleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
	if (extension != null) {
		ASN1GeneralizedTime archiveCutOffAsn1 = (ASN1GeneralizedTime) extension.getParsedValue();
		try {
			archiveCutOff = archiveCutOffAsn1.getDate();
		} catch (ParseException e) {
			LOG.warn("Unable to extract id_pkix_ocsp_archive_cutoff : {}", e.getMessage());
		}
	}
}
 
示例8
/**
 * Convert a BasicOCSPResp in OCSPResp (connection status is set to
 * SUCCESSFUL).
 *
 * @param basicOCSPRespBinary
 *            the binary of BasicOCSPResp
 * @return an instance of OCSPResp
 */
public static OCSPResp fromBasicToResp(final byte[] basicOCSPRespBinary) {
	final OCSPResponseStatus responseStatus = new OCSPResponseStatus(OCSPResponseStatus.SUCCESSFUL);
	final DEROctetString derBasicOCSPResp = new DEROctetString(basicOCSPRespBinary);
	final ResponseBytes responseBytes = new ResponseBytes(OCSPObjectIdentifiers.id_pkix_ocsp_basic, derBasicOCSPResp);
	final OCSPResponse ocspResponse = new OCSPResponse(responseStatus, responseBytes);
	// !!! todo to be checked: System.out.println("===> RECREATED: " +
	// ocspResp.hashCode());
	return new OCSPResp(ocspResponse);
}
 
示例9
@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);
  }
}
 
示例10
/**
 * Extends the provided {@code cmsSignedData} with the required validation data
 * @param cmsSignedData {@link CMSSignedData} to be extended
 * @param validationDataForInclusion the {@link ValidationDataForInclusion} to be included into the cmsSignedData
 * @param detachedContents list of detached {@link DSSDocument}s
 * @return extended {@link CMSSignedData}
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public CMSSignedData extendCMSSignedData(CMSSignedData cmsSignedData, ValidationDataForInclusion validationDataForInclusion, 
		List<DSSDocument> detachedContents) {

	Store<X509CertificateHolder> certificatesStore = cmsSignedData.getCertificates();
	final Set<CertificateToken> certificates = validationDataForInclusion.getCertificateTokens();
	final Collection<X509CertificateHolder> newCertificateStore = new HashSet<>(certificatesStore.getMatches(null));
	for (final CertificateToken certificateToken : certificates) {
		final X509CertificateHolder x509CertificateHolder = DSSASN1Utils.getX509CertificateHolder(certificateToken);
		newCertificateStore.add(x509CertificateHolder);
	}
	certificatesStore = new CollectionStore<>(newCertificateStore);

	Store<X509CRLHolder> crlsStore = cmsSignedData.getCRLs();
	final Collection<X509CRLHolder> newCrlsStore = new HashSet<>(crlsStore.getMatches(null));
	final List<CRLToken> crlTokens = validationDataForInclusion.getCrlTokens();
	for (final CRLToken crlToken : crlTokens) {
		final X509CRLHolder x509CRLHolder = getX509CrlHolder(crlToken);
		newCrlsStore.add(x509CRLHolder);
	}
	crlsStore = new CollectionStore<>(newCrlsStore);

	Store otherRevocationInfoFormatStoreBasic = cmsSignedData.getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
	final Collection<ASN1Primitive> newOtherRevocationInfoFormatStore = new HashSet<>(otherRevocationInfoFormatStoreBasic.getMatches(null));
	final List<OCSPToken> ocspTokens = validationDataForInclusion.getOcspTokens();
	for (final OCSPToken ocspToken : ocspTokens) {
		final BasicOCSPResp basicOCSPResp = ocspToken.getBasicOCSPResp();
		if (basicOCSPResp != null) {
			newOtherRevocationInfoFormatStore.add(DSSASN1Utils.toASN1Primitive(DSSASN1Utils.getEncoded(basicOCSPResp)));
		}
	}
	otherRevocationInfoFormatStoreBasic = new CollectionStore(newOtherRevocationInfoFormatStore);

	Store attributeCertificatesStore = cmsSignedData.getAttributeCertificates();
	Store otherRevocationInfoFormatStoreOcsp = cmsSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);

	final CMSSignedDataBuilder cmsSignedDataBuilder = new CMSSignedDataBuilder(certificateVerifier);
	cmsSignedData = cmsSignedDataBuilder.regenerateCMSSignedData(cmsSignedData, detachedContents, certificatesStore, attributeCertificatesStore, crlsStore,
			otherRevocationInfoFormatStoreBasic, otherRevocationInfoFormatStoreOcsp);
	return cmsSignedData;
}
 
示例11
@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();
}