Example usage for org.bouncycastle.asn1.x509 SubjectKeyIdentifier getKeyIdentifier

List of usage examples for org.bouncycastle.asn1.x509 SubjectKeyIdentifier getKeyIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 SubjectKeyIdentifier getKeyIdentifier.

Prototype

public byte[] getKeyIdentifier() 

Source Link

Usage

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

License:Open Source License

/**
 * Get the subject key identifier from a certificate extensions
 * /*from w  w w.  j ava  2 s.com*/
 * @param cert certificate containing the extension
 * @return byte[] containing the subject key identifier, or null if it does not exist
 */
public static byte[] getSubjectKeyId(Certificate cert) {
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;
        byte[] extvalue = x509cert.getExtensionValue("2.5.29.14");
        if (extvalue == null) {
            return null;
        }
        ASN1InputStream extvalueAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extvalue));
        try {
            try {
                ASN1OctetString str = ASN1OctetString.getInstance(extvalueAsn1InputStream.readObject());
                ASN1InputStream strAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(str.getOctets()));
                try {
                    SubjectKeyIdentifier keyId = SubjectKeyIdentifier
                            .getInstance(strAsn1InputStream.readObject());
                    return keyId.getKeyIdentifier();
                } finally {
                    strAsn1InputStream.close();
                }
            } finally {
                extvalueAsn1InputStream.close();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Could not parse subject key ID from certificate.", e);
        }
    }
    return null;
}

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

License:Open Source License

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs)
        throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;//ww w.  j  a  v a 2  s .  c  o  m
        }
    }

    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject()
                    .getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();

                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf
                                    .generateCertificate(new ByteArrayInputStream(byteValue));
                            //check that the certificate is still valid
                            cert.checkValidity();

                            //HoK spec section 2.5:
                            //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession.
                            //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte.
                            //if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                //verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException
                                | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with certificate.");
                        }

                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        //HoK spec section 2.5:
                        //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate.
                        //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject DN.");
                        }

                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        //we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException(
                                "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(assertionOs.getOctets());
                            //HoK spec section 2.5:
                            //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate.
                            //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension,
                            //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(),
                                    assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException(
                                        "Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}

From source file:org.codice.ddf.security.saml.assertion.validator.impl.SamlAssertionValidatorImpl.java

License:Open Source License

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs)
        throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;//w  w w. j a v  a  2  s.  co  m
        }
    }

    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject()
                    .getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();

                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf
                                    .generateCertificate(new ByteArrayInputStream(byteValue));
                            // check that the certificate is still valid
                            cert.checkValidity();

                            // HoK spec section 2.5:
                            // relying party MUST ensure that the certificate bound to the assertion matches the
                            // X.509 certificate in its possession.
                            // Matching is done by comparing the base64-decoded certificates, or the hash values
                            // of the base64-decoded certificates, byte-for-byte.
                            // if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                // verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException
                                | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with certificate.");
                        }

                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        // HoK spec section 2.5:
                        // relying party MUST ensure that the subject distinguished name (DN) bound to the
                        // assertion matches the DN bound to the X.509 certificate.
                        // If, however, the relying party does not trust the certificate issuer to issue such
                        // a DN, the attesting entity is not confirmed and the relying party SHOULD disregard
                        // the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject DN.");
                        }

                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        // we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException(
                                "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(assertionOs.getOctets());
                            // HoK spec section 2.5:
                            // relying party MUST ensure that the value bound to the assertion matches the
                            // Subject Key Identifier (SKI) extension bound to the X.509 certificate.
                            // Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the
                            // X.509 certificate does not contain an SKI extension,
                            // the attesting entity is not confirmed and the relying party SHOULD disregard the
                            // assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(),
                                    assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException(
                                        "Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}

From source file:org.cryptacular.x509.ExtensionReaderTest.java

License:Open Source License

@Test(dataProvider = "subject-key-id")
public void testReadSubjectKeyIdentifier(final X509Certificate cert, final String expected) throws Exception {
    final SubjectKeyIdentifier keyId = new ExtensionReader(cert).readSubjectKeyIdentifier();
    assertEquals(CodecUtil.hex(keyId.getKeyIdentifier(), true).toUpperCase(), expected);
}

From source file:org.ejbca.ui.cli.ca.CaRenewCACommand.java

License:Open Source License

private static String computeSubjectKeyIdentifier(final X509Certificate certificate) {
    ASN1InputStream asn1InputStream = new ASN1InputStream(
            new ByteArrayInputStream(certificate.getPublicKey().getEncoded()));
    try {//from  ww  w.  j a  v  a2s. c  o  m
        try {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject());
            X509ExtensionUtils utils = new X509ExtensionUtils(SHA1DigestCalculator.buildSha1Instance());
            SubjectKeyIdentifier ski = utils.createSubjectKeyIdentifier(spki);
            return new String(Hex.encode(ski.getKeyIdentifier()));

        } catch (IOException e) {
            return "n/a";
        } finally {
            asn1InputStream.close();
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unknown IOException was caught.", e);
    }
}

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

License:Open Source License

/**
 * Get the subject key identifier from a certificate extensions
 *
 * @param cert certificate containing the extension
 * @return byte[] containing the subject key identifier, or null if it does not exist
 * @throws IOException if extension can not be parsed
 *//*from w  w  w. j  a  va 2 s  .c o  m*/
public static byte[] getSubjectKeyId(Certificate cert) throws IOException {
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;
        byte[] extvalue = x509cert.getExtensionValue("2.5.29.14");
        if (extvalue == null) {
            return null;
        }
        ASN1OctetString str = ASN1OctetString
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject());
        SubjectKeyIdentifier keyId = SubjectKeyIdentifier
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject());
        return keyId.getKeyIdentifier();
    }
    return null;
}

