Example usage for java.security.cert X509Certificate getPublicKey

List of usage examples for java.security.cert X509Certificate getPublicKey

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getPublicKey.

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

private X509Certificate createIntermediateCertificate(PrivateKey caPrivKey, X509Certificate caCert,
        Date startDate, KeyPair keyPair) throws Exception {
    X500Name issuerDn = JcaX500NameUtil.getSubject(caCert);

    X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    subjectBuilder.addRDN(BCStyle.OU, INTERMEDIATE_CERT_OU);
    subjectBuilder.addRDN(BCStyle.EmailAddress, CERT_EMAIL);
    X500Name subjectDn = subjectBuilder.build();

    X509CertificateGenerator.V3X509CertificateGenerator v3CertGen = new V3X509CertificateGenerator(startDate,
            issuerDn, subjectDn, keyPair.getPublic(), serialNumber());

    // extensions
    v3CertGen.addSubjectKeyIdExtension(keyPair.getPublic());
    v3CertGen.addAuthorityKeyIdExtension(caCert);
    v3CertGen.addBasicConstraintsExtension();

    X509Certificate cert = v3CertGen.generate(caPrivKey);

    Date now = new Date();
    cert.checkValidity(now);/*from ww  w  .j  a  va2  s .co  m*/
    cert.verify(caCert.getPublicKey());

    PKCS12BagAttributeSetter.usingBagAttributeCarrier(cert).setFriendlyName(INTERMEDIATE_CERT_OU);

    PKCS12BagAttributeSetter.usingBagAttributeCarrier(keyPair.getPrivate()).setFriendlyName(FRIENDLY_NAME)
            .setLocalKeyId(keyPair.getPublic());

    return cert;
}

From source file:cybervillains.ca.KeyStoreManager.java

