Example usage for org.bouncycastle.asn1.x509 KeyPurposeId id_kp_OCSPSigning

List of usage examples for org.bouncycastle.asn1.x509 KeyPurposeId id_kp_OCSPSigning

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 KeyPurposeId id_kp_OCSPSigning.

Prototype

KeyPurposeId id_kp_OCSPSigning

To view the source code for org.bouncycastle.asn1.x509 KeyPurposeId id_kp_OCSPSigning.

Click Source Link

Document

{ id-kp 9 }

Usage

From source file:be.fedict.trust.ocsp.OcspTrustLinker.java

License:Open Source License

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    URI ocspUri = getOcspUri(childCertificate);
    if (null == ocspUri) {
        return TrustLinkerResult.UNDECIDED;
    }// ww  w.  j  av  a  2  s.  c o  m
    LOG.debug("OCSP URI: " + ocspUri);

    OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate,
            validationDate);
    if (null == ocspResp) {
        LOG.debug("OCSP response not found");
        return TrustLinkerResult.UNDECIDED;
    }

    int ocspRespStatus = ocspResp.getStatus();
    if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) {
        LOG.debug("OCSP response status: " + ocspRespStatus);
        return TrustLinkerResult.UNDECIDED;
    }

    Object responseObject = ocspResp.getResponseObject();
    BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject;

    X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts();
    for (X509CertificateHolder responseCertificate : responseCertificates) {
        LOG.debug("OCSP response cert: " + responseCertificate.getSubject());
        LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer());
    }

    algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate);

    if (0 == responseCertificates.length) {
        /*
         * This means that the OCSP response has been signed by the issuing
         * CA itself.
         */
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey());
        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
    } else {
        /*
         * We're dealing with a dedicated authorized OCSP Responder
         * certificate, or of course with a CA that issues the OCSP
         * Responses itself.
         */

        X509CertificateHolder ocspResponderCertificate = responseCertificates[0];
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate);

        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP Responser response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
        if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) {
            // check certificate signature algorithm
            algorithmPolicy.checkSignatureAlgorithm(
                    ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate);

            X509Certificate issuingCaCertificate;
            if (responseCertificates.length < 2) {
                // so the OCSP certificate chain only contains a single
                // entry
                LOG.debug("OCSP responder complete certificate chain missing");
                /*
                 * Here we assume that the OCSP Responder is directly signed
                 * by the CA.
                 */
                issuingCaCertificate = certificate;
            } else {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                issuingCaCertificate = (X509Certificate) certificateFactory
                        .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded()));
                /*
                 * Is next check really required?
                 */
                if (false == certificate.equals(issuingCaCertificate)) {
                    LOG.debug("OCSP responder certificate not issued by CA");
                    return TrustLinkerResult.UNDECIDED;
                }
            }
            // check certificate signature
            algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate);

            PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker();
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory
                    .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded()));
            LOG.debug("OCSP Responder public key fingerprint: "
                    + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded()));
            publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate,
                    validationDate, revocationData, algorithmPolicy);
            if (null == x509OcspResponderCertificate
                    .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) {
                LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck");
                /*
                 * TODO: perform CRL validation on the OCSP Responder
                 * certificate. On the other hand, do we really want to
                 * check the checker?
                 */
                return TrustLinkerResult.UNDECIDED;
            }
            List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage();
            if (null == extendedKeyUsage) {
                LOG.debug("OCSP Responder certificate has no extended key usage extension");
                return TrustLinkerResult.UNDECIDED;
            }
            if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage");
                return TrustLinkerResult.UNDECIDED;
            }
        } else {
            LOG.debug("OCSP Responder certificate equals the CA certificate");
            // and the CA certificate is already trusted at this point
        }
    }

    DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
    CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1),
            new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber());

    SingleResp[] singleResps = basicOCSPResp.getResponses();
    for (SingleResp singleResp : singleResps) {
        CertificateID responseCertificateId = singleResp.getCertID();
        if (false == certificateId.equals(responseCertificateId)) {
            continue;
        }
        DateTime thisUpdate = new DateTime(singleResp.getThisUpdate());
        DateTime nextUpdate;
        if (null != singleResp.getNextUpdate()) {
            nextUpdate = new DateTime(singleResp.getNextUpdate());
        } else {
            LOG.debug("no OCSP nextUpdate");
            nextUpdate = thisUpdate;
        }
        LOG.debug("OCSP thisUpdate: " + thisUpdate);
        LOG.debug("(OCSP) nextUpdate: " + nextUpdate);
        DateTime beginValidity = thisUpdate.minus(this.freshnessInterval);
        DateTime endValidity = nextUpdate.plus(this.freshnessInterval);
        DateTime validationDateTime = new DateTime(validationDate);
        if (validationDateTime.isBefore(beginValidity)) {
            LOG.warn("OCSP response not yet valid");
            continue;
        }
        if (validationDateTime.isAfter(endValidity)) {
            LOG.warn("OCSP response expired");
            continue;
        }
        if (null == singleResp.getCertStatus()) {
            LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal());
            addRevocationData(revocationData, ocspResp, ocspUri);
            return TrustLinkerResult.TRUSTED;
        } else {
            LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName());
            if (singleResp.getCertStatus() instanceof RevokedStatus) {
                LOG.debug("OCSP status revoked");
            }
            addRevocationData(revocationData, ocspResp, ocspUri);
            throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
                    "certificate revoked by OCSP");
        }
    }

    LOG.debug("no matching OCSP response entry");
    return TrustLinkerResult.UNDECIDED;
}