From source file:org.glite.voms.PKIUtils.java

License:Open Source License

/**
 * Checks if a certificate issued another certificate, according to RFC 3280.
 *
 * @param issuer The candidate issuer certificate.
 * @param issued The candidate issued certificate.
 *
 * @return true if <em>issuer</em> issued <em>issued</em>, false othersie.
 *//*from   w  ww  .  j  a v  a  2 s .  c om*/
static public boolean checkIssued(X509Certificate issuer, X509Certificate issued) {
    X500Principal issuerSubject = issuer.getSubjectX500Principal();
    X500Principal issuedIssuer = issued.getIssuerX500Principal();

    if (logger.isDebugEnabled()) {
        logger.debug("Is: " + issued.getSubjectDN().getName() + " issued by " + issuer.getSubjectDN().getName()
                + "?");

        logger.debug("Is: " + issuedIssuer.getName() + " issued by " + issuerSubject.getName() + "?");
        logger.debug(
                "Is: " + issued.getSubjectDN().getName() + " issued by " + issuer.getSubjectDN().getName());
        logger.debug("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[");
    }
    //        try {
    boolean b = issuerSubject.equals(issuedIssuer);
    //        }
    //        catch(Exception e) {
    //            System.out.println("Caught: " + e.getMessage() + " " + e.getClass());
    //        }

    if (issuerSubject.equals(issuedIssuer)) {
        logger.debug("================================");
        logger.debug("issuersSubject = issuedIssuer");

        AuthorityKeyIdentifier akid = PKIUtils.getAKID(issued);
        if (logger.isDebugEnabled())
            logger.debug("akid = " + akid);

        if (akid != null) {
            logger.debug("Authority Key Identifier extension found in issued certificate.");

            logger.debug("Entered.");
            SubjectKeyIdentifier skid = PKIUtils.getSKID(issuer);

            if (logger.isDebugEnabled())
                logger.debug("sid = " + skid);

            if (skid != null) {
                logger.debug("subject Key Identifier extensions found in issuer certificate.");
                logger.debug("comparing skid to akid");

                byte[] skidValue = skid.getKeyIdentifier();
                if (logger.isDebugEnabled()) {
                    logger.debug("skid");

                    String str = "";
                    for (int i = 0; i < skidValue.length; i++)
                        str += Integer.toHexString(skidValue[i]) + " ";
                    logger.debug(str);
                }

                byte[] akidValue = akid.getKeyIdentifier();
                if (logger.isDebugEnabled()) {
                    logger.debug("akid");

                    String str = "";
                    for (int i = 0; i < akidValue.length; i++)
                        str += Integer.toHexString(akidValue[i]) + " ";
                    logger.debug(str);
                }

                logger.debug("skid/akid checking.");
                if (!Arrays.equals(skidValue, akidValue))
                    return false;

                logger.debug("skid/akid check passed.");
            }

            if (false) {
                // The following should be skipped if the previous check passed.
                // And code cannot reach here unless the previous step passed.
                BigInteger sn = getAuthorityCertificateSerialNumber(akid);
                //
                //                if (sn == null) {
                //                    logger.error("Serial number missing from Authority Key Identifier");
                //                    return false;
                //                }
                //
                //                if (!sn.equals(issuer.getSerialNumber())) {
                //                    logger.error("Serial number in Authority Key Identifier and in issuer certificate do not match");
                //                    logger.error("From akid              : " + sn.toString());
                //                    logger.error("From issuer certificate: " + issuer.getSerialNumber());
                //                    return false;
                //                }

                if (sn != null && !sn.equals(issuer.getSerialNumber())) {
                    logger.error(
                            "Serial number in Authority Key Identifier and in issuer certificate do not match");
                    logger.error("From akid              : " + sn.toString());
                    logger.error("From issuer certificate: " + issuer.getSerialNumber());
                    return false;
                }

                GeneralNames gns = getAuthorityCertIssuer(akid);

                if (gns != null) {
                    GeneralName names[] = getNames(gns);

                    //                System.out.println("GOT CERTISSUER");

                    int i = 0;
                    //                System.out.println("SIZE = " + names.length);
                    while (i < names.length) {
                        //                    System.out.println("NAME = " + names[i].getName());
                        //                    System.out.println("TAG IS: " + names[i].getTagNo());
                        if (names[i].getTagNo() == 4) {
                            ASN1Primitive dobj = names[i].getName().toASN1Primitive();
                            ByteArrayOutputStream baos = null;
                            ASN1OutputStream aos = null;
                            //                        System.out.println("Inside tag 4");
                            try {
                                baos = new ByteArrayOutputStream();
                                aos = new ASN1OutputStream(baos);
                                aos.writeObject(dobj);
                                aos.flush();
                            } catch (IOException e) {
                                logger.error("Error in encoding of Authority Key Identifier." + e.getMessage());
                                return false;
                            }
                            X500Principal principal = new X500Principal(baos.toByteArray());
                            //                        System.out.println("PRINCIPAL: " + principal);
                            X500Principal issuerIssuer = issuer.getIssuerX500Principal();

                            if (issuerIssuer.equals(principal)) {
                                logger.debug("PASSED");
                                break;
                            } else {
                                logger.error(
                                        "Issuer Issuer not found among Authority Key Identifier's Certifiacte Issuers.");
                                return false;
                            }
                        }
                    }
                }
            }
        }
        logger.debug("]]]]]]]]]]]]]]]]]]]]]]]]");

        boolean keyUsage[] = issuer.getKeyUsage();
        if (!PKIUtils.isCA(issuer)) {
            if ((keyUsage != null && !keyUsage[digitalSignature]) || !PKIUtils.isProxy(issued))
                return false;
        }

        logger.debug("CHECK ISSUED PASSED");
        return true;

    }
    logger.debug("Check Issued failed.");
    return false;
}