/**
 * This method returns the duplicated certificate mapped to the passed in cert, or
 * creates and returns one if no mapping has yet been performed.  If a naked public
 * key has already been mapped that matches the key in the cert, the already mapped
 * keypair will be reused for the mapped cert.
 * @param cert//from   w  w  w  .ja v  a 2 s. c o m
 * @return
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws CertificateException
 * @throws CertificateNotYetValidException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)
        throws CertificateEncodingException, InvalidKeyException, CertificateException,
        CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        KeyStoreException, UnrecoverableKeyException {

    String thumbprint = ThumbprintUtil.getThumbprint(cert);

    String mappedCertThumbprint = _certMap.get(thumbprint);

    if (mappedCertThumbprint == null) {

        // Check if we've already mapped this public key from a KeyValue
        PublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());
        PrivateKey privKey;

        if (mappedPk == null) {
            PublicKey pk = cert.getPublicKey();

            String algo = pk.getAlgorithm();

            KeyPair kp;

            if (algo.equals("RSA")) {
                kp = getRSAKeyPair();
            } else if (algo.equals("DSA")) {
                kp = getDSAKeyPair();
            } else {
                throw new InvalidKeyException("Key algorithm " + algo + " not supported.");
            }
            mappedPk = kp.getPublic();
            privKey = kp.getPrivate();

            mapPublicKeys(cert.getPublicKey(), mappedPk);
        } else {
            privKey = getPrivateKey(mappedPk);
        }

        X509Certificate replacementCert = CertificateCreator.mitmDuplicateCertificate(cert, mappedPk,
                getSigningCert(), getSigningPrivateKey());

        addCertAndPrivateKey(null, replacementCert, privKey);

        mappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);

        _certMap.put(thumbprint, mappedCertThumbprint);
        _certMap.put(mappedCertThumbprint, thumbprint);
        _subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);

        if (persistImmediately) {
            persist();
        }
        return replacementCert;
    }
    return getCertificateByAlias(mappedCertThumbprint);

}

From source file:be.fedict.trust.service.bean.DownloaderMDB.java

private void processColdStartMessage(ColdStartMessage coldStartMessage) {
    if (null == coldStartMessage) {
        return;// w  w  w.  j a v  a 2s.  c om
    }

    String crlUrl = coldStartMessage.getCrlUrl();
    String certUrl = coldStartMessage.getCertUrl();
    LOG.debug("cold start CRL URL: " + crlUrl);
    LOG.debug("cold start CA URL: " + certUrl);

    File crlFile = download(crlUrl);
    File certFile = download(certUrl);

    // parsing
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        LOG.debug("certificate factory error: " + e.getMessage(), e);
        crlFile.delete();
        certFile.delete();
        return;
    }

    X509Certificate certificate = null;
    try {
        certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certFile));
    } catch (Exception e) {
        LOG.debug("error DER-parsing certificate");
        try {
            PEMReader pemReader = new PEMReader(new FileReader(certFile));
            certificate = (X509Certificate) pemReader.readObject();
            pemReader.close();
        } catch (Exception e2) {
            retry("error PEM-parsing certificate", e, certFile, crlFile);
        }
    }
    certFile.delete();

    X509CRL crl = null;
    try {
        crl = (X509CRL) certificateFactory.generateCRL(new FileInputStream(crlFile));
    } catch (Exception e) {
        retry("error parsing CRL", e, crlFile);
    }

    // first check whether the two correspond
    try {
        crl.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.error("no correspondence between CRL and CA");
        LOG.error("CRL issuer: " + crl.getIssuerX500Principal());
        LOG.debug("CA subject: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }
    LOG.debug("CRL matches CA: " + certificate.getSubjectX500Principal());

    // skip expired CAs
    Date now = new Date();
    Date notAfter = certificate.getNotAfter();
    if (now.after(notAfter)) {
        LOG.warn("CA already expired: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    // create database entitities
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(certificate);
    if (null != certificateAuthority) {
        LOG.debug("CA already in cache: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    /*
     * Lookup Root CA's trust point via parent certificates' CA entity.
     */
    LOG.debug(
            "Lookup Root CA's trust point via parent certificates' CA entity - Don't have Issuer's Serial Number??");
    String parentIssuerName = certificate.getIssuerX500Principal().toString();
    CertificateAuthorityEntity parentCertificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(parentIssuerName);
    if (null == parentCertificateAuthority) {
        LOG.error("CA not found for " + parentIssuerName + " ?!");
        crlFile.delete();
        return;
    }
    LOG.debug("parent CA: " + parentCertificateAuthority.getName());
    TrustPointEntity parentTrustPoint = parentCertificateAuthority.getTrustPoint();
    if (null != parentTrustPoint) {
        LOG.debug("trust point parent: " + parentTrustPoint.getName());
        LOG.debug("previous trust point fire data: " + parentTrustPoint.getFireDate());
    } else {
        LOG.debug("no parent trust point");
    }

    // create new CA
    certificateAuthority = this.certificateAuthorityDAO.addCertificateAuthority(certificate, crlUrl);

    // prepare harvesting
    certificateAuthority.setTrustPoint(parentTrustPoint);
    certificateAuthority.setStatus(Status.PROCESSING);
    if (null != certificateAuthority.getTrustPoint()
            && null == certificateAuthority.getTrustPoint().getFireDate()) {
        try {
            this.schedulingService.startTimer(certificateAuthority.getTrustPoint());
        } catch (InvalidCronExpressionException e) {
            LOG.error("invalid cron expression");
            crlFile.delete();
            return;
        }
    }

    // notify harvester
    String crlFilePath = crlFile.getAbsolutePath();
    try {
        this.notificationService.notifyHarvester(certificate.getSubjectX500Principal().toString(), crlFilePath,
                false);
    } catch (JMSException e) {
        crlFile.delete();
        throw new RuntimeException(e);
    }
}

From source file:android.net.http.CertificateChainValidator.java

/**
 * Performs the handshake and server certificates validation
 * @param sslSocket The secure connection socket
 * @param domain The website domain/*from  w w w  . j  a v a 2s  .  c om*/
 * @return An SSL error object if there is an error and null otherwise
 */