From source file:be.fedict.trust.test.PKITestUtils.java

License:Open Source License

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        DateTime notBefore, DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey,
        boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage,
        String signatureAlgorithm, boolean tsa, boolean includeSKID, boolean includeAKID,
        PublicKey akidPublicKey, String certificatePolicy, Boolean qcCompliance, boolean ocspResponder,
        boolean qcSSCD) throws IOException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException {

    X500Name issuerName;//from  w ww  .  j av  a 2s  .  c o m
    if (null != issuerCertificate) {
        issuerName = new X500Name(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerName = new X500Name(subjectDn);
    }
    X500Name subjectName = new X500Name(subjectDn);
    BigInteger serial = new BigInteger(128, new SecureRandom());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo);

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    if (includeSKID) {
        x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                extensionUtils.createSubjectKeyIdentifier(subjectPublicKey));
    }

    if (includeAKID) {

        PublicKey authorityPublicKey;
        if (null != akidPublicKey) {
            authorityPublicKey = akidPublicKey;
        } else if (null != issuerCertificate) {
            authorityPublicKey = issuerCertificate.getPublicKey();
        } else {
            authorityPublicKey = subjectPublicKey;
        }
        x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extensionUtils.createAuthorityKeyIdentifier(authorityPublicKey));
    }

    if (caFlag) {
        if (-1 == pathLength) {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(2147483647));
        } else {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(pathLength));
        }
    }

    if (null != crlUri) {
        GeneralName generalName = new GeneralName(GeneralName.uniformResourceIdentifier,
                new DERIA5String(crlUri));
        GeneralNames generalNames = new GeneralNames(generalName);
        DistributionPointName distPointName = new DistributionPointName(generalNames);
        DistributionPoint distPoint = new DistributionPoint(distPointName, null, null);
        DistributionPoint[] crlDistPoints = new DistributionPoint[] { distPoint };
        CRLDistPoint crlDistPoint = new CRLDistPoint(crlDistPoints);
        x509v3CertificateBuilder.addExtension(Extension.cRLDistributionPoints, false, crlDistPoint);
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        x509v3CertificateBuilder.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    if (null != keyUsage) {
        x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, keyUsage);
    }

    if (null != certificatePolicy) {
        ASN1ObjectIdentifier policyObjectIdentifier = new ASN1ObjectIdentifier(certificatePolicy);
        PolicyInformation policyInformation = new PolicyInformation(policyObjectIdentifier);
        x509v3CertificateBuilder.addExtension(Extension.certificatePolicies, false,
                new DERSequence(policyInformation));
    }

    if (null != qcCompliance) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        if (qcCompliance) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcCompliance));
        } else {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_RetentionPeriod));
        }
        if (qcSSCD) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcSSCD));
        }
        x509v3CertificateBuilder.addExtension(Extension.qCStatements, true, new DERSequence(vec));

    }

    if (tsa) {
        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
    }

    if (ocspResponder) {
        x509v3CertificateBuilder.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false,
                DERNull.INSTANCE);

        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning));
    }

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    return certificate;
}

From source file:net.maritimecloud.pki.ocsp.OCSPClient.java

License:Open Source License