From source file:org.jruby.ext.openssl.x509store.X509Utils.java

License:LGPL

/**
 * c: X509_check_issued//w w  w .j av  a  2s .co  m
 */
public static int checkIfIssuedBy(X509AuxCertificate issuer, X509AuxCertificate subject) throws Exception {
    if (!issuer.getSubjectX500Principal().equals(subject.getIssuerX500Principal())) {
        return V_ERR_SUBJECT_ISSUER_MISMATCH;
    }

    if (subject.getExtensionValue("2.5.29.35") != null) { //authorityKeyID
        // I hate ASN1 and DER
        Object key = get(subject.getExtensionValue("2.5.29.35"));
        if (!(key instanceof ASN1Sequence)) {
            key = get(key);
        }

        ASN1Sequence seq = (ASN1Sequence) key;
        AuthorityKeyIdentifier sakid = null;
        if (seq.size() == 1 && (seq.getObjectAt(0) instanceof ASN1OctetString)) {
            sakid = AuthorityKeyIdentifier
                    .getInstance(new DLSequence(new DERTaggedObject(0, seq.getObjectAt(0))));
        } else {
            sakid = AuthorityKeyIdentifier.getInstance(seq);
        }

        if (sakid.getKeyIdentifier() != null) {
            if (issuer.getExtensionValue("2.5.29.14") != null) {
                DEROctetString der = (DEROctetString) get(issuer.getExtensionValue("2.5.29.14"));
                if (der.getOctets().length > 20) {
                    der = (DEROctetString) get(der.getOctets());
                }
                SubjectKeyIdentifier iskid = SubjectKeyIdentifier.getInstance(der);
                if (iskid.getKeyIdentifier() != null) {
                    if (!Arrays.equals(sakid.getKeyIdentifier(), iskid.getKeyIdentifier())) {
                        return V_ERR_AKID_SKID_MISMATCH;
                    }
                }
            }
        }
        if (sakid.getAuthorityCertSerialNumber() != null
                && !sakid.getAuthorityCertSerialNumber().equals(issuer.getSerialNumber())) {
            return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
        }
        if (sakid.getAuthorityCertIssuer() != null) {
            GeneralName[] gens = sakid.getAuthorityCertIssuer().getNames();
            X500Name nm = null;
            for (int i = 0; i < gens.length; i++) {
                if (gens[i].getTagNo() == GeneralName.directoryName) {
                    ASN1Encodable nameTmp = gens[i].getName();
                    if (nameTmp instanceof X500Name) {
                        nm = (X500Name) nameTmp;
                    } else if (nameTmp instanceof ASN1Sequence) {
                        nm = X500Name.getInstance((ASN1Sequence) nameTmp);
                    } else {
                        throw new RuntimeException("unknown name type in X509Utils: " + nameTmp);
                    }
                    break;
                }
            }
            if (nm != null) {
                if (!(new Name(nm).isEqual(issuer.getIssuerX500Principal()))) {
                    return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
                }
            }
        }
    }

    if (subject.getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
        if (issuer.getKeyUsage() != null && !issuer.getKeyUsage()[0]) { // KU_DIGITAL_SIGNATURE
            return V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
        }
    } else if (issuer.getKeyUsage() != null && !issuer.getKeyUsage()[5]) { // KU_KEY_CERT_SIGN
        return V_ERR_KEYUSAGE_NO_CERTSIGN;
    }
    return V_OK;
}

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  ww  w.j  a v a 2  s.  c  om
        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");
            }
        }
    }
}