public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket,
        String domain) throws SSLHandshakeException, IOException {

    ++sTotal;

    SSLContext sslContext = HttpsConnection.getContext();
    if (sslContext == null) {
        closeSocketThrowException(sslSocket, "SSL context is null");
    }

    X509Certificate[] serverCertificates = null;

    long sessionBeforeHandshakeLastAccessedTime = 0;
    byte[] sessionBeforeHandshakeId = null;

    SSLSession sessionAfterHandshake = null;

    synchronized (sslContext) {
        // get SSL session before the handshake
        SSLSession sessionBeforeHandshake = getSSLSession(sslContext, connection.getHost());
        if (sessionBeforeHandshake != null) {
            sessionBeforeHandshakeLastAccessedTime = sessionBeforeHandshake.getLastAccessedTime();

            sessionBeforeHandshakeId = sessionBeforeHandshake.getId();
        }

        // start handshake, close the socket if we fail
        try {
            sslSocket.setUseClientMode(true);
            sslSocket.startHandshake();
        } catch (IOException e) {
            closeSocketThrowException(sslSocket, e.getMessage(), "failed to perform SSL handshake");
        }

        // retrieve the chain of the server peer certificates
        Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates();

        if (peerCertificates == null || peerCertificates.length <= 0) {
            closeSocketThrowException(sslSocket, "failed to retrieve peer certificates");
        } else {
            serverCertificates = new X509Certificate[peerCertificates.length];
            for (int i = 0; i < peerCertificates.length; ++i) {
                serverCertificates[i] = (X509Certificate) (peerCertificates[i]);
            }

            // update the SSL certificate associated with the connection
            if (connection != null) {
                if (serverCertificates[0] != null) {
                    connection.setCertificate(new SslCertificate(serverCertificates[0]));
                }
            }
        }

        // get SSL session after the handshake
        sessionAfterHandshake = getSSLSession(sslContext, connection.getHost());
    }

    if (sessionBeforeHandshakeLastAccessedTime != 0 && sessionAfterHandshake != null
            && Arrays.equals(sessionBeforeHandshakeId, sessionAfterHandshake.getId())
            && sessionBeforeHandshakeLastAccessedTime < sessionAfterHandshake.getLastAccessedTime()) {

        if (HttpLog.LOGV) {
            HttpLog.v("SSL session was reused: total reused: " + sTotalReused + " out of total of: " + sTotal);

            ++sTotalReused;
        }

        // no errors!!!
        return null;
    }

    // check if the first certificate in the chain is for this site
    X509Certificate currCertificate = serverCertificates[0];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "certificate for this site is null");
    } else {
        if (!DomainNameChecker.match(currCertificate, domain)) {
            String errorMessage = "certificate not for this host: " + domain;

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            sslSocket.getSession().invalidate();
            return new SslError(SslError.SSL_IDMISMATCH, currCertificate);
        }
    }

    //
    // first, we validate the chain using the standard validation
    // solution; if we do not find any errors, we are done; if we
    // fail the standard validation, we re-validate again below,
    // this time trying to retrieve any individual errors we can
    // report back to the user.
    //
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(serverCertificates, "RSA");

            // no errors!!!
            return null;
        }
    } catch (CertificateException e) {
        if (HttpLog.LOGV) {
            HttpLog.v("failed to pre-validate the certificate chain, error: " + e.getMessage());
        }
    }

    sslSocket.getSession().invalidate();

    SslError error = null;

    // we check the root certificate separately from the rest of the
    // chain; this is because we need to know what certificate in
    // the chain resulted in an error if any
    currCertificate = serverCertificates[serverCertificates.length - 1];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "root certificate is null");
    }

    // check if the last certificate in the chain (root) is trusted
    X509Certificate[] rootCertificateChain = { currCertificate };
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(rootCertificateChain, "RSA");
        }
    } catch (CertificateExpiredException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate has expired";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_EXPIRED, currCertificate);
    } catch (CertificateNotYetValidException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not valid yet";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
    } catch (CertificateException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not trusted";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
    }

    // Then go through the certificate chain checking that each
    // certificate trusts the next and that each certificate is
    // within its valid date range. Walk the chain in the order
    // from the CA to the end-user
    X509Certificate prevCertificate = serverCertificates[serverCertificates.length - 1];

    for (int i = serverCertificates.length - 2; i >= 0; --i) {
        currCertificate = serverCertificates[i];

        // if a certificate is null, we cannot verify the chain
        if (currCertificate == null) {
            closeSocketThrowException(sslSocket, "null certificate in the chain");
        }

        // verify if trusted by chain
        if (!prevCertificate.getSubjectDN().equals(currCertificate.getIssuerDN())) {
            String errorMessage = "not trusted by chain";

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        try {
            currCertificate.verify(prevCertificate.getPublicKey());
        } catch (GeneralSecurityException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "not trusted by chain";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        // verify if the dates are valid
        try {
            currCertificate.checkValidity();
        } catch (CertificateExpiredException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate expired";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_EXPIRED) {
                error = new SslError(SslError.SSL_EXPIRED, currCertificate);
            }
        } catch (CertificateNotYetValidException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate not valid yet";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_NOTYETVALID) {
                error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
            }
        }

        prevCertificate = currCertificate;
    }

    // if we do not have an error to report back to the user, throw
    // an exception (a generic error will be reported instead)
    if (error == null) {
        closeSocketThrowException(sslSocket,
                "failed to pre-validate the certificate chain due to a non-standard error");
    }

    return error;
}

From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java