public CertStatus getCertificateStatus() throws OCSPValidationException {
    try {//from  w  ww  .ja va  2s. c  o  m
        if (null == url) {
            throw new OCSPValidationException("Certificate not validated by OCSP");
        }

        byte[] encodedOcspRequest = generateOCSPRequest(issuer, certificate.getSerialNumber()).getEncoded();

        HttpURLConnection httpConnection;
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestProperty("Content-Type", "application/ocsp-request");
        httpConnection.setRequestProperty("Accept", "application/ocsp-response");
        httpConnection.setDoOutput(true);

        try (DataOutputStream dataOut = new DataOutputStream(
                new BufferedOutputStream(httpConnection.getOutputStream()))) {
            dataOut.write(encodedOcspRequest);
            dataOut.flush();
        }

        InputStream in = (InputStream) httpConnection.getContent();

        if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new OCSPValidationException(
                    "Received HTTP code != 200 [" + httpConnection.getResponseCode() + "]");
        }

        OCSPResp ocspResponse = new OCSPResp(in);
        BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        byte[] receivedNonce = basicResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnId()
                .getEncoded();
        if (!Arrays.equals(receivedNonce, sentNonce)) {
            throw new OCSPValidationException("Nonce in ocsp response does not match nonce of ocsp request");
        }

        X509CertificateHolder certHolder = basicResponse.getCerts()[0];
        if (!basicResponse
                .isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) {
            if (!certHolder.isValidOn(Date.from(Instant.now()))) {
                throw new OCSPValidationException("Certificate is not valid today!");
            }
            // Certificate must have a Key Purpose ID for authorized responders
            if (!ExtendedKeyUsage.fromExtensions(certHolder.getExtensions())
                    .hasKeyPurposeId(KeyPurposeId.id_kp_OCSPSigning)) {
                throw new OCSPValidationException(
                        "Certificate does not contain required extension (id_kp_OCSPSigning)");
            }
            // Certificate must be issued by the same CA of the certificate that we are verifying
            if (!certHolder.isSignatureValid(
                    new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) {
                throw new OCSPValidationException("Certificate is not signed by the same issuer");
            }
            // Validate signature in OCSP response
            if (!basicResponse.isSignatureValid(
                    new JcaContentVerifierProviderBuilder().setProvider("BC").build(certHolder))) {
                throw new OCSPValidationException("Could not validate OCSP response!");
            }
        } else {
            if (!certHolder.isValidOn(Date.from(Instant.now()))) {
                throw new OCSPValidationException("Certificate is not valid today!");
            }
        }

        // SCEE Certificate Policy (?)
        /*if (null == certHolder.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck) || null == certHolder.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck).getExtnId()) {
        throw new OCSPValidationException("Extension id_pkix_ocsp_nocheck not found in certificate");
        }*/

        SingleResp[] responses = basicResponse.getResponses();
        if (responses[0].getCertID().getSerialNumber().equals(certificate.getSerialNumber())) {
            CertificateStatus status = responses[0].getCertStatus();
            if (status == CertificateStatus.GOOD) {
                return CertStatus.GOOD;
            } else {

                if (status instanceof RevokedStatus) {
                    revokedStatus = (RevokedStatus) status;
                    return CertStatus.REVOKED;
                } else {
                    return CertStatus.UNKNOWN;
                }
            }
        } else {
            throw new OCSPValidationException(
                    "Serial number of certificate in response ocsp does not match certificate serial number");
        }
    } catch (CertificateEncodingException | OperatorCreationException | OCSPException | IOException ex) {
        throw new OCSPValidationException("Unable to perform validation through OCSP ("
                + certificate.getSubjectX500Principal().getName() + ")", ex);
    } catch (CertException | CertificateException ex) {
        throw new OCSPValidationException("Unable to perform validation through OCSP ("
                + certificate.getSubjectX500Principal().getName() + ")", ex);
    }
}

From source file:org.cesecore.certificates.certificateprofile.CertificateProfile.java

License:Open Source License

/**
 * @param type//from  www.j a v a 2s.  com
 *            one of CertificateProfileConstants.CERTPROFILE_FIXED_XX, for example CertificateConstants.CERTPROFILE_FIXED_ROOTCA
 */