From source file:org.mailster.gui.dialogs.CertificateDialog.java

License:Open Source License

private void generateExtensionNode(TreeItem parent, X509Certificate cert, X509Extensions extensions,
        String oid) {/* www . ja v a 2 s . c om*/
    DERObjectIdentifier derOID = new DERObjectIdentifier(oid);
    X509Extension ext = extensions.getExtension(derOID);

    if (ext.getValue() == null)
        return;

    byte[] octs = ext.getValue().getOctets();
    ASN1InputStream dIn = new ASN1InputStream(octs);
    StringBuilder buf = new StringBuilder();

    try {
        if (ext.isCritical())
            buf.append(Messages.getString("MailsterSWT.dialog.certificate.criticalExt")); //$NON-NLS-1$
        else
            buf.append(Messages.getString("MailsterSWT.dialog.certificate.nonCriticalExt")); //$NON-NLS-1$

        if (derOID.equals(X509Extensions.BasicConstraints)) {
            BasicConstraints bc = new BasicConstraints((ASN1Sequence) dIn.readObject());
            if (bc.isCA())
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.isCA")); //$NON-NLS-1$
            else
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.notCA")); //$NON-NLS-1$

            buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.maxIntermediateCA")); //$NON-NLS-1$

            if (bc.getPathLenConstraint() == null || bc.getPathLenConstraint().intValue() == Integer.MAX_VALUE)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.BasicConstraints.unlimited")); //$NON-NLS-1$
            else
                buf.append(bc.getPathLenConstraint()).append('\n');

            generateNode(parent, Messages.getString(oid), buf);
        } else if (derOID.equals(X509Extensions.KeyUsage)) {
            KeyUsage us = new KeyUsage((DERBitString) dIn.readObject());
            if ((us.intValue() & KeyUsage.digitalSignature) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.digitalSignature")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.nonRepudiation) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.nonRepudiation")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.keyEncipherment) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyEncipherment")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.dataEncipherment) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.dataEncipherment")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.keyAgreement) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyAgreement")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.keyCertSign) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.keyCertSign")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.cRLSign) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.cRLSign")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.encipherOnly) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.encipherOnly")); //$NON-NLS-1$
            if ((us.intValue() & KeyUsage.decipherOnly) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.KeyUsage.decipherOnly")); //$NON-NLS-1$

            generateNode(parent, Messages.getString(oid), buf);
        } else if (derOID.equals(X509Extensions.SubjectKeyIdentifier)) {
            SubjectKeyIdentifier id = new SubjectKeyIdentifier((DEROctetString) dIn.readObject());
            generateNode(parent, Messages.getString(oid),
                    buf.toString() + CertificateUtilities.byteArrayToString(id.getKeyIdentifier()));
        } else if (derOID.equals(X509Extensions.AuthorityKeyIdentifier)) {
            AuthorityKeyIdentifier id = new AuthorityKeyIdentifier((ASN1Sequence) dIn.readObject());
            generateNode(parent, Messages.getString(oid), buf.toString() + id.getAuthorityCertSerialNumber());
        } else if (derOID.equals(MiscObjectIdentifiers.netscapeRevocationURL)) {
            buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append("\n");
            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(MiscObjectIdentifiers.verisignCzagExtension)) {
            buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append("\n");
            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(X509Extensions.CRLNumber)) {
            buf.append((DERInteger) dIn.readObject()).append("\n");
            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(X509Extensions.ReasonCode)) {
            ReasonFlags rf = new ReasonFlags((DERBitString) dIn.readObject());

            if ((rf.intValue() & ReasonFlags.unused) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.unused")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.keyCompromise) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.keyCompromise")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.cACompromise) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.cACompromise")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.affiliationChanged) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.affiliationChanged")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.superseded) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.superseded")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.cessationOfOperation) > 0)
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.cessationOfOperation")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.certificateHold) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.certificateHold")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.privilegeWithdrawn) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.privilegeWithdrawn")); //$NON-NLS-1$
            if ((rf.intValue() & ReasonFlags.aACompromise) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.ReasonCode.aACompromise")); //$NON-NLS-1$
            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(MiscObjectIdentifiers.netscapeCertType)) {
            NetscapeCertType type = new NetscapeCertType((DERBitString) dIn.readObject());

            if ((type.intValue() & NetscapeCertType.sslClient) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslClient")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.sslServer) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslServer")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.smime) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.smime")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.objectSigning) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.objectSigning")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.reserved) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.reserved")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.sslCA) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.sslCA")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.smimeCA) > 0)
                buf.append(Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.smimeCA")); //$NON-NLS-1$
            if ((type.intValue() & NetscapeCertType.objectSigningCA) > 0)
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.NetscapeCertType.objectSigningCA")); //$NON-NLS-1$

            generateNode(parent, Messages.getString(oid), buf.toString());
        } else if (derOID.equals(X509Extensions.ExtendedKeyUsage)) {
            ExtendedKeyUsage eku = new ExtendedKeyUsage((ASN1Sequence) dIn.readObject());
            if (eku.hasKeyPurposeId(KeyPurposeId.anyExtendedKeyUsage))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.anyExtendedKeyUsage")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth))
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_clientAuth")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_codeSigning))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_codeSigning")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_emailProtection))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_emailProtection")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecEndSystem))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecEndSystem")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecTunnel))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecTunnel")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_ipsecUser))
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_ipsecUser")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_OCSPSigning))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_OCSPSigning")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth))
                buf.append(
                        Messages.getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_serverAuth")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_smartcardlogon))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_smartcardlogon")); //$NON-NLS-1$
            if (eku.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping))
                buf.append(Messages
                        .getString("MailsterSWT.dialog.certificate.ExtendedKeyUsage.id_kp_timeStamping")); //$NON-NLS-1$

            generateNode(parent, Messages.getString(oid), buf.toString());
        } else
            generateNode(parent,
                    MessageFormat.format(Messages.getString("MailsterSWT.dialog.certificate.objectIdentifier"), //$NON-NLS-1$ 
                            new Object[] { oid.replace('.', ' ') }),
                    CertificateUtilities.byteArrayToString((cert.getExtensionValue(oid))));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}