@Test
public void handleRenewCertificateInstruction() throws Exception {
    SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, "localhost", 80, false, TEST_PW_VALUE);
    expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce();
    replayAll();/*from  ww  w. j av  a 2  s  .  com*/
    keystoreService.saveCACertificate(CA_CERT);
    keystoreService.generateNodeSelfSignedCertificate(TEST_DN);
    String csr = keystoreService.generateNodePKCS10CertificateRequestString();

    X509Certificate originalCert;

    PemReader pemReader = new PemReader(new StringReader(csr));
    try {
        PemObject pem = pemReader.readPemObject();
        PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent());
        originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate());
        String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert });
        keystoreService.saveNodeSignedCertificate(signedPem);

        log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem);

        assertThat("Generated CSR", csr, notNullValue());
    } finally {
        pemReader.close();
    }

    // now let's renew!
    KeyStore keyStore = loadKeyStore();
    PrivateKey nodeKey = (PrivateKey) keyStore.getKey("node", TEST_PW_VALUE.toCharArray());
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSA");
    ContentSigner signer = signerBuilder.build(nodeKey);
    PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(
            JcaX500NameUtil.getSubject(originalCert),
            SubjectPublicKeyInfo.getInstance(originalCert.getPublicKey().getEncoded()));
    X509Certificate renewedCert = PKITestUtils.sign(builder.build(signer), CA_CERT, CA_KEY_PAIR.getPrivate());
    String renewedSignedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { renewedCert });

    BasicInstruction instr = new BasicInstruction(DefaultSetupService.INSTRUCTION_TOPIC_RENEW_CERTIFICATE,
            new Date(), "123", "456", new BasicInstructionStatus(456L, InstructionState.Received, new Date()));
    for (int i = 0; i < renewedSignedPem.length(); i += 256) {
        int end = i + (i + 256 < renewedSignedPem.length() ? 256 : renewedSignedPem.length() - i);
        instr.addParameter(DefaultSetupService.INSTRUCTION_PARAM_CERTIFICATE,
                renewedSignedPem.substring(i, end));
    }

    InstructionState state = service.processInstruction(instr);
    assertThat("Instruction state", state, equalTo(InstructionState.Completed));

    X509Certificate nodeCert = keystoreService.getNodeCertificate();
    assertThat("Node cert is now renewed cert", nodeCert, equalTo(renewedCert));
}

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * Verifica si una firma XML embedida es v&aacute;lida seg&uacute;n define
 * el est&aacute;ndar XML Signature (<a
 * href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core
 * Validation</a>), y si el certificado era v&aacute;lido en la fecha dada.
 * <p>//from   w ww.  j ava 2s .  c  om
 * 
 * Esta rutina <b>NO</b> verifica si el certificado embedido en
 * &lt;KeyInfo&gt; es v&aacute;lido (eso debe verificarlo con la autoridad
 * certificadora que emiti&oacute; el certificado), pero si verifica que la
 * llave utilizada para verificar corresponde a la contenida en el
 * certificado.
 * 
 * @param xml
 *            el nodo &lt;Signature&gt;
 * @param date
 *            una fecha en la que se verifica la validez del certificado
 * @return el resultado de la verificaci&oacute;n
 * 
 * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext)
 * @see cl.nic.dte.VerifyResult
 * @see cl.nic.dte.extension.DTEDefTypeExtensionHandler
 * @see #getCertificate(XMLSignature)
 */
@SuppressWarnings("unchecked")
public static VerifyResult verifySignature(XMLSignature signature, DOMValidateContext valContext) {

    try {

        KeyValueKeySelector ksel = (KeyValueKeySelector) valContext.getKeySelector();
        X509Certificate x509 = getCertificate(signature);

        // Verifica que un certificado bien embedido
        if (x509 == null) {
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                    Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NO509")));
        }

        // Validate the XMLSignature
        boolean coreValidity = signature.validate(valContext);

        // Check core validation status
        if (coreValidity == false) {
            boolean sv = signature.getSignatureValue().validate(valContext);
            if (!sv)
                return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                        Utilities.verificationLabels.getString("XML_SIGNATURE_BAD_VALUE"));

            // check the validation status of each Reference
            String message = "";

            for (Reference ref : (List<Reference>) signature.getSignedInfo().getReferences()) {
                if (!ref.validate(valContext)) {
                    message += Utilities.verificationLabels.getString("XML_SIGNATURE_BAD_REFERENCE");
                    message = message.replaceAll("%1",
                            new String(Base64.encodeBase64(ref.getCalculatedDigestValue())));
                    message = message.replaceAll("%2", new String(Base64.encodeBase64(ref.getDigestValue())));
                    message += "\n";
                }
            }
            return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message);
        }

        // Verifica que la llave del certificado corresponde a la usada para
        // la firma
        if (!ksel.getPk().equals(x509.getPublicKey())) {
            String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_BADKEY");
            return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message));
        }

        return new VerifyResult(VerifyResult.XML_SIGNATURE_OK, true, null);
    } catch (XMLSignatureException e) {
        return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false,
                Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNKNOWN") + ": " + e.getMessage()));
    }

}

From source file:eu.europa.ec.markt.dss.report.Tsl2PdfExporter.java