private void setDefaultValues(int type) {
    if (type == CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA) {
        setType(CertificateConstants.CERTTYPE_ROOTCA);
        setAllowValidityOverride(true);
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        setKeyUsage(CertificateConstants.KEYCERTSIGN, true);
        setKeyUsage(CertificateConstants.CRLSIGN, true);
        setKeyUsageCritical(true);
        setValidity(25 * 365 + 7); // Default validity for this profile is 25 years including 6 or 7 leap days
    } else if (type == CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA) {
        setType(CertificateConstants.CERTTYPE_SUBCA);
        setAllowValidityOverride(true);
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        setKeyUsage(CertificateConstants.KEYCERTSIGN, true);
        setKeyUsage(CertificateConstants.CRLSIGN, true);
        setKeyUsageCritical(true);
        setValidity(25 * 365 + 7); // Default validity for this profile is 25 years including 6 or 7 leap days
    } else if (type == CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER) {
        setType(CertificateConstants.CERTTYPE_ENDENTITY);
        // Standard key usages for end users are: digitalSignature | nonRepudiation, and/or (keyEncipherment or keyAgreement)
        // Default key usage is digitalSignature | nonRepudiation | keyEncipherment
        // Create an array for KeyUsage according to X509Certificate.getKeyUsage()
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        setKeyUsage(CertificateConstants.NONREPUDIATION, true);
        setKeyUsage(CertificateConstants.KEYENCIPHERMENT, true);
        setKeyUsageCritical(true);
        setUseExtendedKeyUsage(true);
        ArrayList<String> eku = new ArrayList<String>();
        eku.add(KeyPurposeId.id_kp_clientAuth.getId());
        eku.add(KeyPurposeId.id_kp_emailProtection.getId());
        setExtendedKeyUsage(eku);
        setExtendedKeyUsageCritical(false);
    } else if (type == CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER) {
        setType(CertificateConstants.CERTTYPE_ENDENTITY);
        // Default key usage for an OCSP signer is digitalSignature
        // Create an array for KeyUsage acoording to X509Certificate.getKeyUsage()
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        setKeyUsageCritical(true);
        setUseExtendedKeyUsage(true);
        ArrayList<String> eku = new ArrayList<String>();
        eku.add(KeyPurposeId.id_kp_OCSPSigning.getId());
        setExtendedKeyUsage(eku);
        setExtendedKeyUsageCritical(false);
        setUseOcspNoCheck(true);
    } else if (type == CertificateProfileConstants.CERTPROFILE_FIXED_SERVER) {
        setType(CertificateConstants.CERTTYPE_ENDENTITY);
        // Standard key usages for server are: digitalSignature | (keyEncipherment or keyAgreement)
        // Default key usage is digitalSignature | keyEncipherment
        // Create an array for KeyUsage acoording to X509Certificate.getKeyUsage()
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        setKeyUsage(CertificateConstants.KEYENCIPHERMENT, true);
        setKeyUsageCritical(true);
        setUseExtendedKeyUsage(true);
        ArrayList<String> eku = new ArrayList<String>();
        eku.add(KeyPurposeId.id_kp_serverAuth.getId());
        setExtendedKeyUsage(eku);
        setExtendedKeyUsageCritical(false);
    } else if (type == CertificateProfileConstants.CERTPROFILE_FIXED_HARDTOKENAUTH) {
        setType(CertificateConstants.CERTTYPE_ENDENTITY);
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        setKeyUsageCritical(true);
        setUseExtendedKeyUsage(true);
        ArrayList<String> eku = new ArrayList<String>();
        eku.add(KeyPurposeId.id_kp_clientAuth.getId());
        eku.add(KeyPurposeId.id_kp_smartcardlogon.getId());
        setExtendedKeyUsage(eku);
        setExtendedKeyUsageCritical(false);
    } else if (type == CertificateProfileConstants.CERTPROFILE_FIXED_HARDTOKENAUTHENC) {
        setType(CertificateConstants.CERTTYPE_ENDENTITY);
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.KEYENCIPHERMENT, true);
        setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        setKeyUsageCritical(true);
        setUseExtendedKeyUsage(true);
        ArrayList<String> eku = new ArrayList<String>();
        eku.add(KeyPurposeId.id_kp_clientAuth.getId());
        eku.add(KeyPurposeId.id_kp_emailProtection.getId());
        eku.add(KeyPurposeId.id_kp_smartcardlogon.getId());
        setExtendedKeyUsage(eku);
        setExtendedKeyUsageCritical(false);
    } else if (type == CertificateProfileConstants.CERTPROFILE_FIXED_HARDTOKENENC) {
        setType(CertificateConstants.CERTTYPE_ENDENTITY);
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.KEYENCIPHERMENT, true);
        setKeyUsageCritical(true);
        setUseExtendedKeyUsage(true);
        ArrayList<String> eku = new ArrayList<String>();
        eku.add(KeyPurposeId.id_kp_emailProtection.getId());
        setExtendedKeyUsage(eku);
        setExtendedKeyUsageCritical(false);
    } else if (type == CertificateProfileConstants.CERTPROFILE_FIXED_HARDTOKENSIGN) {
        setType(CertificateConstants.CERTTYPE_ENDENTITY);
        setUseKeyUsage(true);
        setKeyUsage(new boolean[9]);
        setKeyUsage(CertificateConstants.NONREPUDIATION, true);
        setKeyUsageCritical(true);
        setUseExtendedKeyUsage(true);
        ArrayList<String> eku = new ArrayList<String>();
        eku.add(KeyPurposeId.id_kp_emailProtection.getId());
        setExtendedKeyUsage(eku);
        setExtendedKeyUsageCritical(false);
    }
}

From source file:org.cesecore.keybind.impl.OcspKeyBinding.java

License:Open Source License

private static void assertCertificateCompatabilityInternal(final Certificate certificate)
        throws CertificateImportException {
    if (certificate == null) {
        throw new CertificateImportException("No certificate provided.");
    }// w w w. j  a  v a  2 s. c  om
    if (!(certificate instanceof X509Certificate)) {
        throw new CertificateImportException("Only X509 certificates are supported for OCSP.");
    }
    try {
        final X509Certificate x509Certificate = (X509Certificate) certificate;
        if (log.isDebugEnabled()) {
            log.debug("SubjectDN: " + CertTools.getSubjectDN(x509Certificate) + " IssuerDN: "
                    + CertTools.getIssuerDN(x509Certificate));
            final boolean[] ku = x509Certificate.getKeyUsage();
            log.debug("Key usages: " + Arrays.toString(ku));
            if (ku != null) {
                log.debug("Key usage (digitalSignature): " + x509Certificate.getKeyUsage()[0]);
                log.debug("Key usage (nonRepudiation):   " + x509Certificate.getKeyUsage()[1]);
                log.debug("Key usage (keyEncipherment):  " + x509Certificate.getKeyUsage()[2]);
            }
        }
        if (x509Certificate.getExtendedKeyUsage() == null) {
            throw new CertificateImportException("No Extended Key Usage present in certificate.");
        }
        for (String extendedKeyUsage : x509Certificate.getExtendedKeyUsage()) {
            log.debug("EKU: " + extendedKeyUsage + " ("
                    + ExtendedKeyUsageConfiguration.getExtendedKeyUsageOidsAndNames().get(extendedKeyUsage)
                    + ")");
        }
        if (!x509Certificate.getExtendedKeyUsage().contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
            throw new CertificateImportException(
                    "Extended Key Usage 1.3.6.1.5.5.7.3.9 (EKU_PKIX_OCSPSIGNING) is required.");
        }
        if (!x509Certificate.getKeyUsage()[0] && !x509Certificate.getKeyUsage()[1]) {
            throw new CertificateImportException(
                    "Key Usage digitalSignature is required (nonRepudiation would also be accepted).");
        }
    } catch (CertificateParsingException e) {
        throw new CertificateImportException(e.getMessage(), e);
    }
}

From source file:org.cesecore.keybind.impl.OcspKeyBindingTest.java

License:Open Source License