/**
 * Produce a human readable export of the given tsl to the given file.
 * //from w  w  w . ja v  a  2 s .  co  m
 * @param tsl
 *            the TrustServiceList to export
 * @param pdfFile
 *            the file to generate
 * @return
 * @throws IOException
 */
public void humanReadableExport(final TrustServiceList tsl, final File pdfFile) {
    Document document = new Document();
    OutputStream outputStream;
    try {
        outputStream = new FileOutputStream(pdfFile);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("file not found: " + pdfFile.getAbsolutePath(), e);
    }
    try {
        final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
        pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);

        // title
        final EUCountry country = EUCountry.valueOf(tsl.getSchemeTerritory());
        final String title = country.getShortSrcLangName() + " (" + country.getShortEnglishName()
                + "): Trusted List";

        Phrase footerPhrase = new Phrase("PDF document generated on " + new Date().toString() + ", page ",
                headerFooterFont);
        HeaderFooter footer = new HeaderFooter(footerPhrase, true);
        document.setFooter(footer);

        Phrase headerPhrase = new Phrase(title, headerFooterFont);
        HeaderFooter header = new HeaderFooter(headerPhrase, false);
        document.setHeader(header);

        document.open();
        addTitle(title, title0Font, Paragraph.ALIGN_CENTER, 0, 20, document);

        addLongItem("Scheme name", tsl.getSchemeName(), document);
        addLongItem("Legal Notice", tsl.getLegalNotice(), document);

        // information table
        PdfPTable informationTable = createInfoTable();
        addItemRow("Scheme territory", tsl.getSchemeTerritory(), informationTable);
        addItemRow("Scheme status determination approach",
                substringAfter(tsl.getStatusDeterminationApproach(), "StatusDetn/"), informationTable);

        final List<String> schemeTypes = new ArrayList<String>();
        for (final String schemeType : tsl.getSchemeTypes()) {
            schemeTypes.add(schemeType);
        }
        addItemRow("Scheme type community rules", schemeTypes, informationTable);

        addItemRow("Issue date", tsl.getListIssueDateTime().toString(), informationTable);
        addItemRow("Next update", tsl.getNextUpdate().toString(), informationTable);
        addItemRow("Historical information period", tsl.getHistoricalInformationPeriod().toString() + " days",
                informationTable);
        addItemRow("Sequence number", tsl.getSequenceNumber().toString(), informationTable);
        addItemRow("Scheme information URIs", tsl.getSchemeInformationUris(), informationTable);

        document.add(informationTable);

        addTitle("Scheme Operator", title1Font, Paragraph.ALIGN_CENTER, 0, 10, document);

        informationTable = createInfoTable();
        addItemRow("Scheme operator name", tsl.getSchemeOperatorName(), informationTable);
        PostalAddressType schemeOperatorPostalAddress = tsl.getSchemeOperatorPostalAddress(Locale.ENGLISH);
        addItemRow("Scheme operator street address", schemeOperatorPostalAddress.getStreetAddress(),
                informationTable);
        addItemRow("Scheme operator postal code", schemeOperatorPostalAddress.getPostalCode(),
                informationTable);
        addItemRow("Scheme operator locality", schemeOperatorPostalAddress.getLocality(), informationTable);
        addItemRow("Scheme operator state", schemeOperatorPostalAddress.getStateOrProvince(), informationTable);
        addItemRow("Scheme operator country", schemeOperatorPostalAddress.getCountryName(), informationTable);

        List<String> schemeOperatorElectronicAddressess = tsl.getSchemeOperatorElectronicAddresses();
        addItemRow("Scheme operator contact", schemeOperatorElectronicAddressess, informationTable);
        document.add(informationTable);

        addTitle("Trust Service Providers", title1Font, Paragraph.ALIGN_CENTER, 10, 2, document);

        List<TrustServiceProvider> trustServiceProviders = tsl.getTrustServiceProviders();
        for (TrustServiceProvider trustServiceProvider : trustServiceProviders) {
            addTitle(trustServiceProvider.getName(), title1Font, Paragraph.ALIGN_LEFT, 10, 2, document);

            PdfPTable providerTable = createInfoTable();
            addItemRow("Service provider trade name", trustServiceProvider.getTradeName(), providerTable);
            addItemRow("Information URI", trustServiceProvider.getInformationUris(), providerTable);
            PostalAddressType postalAddress = trustServiceProvider.getPostalAddress();
            addItemRow("Service provider street address", postalAddress.getStreetAddress(), providerTable);
            addItemRow("Service provider postal code", postalAddress.getPostalCode(), providerTable);
            addItemRow("Service provider locality", postalAddress.getLocality(), providerTable);
            addItemRow("Service provider state", postalAddress.getStateOrProvince(), providerTable);
            addItemRow("Service provider country", postalAddress.getCountryName(), providerTable);
            document.add(providerTable);

            List<TrustService> trustServices = trustServiceProvider.getTrustServices();
            for (TrustService trustService : trustServices) {
                addTitle(trustService.getName(), title2Font, Paragraph.ALIGN_LEFT, 10, 2, document);
                PdfPTable serviceTable = createInfoTable();
                addItemRow("Type", substringAfter(trustService.getType(), "Svctype/"), serviceTable);
                addItemRow("Status", substringAfter(trustService.getStatus(), "Svcstatus/"), serviceTable);
                addItemRow("Status starting time", trustService.getStatusStartingTime().toString(),
                        serviceTable);
                document.add(serviceTable);

                addTitle("Service digital identity (X509)", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                final X509Certificate certificate = trustService.getServiceDigitalIdentity();
                final PdfPTable serviceIdentityTable = createInfoTable();
                addItemRow("Version", Integer.toString(certificate.getVersion()), serviceIdentityTable);
                addItemRow("Serial number", certificate.getSerialNumber().toString(), serviceIdentityTable);
                addItemRow("Signature algorithm", certificate.getSigAlgName(), serviceIdentityTable);
                addItemRow("Issuer", certificate.getIssuerX500Principal().toString(), serviceIdentityTable);
                addItemRow("Valid from", certificate.getNotBefore().toString(), serviceIdentityTable);
                addItemRow("Valid to", certificate.getNotAfter().toString(), serviceIdentityTable);
                addItemRow("Subject", certificate.getSubjectX500Principal().toString(), serviceIdentityTable);
                addItemRow("Public key", certificate.getPublicKey().toString(), serviceIdentityTable);
                // TODO certificate policies
                addItemRow("Subject key identifier", toHex(getSKId(certificate)), serviceIdentityTable);
                addItemRow("CRL distribution points", getCrlDistributionPoints(certificate),
                        serviceIdentityTable);
                addItemRow("Authority key identifier", toHex(getAKId(certificate)), serviceIdentityTable);
                addItemRow("Key usage", getKeyUsage(certificate), serviceIdentityTable);
                addItemRow("Basic constraints", getBasicConstraints(certificate), serviceIdentityTable);

                byte[] encodedCertificate;
                try {
                    encodedCertificate = certificate.getEncoded();
                } catch (CertificateEncodingException e) {
                    throw new RuntimeException("cert: " + e.getMessage(), e);
                }
                addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedCertificate), serviceIdentityTable);
                addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedCertificate),
                        serviceIdentityTable);
                document.add(serviceIdentityTable);

                List<ExtensionType> extensions = trustService.getExtensions();
                for (ExtensionType extension : extensions) {
                    printExtension(extension, document);
                }

                addLongMonoItem("The decoded certificate:", certificate.toString(), document);
                addLongMonoItem("The certificate in PEM format:", toPem(certificate), document);
            }
        }

        X509Certificate signerCertificate = tsl.verifySignature();
        if (null != signerCertificate) {
            Paragraph tslSignerTitle = new Paragraph("Trusted List Signer", title1Font);
            tslSignerTitle.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(tslSignerTitle);

            final PdfPTable signerTable = createInfoTable();
            addItemRow("Subject", signerCertificate.getSubjectX500Principal().toString(), signerTable);
            addItemRow("Issuer", signerCertificate.getIssuerX500Principal().toString(), signerTable);
            addItemRow("Not before", signerCertificate.getNotBefore().toString(), signerTable);
            addItemRow("Not after", signerCertificate.getNotAfter().toString(), signerTable);
            addItemRow("Serial number", signerCertificate.getSerialNumber().toString(), signerTable);
            addItemRow("Version", Integer.toString(signerCertificate.getVersion()), signerTable);
            byte[] encodedPublicKey = signerCertificate.getPublicKey().getEncoded();
            addItemRow("Public key SHA1 Thumbprint", DigestUtils.shaHex(encodedPublicKey), signerTable);
            addItemRow("Public key SHA256 Thumbprint", DigestUtils.sha256Hex(encodedPublicKey), signerTable);
            document.add(signerTable);

            addLongMonoItem("The decoded certificate:", signerCertificate.toString(), document);
            addLongMonoItem("The certificate in PEM format:", toPem(signerCertificate), document);
            addLongMonoItem("The public key in PEM format:", toPem(signerCertificate.getPublicKey()), document);
        }

        document.close();
    } catch (DocumentException e) {
        throw new RuntimeException("PDF document error: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException("Exception: " + e.getMessage(), e);
    }
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String action = (String) request.getAttribute(IDP.ACTION_NAME);

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
    if (holder == null) {
        throw new ServletException("Holder is null");
    }/*  w  w w.  ja v a2  s  .  c o m*/

    AuthController ac = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL));

    if (action.equalsIgnoreCase(".well-known/openid-configuration")) {

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(new OpenIDConnectConfig(this.idpName, request, mapper));
        response.setContentType("application/json");
        response.getWriter().print(json);

        AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), (HttpServletRequest) request, ac.getAuthInfo(),
                "NONE");

        return;

    } else if (action.equalsIgnoreCase("certs")) {
        try {
            X509Certificate cert = GlobalEntries.getGlobalEntries().getConfigManager()
                    .getCertificate(this.jwtSigningKeyName);
            JsonWebKey jwk = JsonWebKey.Factory.newJwk(cert.getPublicKey());

            String keyID = buildKID(cert);
            jwk.setKeyId(keyID);
            jwk.setUse("sig");
            jwk.setAlgorithm("RS256");
            response.setContentType("application/json");
            response.getWriter().print(new JsonWebKeySet(jwk).toJson());

            AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), (HttpServletRequest) request,
                    ac.getAuthInfo(), "NONE");

            return;
        } catch (JoseException e) {
            throw new ServletException("Could not generate jwt", e);
        }
    } else if (action.equalsIgnoreCase("auth")) {
        String clientID = request.getParameter("client_id");
        String responseCode = request.getParameter("response_type");
        String scope = request.getParameter("scope");
        String redirectURI = request.getParameter("redirect_uri");
        String state = request.getParameter("state");
        String nonce = request.getParameter("nonce");

        OpenIDConnectTransaction transaction = new OpenIDConnectTransaction();
        transaction.setClientID(clientID);
        transaction.setResponseCode(responseCode);
        transaction.setNonce(nonce);

        StringTokenizer toker = new StringTokenizer(scope, " ", false);
        while (toker.hasMoreTokens()) {
            String token = toker.nextToken();
            transaction.getScope().add(token);
        }

        transaction.setRedirectURI(redirectURI);
        transaction.setState(state);

        OpenIDConnectTrust trust = trusts.get(clientID);

        if (trust == null) {
            StringBuffer b = new StringBuffer();
            b.append(redirectURI).append("?error=unauthorized_client");
            logger.warn("Trust '" + clientID + "' not found");
            response.sendRedirect(b.toString());
            return;
        }

        if (trust.isVerifyRedirect()) {

            if (!trust.getRedirectURI().equals(redirectURI)) {
                StringBuffer b = new StringBuffer();
                b.append(trust.getRedirectURI()).append("?error=unauthorized_client");
                logger.warn("Invalid redirect");

                AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request,
                        ac.getAuthInfo(), "NONE");

                response.sendRedirect(b.toString());
                return;
            }

            transaction.setRedirectURI(trust.getRedirectURI());

        } else {
            transaction.setRedirectURI(redirectURI);
        }

        if (transaction.getScope().size() == 0 || !transaction.getScope().get(0).equals("openid")) {
            StringBuffer b = new StringBuffer();
            b.append(transaction.getRedirectURI()).append("?error=invalid_scope");
            logger.warn("First scope not openid");
            AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, ac.getAuthInfo(),
                    "NONE");
            response.sendRedirect(b.toString());
            return;
        } else {
            //we don't need the openid scope anymore
            transaction.getScope().remove(0);
        }

        String authChain = trust.getAuthChain();

        if (authChain == null) {
            StringBuffer b = new StringBuffer();
            b.append("IdP does not have an authenticaiton chain configured");
            throw new ServletException(b.toString());
        }

        HttpSession session = request.getSession();

        AuthInfo authData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();

        AuthChainType act = holder.getConfig().getAuthChains().get(authChain);

        session.setAttribute(OpenIDConnectIdP.TRANSACTION_DATA, transaction);

        if (authData == null || !authData.isAuthComplete() && !(authData.getAuthLevel() < act.getLevel())) {
            nextAuth(request, response, session, false, act);
        } else {
            if (authData.getAuthLevel() < act.getLevel()) {
                //step up authentication, clear existing auth data

                session.removeAttribute(ProxyConstants.AUTH_CTL);
                holder.getConfig().createAnonUser(session);

                nextAuth(request, response, session, false, act);
            } else {

                StringBuffer b = genFinalURL(request);
                response.sendRedirect(b.toString());

                //TODO if session already exists extend the life of the id_token

            }
        }

    } else if (action.contentEquals("completefed")) {
        this.completeFederation(request, response);
    } else if (action.equalsIgnoreCase("userinfo")) {
        try {
            processUserInfoRequest(request, response);
        } catch (JoseException | InvalidJwtException e) {
            throw new ServletException("Could not process userinfo request", e);
        }

    }

}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