/** @return An extended key usage extension with id_kp_OCSPSigning set. */
private static Extension getExtendedKeyUsageExtension() throws IOException {
    final ASN1Encodable usage = KeyPurposeId.getInstance(KeyPurposeId.id_kp_OCSPSigning);
    final ASN1Sequence seq = ASN1Sequence.getInstance(new DERSequence(usage));
    return new Extension(Extension.extendedKeyUsage, true, seq.getEncoded());
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Is OCSP extended key usage set for a certificate?
 * //from  w w w. j  av a 2 s.c  om
 * @param cert to check.
 * @return true if the extended key usage for OCSP is check
 */
public static boolean isOCSPCert(X509Certificate cert) {
    final List<String> keyUsages;
    try {
        keyUsages = cert.getExtendedKeyUsage();
    } catch (CertificateParsingException e) {
        return false;
    }
    return keyUsages != null && keyUsages.contains(KeyPurposeId.id_kp_OCSPSigning.getId());
}

From source file:org.ejbca.core.model.ca.certificateprofiles.OCSPSignerCertificateProfile.java

License:Open Source License

/** Creates a certificate with the characteristics of an end user. 
 * General options are set in the superclass's default contructor that is called automatically.
 * You can override the general options by defining them again with different parameters here.
 *//*from   w  ww .  jav a 2  s. c o m*/
public OCSPSignerCertificateProfile() {

    setType(TYPE_ENDENTITY);

    // Default key usage for an OCSP signer is digitalSignature
    // Create an array for KeyUsage acoording to X509Certificate.getKeyUsage()
    setUseKeyUsage(true);
    setKeyUsage(new boolean[9]);
    setKeyUsage(DIGITALSIGNATURE, true);
    setKeyUsageCritical(true);

    setUseExtendedKeyUsage(true);
    ArrayList eku = new ArrayList();
    eku.add(KeyPurposeId.id_kp_OCSPSigning.getId());
    setExtendedKeyUsage(eku);
    setExtendedKeyUsageCritical(false);

    setUseOcspNoCheck(true);

}

From source file:org.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * Creates a CertificateExtension. The id can be the OID or the name as
 * defined below. The values is a comma separated list of value(s)
 * <p>/*from  w ww  .  j  a v a  2  s .  co m*/
 * Valid names and values:
 * <ul>
 * <li>KeyUsage
 * <ul>
 * <li>DigitalSignature
 * <li>NonRepudiation
 * <li>KeyEncipherment
 * <li>DataEncipherment
 * <li>KeyAgreement
 * <li>KeyCertSign
 * <li>CRLSign
 * <li>EncipherOnly
 * <li>DecipherOnly
 * </ul>
 * <li>ExtendedKeyUsage
 * <ul>
 * <li>AnyExtendedKeyUsage
 * <li>ServerAuth
 * <li>ClientAuth
 * <li>CodeSigning
 * <li>EmailProtection
 * <li>IPSecEndSystem
 * <li>IPSecTunnel
 * <li>IPSecUser
 * <li>OCSPSigning
 * <li>Smartcardlogon
 * </ul>
 * <li>CertificatePolicies
 * <ul>
 * <li>The policy OID(s)
 * </ul>
 * <li>SubjectAltName
 * <ul>
 * <li>email:EMAIL_ADDRESS
 * <li>dns:HOSTNAME
 * </ul>
 * </ul>
 * <p>
 * Example:
 * <pre>
 * CertificateExtension keyUsageExtension = 
 *       CertificateExtensionFactory.createCertificateExtension("KeyUsage", "DigitalSignature,KeyEncipherment");
 * CertificateExtension subjectAltNameExtension = 
 *       CertificateExtensionFactory.createCertificateExtension("SubjectAltName", "email:john.doe@example.com,dns:www.exmaple.com");
 * </pre>
 * 
 * @param id
 *            The name or the OID of the extension.
 * @param values
 *            A comma separated list of extension value(s).
 * @return The corresponding CertificateExtension or <code>null</code> if
 *         the id (name or oid) is not supported.
 */
static public CertificateExtension createCertificateExtension(String id, String values) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("id:" + id + " value(s):" + values);
    }
    if (id.equals(X509Extensions.KeyUsage.getId()) || id.equalsIgnoreCase("KeyUsage")) {
        // parse the comma separated list of key usage
        int usage = 0;
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String keyUsage = (String) st.nextElement();
            keyUsage = keyUsage.trim();

            if (keyUsage.equalsIgnoreCase("DigitalSignature")) {
                usage += KeyUsage.digitalSignature;
            } else if (keyUsage.equalsIgnoreCase("NonRepudiation")) {
                usage += KeyUsage.nonRepudiation;
            } else if (keyUsage.equalsIgnoreCase("KeyEncipherment")) {
                usage += KeyUsage.keyEncipherment;
            } else if (keyUsage.equalsIgnoreCase("DataEncipherment")) {
                usage += KeyUsage.dataEncipherment;
            } else if (keyUsage.equalsIgnoreCase("KeyAgreement")) {
                usage += KeyUsage.keyAgreement;
            } else if (keyUsage.equalsIgnoreCase("KeyCertSign")) {
                usage += KeyUsage.keyCertSign;
            } else if (keyUsage.equalsIgnoreCase("CRLSign")) {
                usage += KeyUsage.cRLSign;
            } else if (keyUsage.equalsIgnoreCase("EncipherOnly")) {
                usage += KeyUsage.encipherOnly;
            } else if (keyUsage.equalsIgnoreCase("DecipherOnly")) {
                usage += KeyUsage.decipherOnly;
            } else {
                LOG.error("Unknown KeyUsage: " + keyUsage);
            }

        }
        return createKeyUsageExtension(usage, values);
    } else if (id.equals(X509Extensions.ExtendedKeyUsage.getId()) || id.equalsIgnoreCase("ExtendedKeyUsage")) {
        // value is a comma separated list of keyPurpose
        Vector keyPurposeIds = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String keyPurpose = (String) st.nextElement();
            keyPurpose = keyPurpose.trim();
            if (keyPurpose.equalsIgnoreCase("AnyExtendedKeyUsage")) {
                keyPurposeIds.add(KeyPurposeId.anyExtendedKeyUsage);
            } else if (keyPurpose.equalsIgnoreCase("ServerAuth")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_serverAuth);
            } else if (keyPurpose.equalsIgnoreCase("ClientAuth")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_clientAuth);
            } else if (keyPurpose.equalsIgnoreCase("CodeSigning")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_codeSigning);
            } else if (keyPurpose.equalsIgnoreCase("EmailProtection")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_emailProtection);
            } else if (keyPurpose.equalsIgnoreCase("IPSecEndSystem")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecEndSystem);
            } else if (keyPurpose.equalsIgnoreCase("IPSecTunnel")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecTunnel);
            } else if (keyPurpose.equalsIgnoreCase("IPSecUser")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecUser);
            } else if (keyPurpose.equalsIgnoreCase("TimeStamping")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_timeStamping);
            } else if (keyPurpose.equalsIgnoreCase("OCSPSigning")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_OCSPSigning);
            } else if (keyPurpose.equalsIgnoreCase("Smartcardlogon")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_smartcardlogon);
            } else {
                LOG.error("Unknown ExtendedKeyUsage: " + keyPurpose);
            }
        }
        return createExtendedKeyUsageExtension(keyPurposeIds, values);
    } else if (id.equals(X509Extensions.CertificatePolicies.getId())
            || id.equalsIgnoreCase("CertificatePolicies")) {
        // values is a comma separated list of policyOIDs
        Vector policyOIDs = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String policyOID = (String) st.nextElement();
            policyOID = policyOID.trim();
            policyOIDs.add(policyOID);
        }
        return createCertificatePoliciesExtension(policyOIDs, values);
    } else if (id.equals(X509Extensions.SubjectAlternativeName.getId())
            || id.equalsIgnoreCase("SubjectAltName")) {
        // values is a comma separated list of altername names prefixed with
        // the type (email: or dns:)
        Vector typedSubjectAltNames = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String typedAltName = (String) st.nextElement();
            typedAltName = typedAltName.trim();
            typedSubjectAltNames.add(typedAltName);
        }
        return createSubjectAltNameExtension(typedSubjectAltNames, values);
    }
    LOG.error("Unsupported CertificateExtension: " + id);
    return null;
}