@Override
public RevocationResult getRevocationStatus(CertPath certPath, TrustAnchor trustAnchor, Date now)
        throws CRLException {
    Check.notNull(certPath, "certPath");
    Check.notNull(trustAnchor, "trustAnchor");

    List<? extends Certificate> certificates = certPath.getCertificates();

    RevocationResult revocationResult = new RevocationResultImpl(certificates.size());

    /* /* w  w w. ja va  2s .c  o m*/
     * Step through all the certificates in the path and check the revocation status of all
     * the certificates in the path.
     */
    for (int i = 0; i < certificates.size(); i++) {
        X509Certificate certificate = toX509Certificate(certificates.get(i));

        PublicKey issuerPublicKey;
        X500Principal issuer;
        X509Certificate issuerCertificate;

        /*
         * we need to get the issuer of the current certificate
         * check if there is a next certificate in the path or that we must use the TrustAnchor
         */
        if ((i + 1) == certificates.size()) {
            /* this was the last entry from the path so we must use the trust anchor */
            if (trustAnchor.getTrustedCert() != null) {
                issuerCertificate = toX509Certificate(trustAnchor.getTrustedCert());
                issuerPublicKey = issuerCertificate.getPublicKey();
                issuer = issuerCertificate.getSubjectX500Principal();
            } else {
                /* the TrustAnchor does not contain a certificate but only an issuer and public key */
                issuerCertificate = null;
                issuerPublicKey = trustAnchor.getCAPublicKey();
                issuer = trustAnchor.getCA();
            }
        } else {
            /* get next entry from path ie. the issuer of the current certificate */
            issuerCertificate = toX509Certificate(certificates.get(i + 1));
            issuerPublicKey = issuerCertificate.getPublicKey();
            issuer = issuerCertificate.getSubjectX500Principal();
        }

        /*
         * sanity check to make sure the CertPath is ordered from end -> final CA
         * ie that the next certificate signed the previous certificate
         */
        verifyCertificate(certificate, issuerPublicKey);

        /* 
         * Sanity check. The issuer principal field of the certificate currently checked should 
         * normally be equal to the issuer principal.
         */
        if (!certificate.getIssuerX500Principal().equals(issuer)) {
            logger.warn("Certificate issuer field is not equal to issuer.");
        }

        if (issuerCertificate != null) {
            Set<KeyUsageType> keyUsage = X509CertificateInspector.getKeyUsage(issuerCertificate);

            /* 
             * check if issuer is allowed to issue CRLs (only when we have an issuerCertificate, and
             * a key usage extension) 
             */
            if (keyUsage != null && !keyUsage.contains(KeyUsageType.CRLSIGN)) {
                logger.debug("Issuer is not allowed to issue CRLs.");

                /*
                 * We will return UNKNOWN status.
                 */
                RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);

                revocationResult.getDetails()[i] = detail;

                /* there is no need to continue because issuer is not allowed to issue CRLs */
                break;
            }
        }

        X509CRLSelector crlSelector = new X509CRLSelector();

        /* create a selector to find all relevant CRLs that were issued to the same issuer as the certificate */
        crlSelector.addIssuer(issuer);

        try {
            List<X509CRL> crls = findCRLs(certificate, crlSelector, issuerPublicKey, now);

            RevocationDetail detail = getRevocationDetail(crls, certificate, issuerCertificate, issuerPublicKey,
                    now);

            revocationResult.getDetails()[i] = detail;

            if (detail.getStatus() == RevocationStatus.REVOKED) {
                logger.warn("Certificate is revoked.");

                if (logger.isDebugEnabled()) {
                    logger.debug("Revoked certificate: " + certificate);
                }

                /* there is no need to continue because the CRL is revoked */
                break;
            }
        } catch (NoSuchProviderException e) {
            throw new NoSuchProviderRuntimeException(e);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Revocation status for CertPath " + certPath + " and TrustAnchor " + trustAnchor + " is "
                + revocationResult);
    }

    return revocationResult;
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validatePem(CertificateBundle certificateBundle, String subjectName)
        throws CertificateException, IOException, KeyVaultErrorException, IllegalArgumentException,
        InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, BadPaddingException {
    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());
    String secretValue = secret.value();

    // Extract private key from PEM
    PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue);
    Assert.assertNotNull(secretPrivateKey);

    // Extract certificates from PEM
    List<X509Certificate> certificates = extractCertificatesFromPemContents(secretValue);
    Assert.assertNotNull(certificates);/*  w w w .jav a  2s .c  o  m*/
    Assert.assertTrue(certificates.size() == 1);

    // has the public key corresponding to the private key.
    X509Certificate secretCertificate = certificates.get(0);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}