From source file:org.keycloak.common.util.OCSPUtils.java

License:Apache License

private static void verifyResponse(BasicOCSPResp basicOcspResponse, X509Certificate issuerCertificate,
        X509Certificate responderCertificate, byte[] requestNonce, Date date)
        throws NoSuchProviderException, NoSuchAlgorithmException, CertificateNotYetValidException,
        CertificateExpiredException, CertPathValidatorException {

    List<X509CertificateHolder> certs = new ArrayList<>(Arrays.asList(basicOcspResponse.getCerts()));
    X509Certificate signingCert = null;

    try {/*from   w  ww.  j  a  v  a  2  s. c  o m*/
        certs.add(new JcaX509CertificateHolder(issuerCertificate));
        if (responderCertificate != null) {
            certs.add(new JcaX509CertificateHolder(responderCertificate));
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    }
    if (certs.size() > 0) {

        X500Name responderName = basicOcspResponse.getResponderId().toASN1Primitive().getName();
        byte[] responderKey = basicOcspResponse.getResponderId().toASN1Primitive().getKeyHash();

        if (responderName != null) {
            logger.log(Level.INFO, "Responder Name: {0}", responderName.toString());
            for (X509CertificateHolder certHolder : certs) {
                try {
                    X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC")
                            .getCertificate(certHolder);
                    X500Name respName = new X500Name(tempCert.getSubjectX500Principal().getName());
                    if (responderName.equals(respName)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO,
                                "Found a certificate whose principal \"{0}\" matches the responder name \"{1}\"",
                                new Object[] { tempCert.getSubjectDN().getName(), responderName.toString() });
                        break;
                    }
                } catch (CertificateException e) {
                    logger.log(Level.FINE, e.getMessage());
                }
            }
        } else if (responderKey != null) {
            SubjectKeyIdentifier responderSubjectKey = new SubjectKeyIdentifier(responderKey);
            logger.log(Level.INFO, "Responder Key: {0}", Arrays.toString(responderKey));
            for (X509CertificateHolder certHolder : certs) {
                try {
                    X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC")
                            .getCertificate(certHolder);

                    SubjectKeyIdentifier subjectKeyIdentifier = null;
                    if (certHolder.getExtensions() != null) {
                        subjectKeyIdentifier = SubjectKeyIdentifier.fromExtensions(certHolder.getExtensions());
                    }

                    if (subjectKeyIdentifier != null) {
                        logger.log(Level.INFO, "Certificate: {0}\nSubject Key Id: {1}",
                                new Object[] { tempCert.getSubjectDN().getName(),
                                        Arrays.toString(subjectKeyIdentifier.getKeyIdentifier()) });
                    }

                    if (subjectKeyIdentifier != null && responderSubjectKey.equals(subjectKeyIdentifier)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO,
                                "Found a signer certificate \"{0}\" with the subject key extension value matching the responder key",
                                signingCert.getSubjectDN().getName());

                        break;
                    }

                    subjectKeyIdentifier = new JcaX509ExtensionUtils()
                            .createSubjectKeyIdentifier(tempCert.getPublicKey());
                    if (responderSubjectKey.equals(subjectKeyIdentifier)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO,
                                "Found a certificate \"{0}\" with the subject key matching the OCSP responder key",
                                signingCert.getSubjectDN().getName());
                        break;
                    }

                } catch (CertificateException e) {
                    logger.log(Level.FINE, e.getMessage());
                }
            }
        }
    }
    if (signingCert != null) {
        if (signingCert.equals(issuerCertificate)) {
            logger.log(Level.INFO, "OCSP response is signed by the target''s Issuing CA");
        } else if (responderCertificate != null && signingCert.equals(responderCertificate)) {
            // https://www.ietf.org/rfc/rfc2560.txt
            // 2.6  OCSP Signature Authority Delegation
            // - The responder certificate is issued to the responder by CA
            logger.log(Level.INFO, "OCSP response is signed by an authorized responder certificate");
        } else {
            // 4.2.2.2  Authorized Responders
            // 3. Includes a value of id-ad-ocspSigning in an ExtendedKeyUsage
            // extension and is issued by the CA that issued the certificate in
            // question."
            if (!signingCert.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
                logger.log(Level.INFO, "Signer certificate''s Issuer: {0}\nIssuer certificate''s Subject: {1}",
                        new Object[] { signingCert.getIssuerX500Principal().getName(),
                                issuerCertificate.getSubjectX500Principal().getName() });
                throw new CertPathValidatorException(
                        "Responder\'s certificate is not authorized to sign OCSP responses");
            }
            try {
                List<String> purposes = signingCert.getExtendedKeyUsage();
                if (purposes != null && !purposes.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                    logger.log(Level.INFO, "OCSPSigning extended usage is not set");
                    throw new CertPathValidatorException(
                            "Responder\'s certificate not valid for signing OCSP responses");
                }
            } catch (CertificateParsingException e) {
                logger.log(Level.FINE, "Failed to get certificate''s extended key usage extension\n{0}",
                        e.getMessage());
            }
            if (date == null) {
                signingCert.checkValidity();
            } else {
                signingCert.checkValidity(date);
            }
            try {
                Extension noOCSPCheck = new JcaX509CertificateHolder(signingCert)
                        .getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck);
                // TODO If the extension is present, the OCSP client can trust the
                // responder's certificate for the lifetime of the certificate.
                logger.log(Level.INFO, "OCSP no-check extension is {0} present",
                        noOCSPCheck == null ? "not" : "");
            } catch (CertificateEncodingException e) {
                logger.log(Level.FINE, "Certificate encoding exception: {0}", e.getMessage());
            }

            try {
                signingCert.verify(issuerCertificate.getPublicKey());
                logger.log(Level.INFO, "OCSP response is signed by an Authorized Responder");

            } catch (GeneralSecurityException ex) {
                signingCert = null;
            }
        }
    }
    if (signingCert == null) {
        throw new CertPathValidatorException("Unable to verify OCSP Response\'s signature");
    } else {
        if (!verifySignature(basicOcspResponse, signingCert)) {
            throw new CertPathValidatorException("Error verifying OCSP Response\'s signature");
        } else {
            Extension responseNonce = basicOcspResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
            if (responseNonce != null && requestNonce != null
                    && !Arrays.equals(requestNonce, responseNonce.getExtnValue().getOctets())) {
                throw new CertPathValidatorException("Nonces do not match.");
            } else {
                // See Sun's OCSP implementation.
                // https://www.ietf.org/rfc/rfc2560.txt, if nextUpdate is not set,
                // the responder is indicating that newer update is avilable all the time
                long current = date == null ? System.currentTimeMillis() : date.getTime();
                Date stop = new Date(current + (long) TIME_SKEW);
                Date start = new Date(current - (long) TIME_SKEW);

                Iterator<SingleResp> iter = Arrays.asList(basicOcspResponse.getResponses()).iterator();
                SingleResp singleRes = null;
                do {
                    if (!iter.hasNext()) {
                        return;
                    }
                    singleRes = iter.next();
                } while (!stop.before(singleRes.getThisUpdate())
                        && !start.after(singleRes.getNextUpdate() != null ? singleRes.getNextUpdate()
                                : singleRes.getThisUpdate()));

                throw new CertPathValidatorException(
                        "Response is unreliable: its validity interval is out-of-date");
            }
        }
    }
}