Example usage for java.security.cert X509Certificate toString

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

Introduction

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

Prototype

public abstract String toString();

Source Link

Document

Returns a string representation of this certificate.

Usage

From source file:com.tremolosecurity.unison.google.u2f.U2FServerUnison.java

@Override
public SecurityKeyData processRegistrationResponse(RegistrationResponse registrationResponse,
        long currentTimeInMillis) throws U2FException {
    log.debug(">> processRegistrationResponse");

    String sessionId = registrationResponse.getSessionId();
    String clientDataBase64 = registrationResponse.getClientData();
    String rawRegistrationDataBase64 = registrationResponse.getRegistrationData();

    log.debug(">> rawRegistrationDataBase64: " + rawRegistrationDataBase64);
    EnrollSessionData sessionData = dataStore.getEnrollSessionData(sessionId);

    if (sessionData == null) {
        throw new U2FException("Unknown session_id");
    }/* w ww . j av  a  2  s . co  m*/

    String appId = sessionData.getAppId();
    String clientData = new String(Base64.decodeBase64(clientDataBase64));
    byte[] rawRegistrationData = Base64.decodeBase64(rawRegistrationDataBase64);
    if (log.isDebugEnabled()) {
        log.debug("-- Input --");
        log.debug("  sessionId: " + sessionId);
        log.debug("  challenge: " + Hex.encodeHexString(sessionData.getChallenge()));
        log.debug("  accountName: " + sessionData.getAccountName());
        log.debug("  clientData: " + clientData);
        log.debug("  rawRegistrationData: " + Hex.encodeHexString(rawRegistrationData));
    }
    RegisterResponse registerResponse = RawMessageCodec.decodeRegisterResponse(rawRegistrationData);

    byte[] userPublicKey = registerResponse.getUserPublicKey();
    byte[] keyHandle = registerResponse.getKeyHandle();
    X509Certificate attestationCertificate = registerResponse.getAttestationCertificate();
    byte[] signature = registerResponse.getSignature();
    List<Transports> transports = null;
    try {
        transports = U2fAttestation.Parse(attestationCertificate).getTransports();
    } catch (CertificateParsingException e) {
        log.warn("Could not parse transports extension " + e.getMessage());
    }

    if (log.isDebugEnabled()) {
        log.debug("-- Parsed rawRegistrationResponse --");
        log.debug("  userPublicKey: " + Hex.encodeHexString(userPublicKey));
        log.debug("  keyHandle: " + Hex.encodeHexString(keyHandle));
        log.debug("  attestationCertificate: " + attestationCertificate.toString());
        log.debug("  transports: " + transports);
        try {
            log.debug("  attestationCertificate bytes: "
                    + Hex.encodeHexString(attestationCertificate.getEncoded()));
        } catch (CertificateEncodingException e) {
            throw new U2FException("Cannot encode certificate", e);
        }
        log.debug("  signature: " + Hex.encodeHexString(signature));
    }

    byte[] appIdSha256 = crypto.computeSha256(appId.getBytes());
    byte[] clientDataSha256 = crypto.computeSha256(clientData.getBytes());
    byte[] signedBytes = RawMessageCodec.encodeRegistrationSignedBytes(appIdSha256, clientDataSha256, keyHandle,
            userPublicKey);

    Set<X509Certificate> trustedCertificates = dataStore.getTrustedCertificates();
    boolean found = false;
    for (X509Certificate trusted : trustedCertificates) {
        try {
            attestationCertificate.verify(trusted.getPublicKey());
            found = true;
        } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException
                | SignatureException e) {

        }
    }

    if (!found) {
        if (!this.requireAttestation) {
            log.warn("attestion cert is not trusted");
        } else {
            throw new U2FException("Attestation certificate is not trusted");
        }
    }

    verifyBrowserData(new JsonParser().parse(clientData), "navigator.id.finishEnrollment", sessionData);
    if (log.isDebugEnabled()) {
        log.debug("Verifying signature of bytes " + Hex.encodeHexString(signedBytes));
    }

    if (!crypto.verifySignature(attestationCertificate, signedBytes, signature)) {
        throw new U2FException("Signature is invalid");
    }

    // The first time we create the SecurityKeyData, we set the counter value to 0.
    // We don't actually know what the counter value of the real device is - but it will
    // be something bigger (or equal) to 0, so subsequent signatures will check out ok.
    SecurityKeyData securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle,
            userPublicKey, attestationCertificate, /* initial counter value */ 0);
    dataStore.addSecurityKeyData(sessionData.getAccountName(), securityKeyData);

    if (log.isDebugEnabled()) {
        log.debug("<< processRegistrationResponse");
    }

    return securityKeyData;
}

From source file:org.tolven.web.RegisterAction.java

public String getUserCertificateString() {
    if (isFormattedUserCertificate()) {
        X509Certificate x509Certificate = getUserX509Certificate();
        if (x509Certificate == null) {
            return null;
        } else {//from ww w.jav a 2 s.  c om
            return x509Certificate.toString();
        }
    } else {
        return getUserX509CertificateString();
    }
}

From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java

/**
 * This function drives the accepting side of the context establishment
 * process. It is expected to be called in tandem with the
 * {@link #initSecContext(byte[], int, int) initSecContext} function.
 * <BR>//from  w w  w .j ava 2 s. c  om
 * The behavior of context establishment process can be modified by
 * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}
 * and {@link GSSConstants#REJECT_LIMITED_PROXY
 * GSSConstants.REJECT_LIMITED_PROXY} context options. If the
 * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}
 * option is set to
 * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL}
 * the context establishment process will be compatible with regular SSL
 * (no credential delegation support). If the option is set to
 * {@link GSIConstants#MODE_GSI GSIConstants.MODE_GSI}
 * credential delegation during context establishment process will be accepted.
 * If the {@link GSSConstants#REJECT_LIMITED_PROXY
 * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, a peer
 * presenting limited proxy credential will be automatically
 * rejected and the context establishment process will be aborted.
 *
 * @return a byte[] containing the token to be sent to the peer.
 *         null indicates that no token is generated (needs more data)
 */
public byte[] acceptSecContext(byte[] inBuff, int off, int len) throws GSSException {
    logger.debug("enter acceptSecContext");

    if (!this.conn) {
        this.role = ACCEPT;

        logger.debug("enter initializing in acceptSecContext");

        if (this.ctxCred.getName().isAnonymous()) {
            throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN,
                    "acceptCtx00");
        }

        if (this.ctxCred.getUsage() != GSSCredential.ACCEPT_ONLY
                && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) {
            throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN,
                    "badCredUsage");
        }

        setCredential();

        try {
            init(this.role);
        } catch (SSLException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        this.conn = true;
        logger.debug("done initializing in acceptSecContext");
    }

    /*DEL
            this.out.reset();
            this.in.putToken(inBuff, off, len);
    */
    this.outByteBuff.clear();
    ByteBuffer inByteBuff;
    if (savedInBytes != null) {
        if (len > 0) {
            byte[] allInBytes = new byte[savedInBytes.length + len];
            logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n");
            System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length);
            System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len);
            inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length);
        } else {
            inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length);
        }
        savedInBytes = null;
    } else {
        inByteBuff = ByteBuffer.wrap(inBuff, off, len);
    }

    switch (state) {

    case HANDSHAKE:

        try {
            logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString());
            SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus();

            if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // return null;
                throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!");
            } else {
                outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff);
            }

            logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString());

            outByteBuff.flip();

            /*DEL
                            if (this.conn.getHandshake().finishedP()) {
            */
            if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // the wrap/unwrap above has resulted in handshaking
                // being complete on our end.

                logger.debug("acceptSecContext handshake finished");
                handshakeFinished();

                // acceptor
                for (X509Certificate cert : this.ctxCred.getCertificateChain()) {
                    setGoodUntil(cert.getNotAfter());
                }
                this.targetName = this.ctxCred.getName();

                // initiator - peer
                /*DEL
                                    Vector chain = this.conn.getCertificateChain();
                */
                Certificate[] chain;
                try {
                    chain = this.sslEngine.getSession().getPeerCertificates();
                } catch (SSLPeerUnverifiedException e) {
                    chain = null;
                }
                if (chain == null || chain.length == 0) {
                    this.sourceName = new GlobusGSSName();
                    this.anonymity = true;
                } else {
                    /*DEL
                                            X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1);
                                            setGoodUntil(crt.getValidityNotAfter());
                            
                                            String identity = verifyChain(chain);
                    */
                    for (X509Certificate cert : (X509Certificate[]) chain) {
                        setGoodUntil(cert.getNotAfter());
                    }

                    String identity = BouncyCastleUtil.getIdentity(
                            bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain)));
                    this.sourceName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false));
                    this.peerLimited = Boolean.valueOf(ProxyCertificateUtil
                            .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0])));

                    logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName
                            + " Limited Proxy: " + this.peerLimited.toString());

                    this.anonymity = false;
                }

                if (this.gssMode == GSIConstants.MODE_GSI) {
                    this.state = SERVER_START_DEL;
                } else {
                    setDone();
                }
            }
        } catch (IOException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } catch (Exception e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        break;

    case SERVER_START_DEL:

        try {
            if (inByteBuff.remaining() <= 0) {
                return null;
            }

            /*DEL
                            int delChar = this.conn.getInStream().read();
            */
            outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff);
            outByteBuff.flip();
            byte[] delChar = new byte[outByteBuff.remaining()];
            outByteBuff.get(delChar, 0, delChar.length);
            /*DEL
                            if (delChar != GSIConstants.DELEGATION_CHAR) {
            */
            if (!Arrays.equals(delChar, DELEGATION_TOKEN)) {
                setDone();
                break;
            }

            /*DEL
                            Vector chain = this.conn.getCertificateChain();
            */
            Certificate[] chain;
            try {
                chain = this.sslEngine.getSession().getPeerCertificates();
            } catch (SSLPeerUnverifiedException e) {
                chain = null;
            }
            if (chain == null || chain.length == 0) {
                throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.DELEGATION_ERROR,
                        "noClientCert");
            }

            X509Certificate tmpCert = (X509Certificate) chain[0];
            /*DEL
            PureTLSUtil.convertCert((X509Cert)chain.lastElement());
            */
            byte[] req = generateCertRequest(tmpCert);
            /*DEL
                            this.conn.getOutStream().write(req, 0, req.length);
            */
            inByteBuff = ByteBuffer.wrap(req, 0, req.length);
            outByteBuff.clear();
            outByteBuff = sslDataWrap(inByteBuff, outByteBuff);
            outByteBuff.flip();

        } catch (GeneralSecurityException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        this.state = SERVER_END_DEL;
        break;

    case SERVER_END_DEL:

        try {
            if (inByteBuff.remaining() <= 0) {
                return null;
            }

            /*DEL
                            X509Certificate certificate = CertUtil.loadCertificate(this.conn.getInStream());
            */
            outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff);
            outByteBuff.flip();
            if (!outByteBuff.hasRemaining())
                break;
            byte[] buf = new byte[outByteBuff.remaining()];
            outByteBuff.get(buf, 0, buf.length);
            ByteArrayInputStream inStream = new ByteArrayInputStream(buf, 0, buf.length);
            CertificateFactory cf = null;
            X509Certificate certificate = null;
            try {
                cf = CertificateFactory.getInstance("X.509");
                certificate = (X509Certificate) cf.generateCertificate(inStream);
            } finally {
                inStream.close();
            }

            if (logger.isTraceEnabled()) {
                logger.trace("Received delegated cert: " + certificate.toString());
            }

            verifyDelegatedCert(certificate);

            /*DEL
                            Vector chain = this.conn.getCertificateChain();
            */
            Certificate[] chain = this.sslEngine.getSession().getPeerCertificates();
            int chainLen = chain.length;
            X509Certificate[] newChain = new X509Certificate[chainLen + 1];
            newChain[0] = bcConvert((X509Certificate) certificate);
            for (int i = 0; i < chainLen; i++) {
                /*DEL
                                    newChain[i+1] = PureTLSUtil.convertCert((X509Cert)chain.elementAt(chainLen - 1 - i));
                */
                newChain[i + 1] = bcConvert((X509Certificate) chain[i]);
            }

            X509Credential proxy = new X509Credential(this.keyPair.getPrivate(), newChain);

            this.delegCred = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT);

        } catch (GeneralSecurityException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } catch (IOException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }
        setDone();
        break;

    default:
        throw new GSSException(GSSException.FAILURE);
    }

    if (inByteBuff.hasRemaining()) {
        // Likely BUFFER_UNDERFLOW; save the
        // inByteBuff bytes here like in the unwrap() case
        logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining()
                + " Handshaking status: " + sslEngine.getHandshakeStatus());
        logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n");
        savedInBytes = new byte[inByteBuff.remaining()];
        inByteBuff.get(savedInBytes, 0, savedInBytes.length);
    }

    logger.debug("exit acceptSecContext");
    /*DEL
            return (this.out.size() > 0) ? this.out.toByteArray() : null;
    */
    if (this.outByteBuff.hasRemaining()) {
        // TODO can we avoid this copy if the ByteBuffer is array based
        // and we return that array, each time allocating a new array
        // for outByteBuff?
        byte[] out = new byte[this.outByteBuff.remaining()];
        this.outByteBuff.get(out, 0, out.length);
        return out;
    } else
        return null;
}

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 .j  a  va  2 s . c  om*/
 * @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:org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler.java

protected final boolean doAuthentication(final Credentials credentials) throws AuthenticationException {

    final X509CertificateCredentials x509Credentials = (X509CertificateCredentials) credentials;
    final X509Certificate[] certificates = x509Credentials.getCertificates();

    /*//from  w w w.j av a 2  s.c  o  m
     * the certificate that was fully authenticated succesfully will be set
     * as the user credentials for CAS last certificate that can be set is
     * the end-user certificate
     */
    X509Certificate certificateCredentialsCandidate = null;
    // flag to check whether a trusted issuer is in the certificate chain
    boolean hasTrustedIssuerInChain = false;

    /*
     * reverse transversal of certificates (should be from root to end-user
     * cert)
     */
    for (int i = (certificates.length - 1); i >= 0; i--) {
        final X509Certificate certificate = certificates[i];
        try {
            final Principal issuerPrincipal = certificate.getIssuerDN();
            // flag that is set when this cert is an end user cert (no CA
            // cert)
            boolean isEndUserCertificate = false;

            if (log.isDebugEnabled()) {
                log.debug("--examining cert[" + certificate.getSerialNumber().toString() + "] "
                        + certificate.getSubjectDN() + "\"" + " from issuer \"" + issuerPrincipal.getName()
                        + "\"");
            }

            // check basic validity of the current certificate
            certificate.checkValidity();
            log.debug("certificate is valid");

            // initial check for trusted issuer in certificate chain
            // final check is done outside for loop
            if (isCertificateFromTrustedIssuer(issuerPrincipal)) {
                hasTrustedIssuerInChain = true;
                log.debug("certificate was issued by trusted issuer");
            }

            // getBasicConstraints returns pathLenContraint which is
            // >=0 when this is a CA cert and -1 when it's not
            int pathLength = certificate.getBasicConstraints();
            if (pathLength != -1) {
                log.debug("this is a CA certificate");

                // check pathLength when CA cert
                //if unlimited/unspecified and unlimited/unspecified not allowed: warn+stop
                if (pathLength == Integer.MAX_VALUE && this.maxPathLength_allowUnspecified != true) {
                    if (log.isWarnEnabled()) {
                        log.warn("authentication failed; cert pathLength not specified"
                                + " and unlimited/unspecified not allowed by config [see maxPathLength_allow_unlimited]");
                    }
                    return false;
                    //else if more than allowed length but not unlimited/unspecified: warn+stop
                } else if (pathLength > this.maxPathLength && pathLength < Integer.MAX_VALUE) {
                    if (log.isWarnEnabled()) {
                        log.warn("authentication failed; cert pathLength [" + pathLength
                                + "] is more than allowed by config [" + this.maxPathLength + "]");
                    }
                    return false;
                }
            } else {
                isEndUserCertificate = true;
                log.debug("this is an end-user certificate");
            }

            /*
             * set this certificate as the user credentials if there is an
             * issuer in the cert (always so if valid cert) and this is an
             * end-user or CA certificate (so not a CA cert) and optional
             * KeyUsage check
             */
            if (issuerPrincipal != null && isEndUserCertificate
                    && this.doesCertificateSubjectDnMatchPattern(certificate.getSubjectDN())
                    && (!this.checkKeyUsage
                            || (this.checkKeyUsage && this.doesCertificateKeyUsageMatch(certificate)))) {

                if (log.isDebugEnabled()) {
                    log.debug("cert[" + certificate.getSerialNumber().toString()
                            + "] ok, setting as credentials candidate");
                }
                certificateCredentialsCandidate = certificate;
            }
        } catch (final CertificateExpiredException e) {
            log.warn("authentication failed; certficiate expired [" + certificate.toString() + "]");
            certificateCredentialsCandidate = null;
        } catch (final CertificateNotYetValidException e) {
            log.warn("authentication failed; certficate not yet valid [" + certificate.toString() + "]");
            certificateCredentialsCandidate = null;
        }
    }

    // check whether one of the certificates in the chain was
    // from the trusted issuer; else => fail auth
    if (certificateCredentialsCandidate != null && hasTrustedIssuerInChain) {
        if (log.isInfoEnabled()) {
            log.info("authentication OK; SSL client authentication data meets criteria for cert["
                    + certificateCredentialsCandidate.getSerialNumber().toString() + "]");
        }
        x509Credentials.setCertificate(certificateCredentialsCandidate);
        return true;
    }

    if (log.isInfoEnabled()) {
        if (!hasTrustedIssuerInChain) {
            log.info("client cert did not have trusted issuer pattern \""
                    + this.regExTrustedIssuerDnPattern.pattern() + "\" in chain; authentication failed");
        } else {
            log.info("authentication failed; SSL client authentication data doesn't meet criteria");
        }
    }
    return false;
}

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

/**
 * Produce a human readable export of the given tsl to the given file.
 * /*ww w . j  a v a 2s  .  c  o 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);
        }
        */
        final List<String> schemeTypes = new ArrayList<String>();
        List<NonEmptyMultiLangURIType> uris = tsl.getSchemeTypes();
        for (NonEmptyMultiLangURIType uri : uris) {
            schemeTypes.add(uri.getValue());
        }
        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.getTradeNames(), 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);

                //add Scheme service definition 
                if (null != trustService.getSchemeServiceDefinitionURI()) {
                    addTitle("Scheme Service Definition URI", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                    final PdfPTable schemeServiceDefinitionURITabel = createInfoTable();
                    for (NonEmptyMultiLangURIType uri : trustService.getSchemeServiceDefinitionURI().getURI()) {
                        addItemRow(uri.getLang(), uri.getValue(), schemeServiceDefinitionURITabel);
                    }
                    document.add(schemeServiceDefinitionURITabel);
                }

                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);

                ServiceHistoryType serviceHistoryType = trustService.getServiceHistoryInstanceType();

                if (null != serviceHistoryType) {

                    for (ServiceHistoryInstanceType serviceHistoryInstanceType : serviceHistoryType
                            .getServiceHistoryInstance()) {
                        PdfPTable serviceHistoryTable = createInfoTable();

                        //Service approval history information
                        addTitle("Service approval history information", title3Font, Paragraph.ALIGN_LEFT, 10,
                                2, document);

                        // service type identifier
                        //5.6.2 Service name
                        InternationalNamesType i18nServiceName = serviceHistoryInstanceType.getServiceName();
                        String servName = TrustServiceListUtils.getValue(i18nServiceName, Locale.ENGLISH);
                        addItemRow("Name", servName, serviceHistoryTable);
                        //5.6.1 Service type identifier
                        addItemRow("Type", substringAfter(serviceHistoryInstanceType.getServiceTypeIdentifier(),
                                "Svctype/"), serviceHistoryTable);
                        addItemRow("Status", serviceHistoryInstanceType.getServiceStatus(),
                                serviceHistoryTable);
                        //5.6.4 Service previous status
                        addItemRow("Previous status", serviceHistoryInstanceType.getServiceStatus(),
                                serviceHistoryTable);
                        //5.6.5 Previous status starting date and time
                        addItemRow(
                                "Previous starting time", new DateTime(serviceHistoryInstanceType
                                        .getStatusStartingTime().toGregorianCalendar()).toString(),
                                serviceHistoryTable);
                        //5.6.3 Service digital identity
                        final X509Certificate previousCertificate = trustService.getServiceDigitalIdentity(
                                serviceHistoryInstanceType.getServiceDigitalIdentity());

                        document.add(serviceHistoryTable);

                        addTitle("Service digital identity (X509)", title4Font, Paragraph.ALIGN_LEFT, 2, 0,
                                document);

                        final PdfPTable serviceIdentityTableHistory = createInfoTable();
                        addItemRow("Version", Integer.toString(previousCertificate.getVersion()),
                                serviceIdentityTableHistory);
                        addItemRow("Serial number", previousCertificate.getSerialNumber().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Signature algorithm", previousCertificate.getSigAlgName(),
                                serviceIdentityTableHistory);
                        addItemRow("Issuer", previousCertificate.getIssuerX500Principal().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Valid from", previousCertificate.getNotBefore().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Valid to", previousCertificate.getNotAfter().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Subject", previousCertificate.getSubjectX500Principal().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Public key", previousCertificate.getPublicKey().toString(),
                                serviceIdentityTableHistory);
                        // TODO certificate policies
                        addItemRow("Subject key identifier", toHex(getSKId(previousCertificate)),
                                serviceIdentityTableHistory);
                        addItemRow("CRL distribution points", getCrlDistributionPoints(previousCertificate),
                                serviceIdentityTableHistory);
                        addItemRow("Authority key identifier", toHex(getAKId(previousCertificate)),
                                serviceIdentityTableHistory);
                        addItemRow("Key usage", getKeyUsage(previousCertificate), serviceIdentityTableHistory);
                        addItemRow("Basic constraints", getBasicConstraints(previousCertificate),
                                serviceIdentityTableHistory);

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

                        ExtensionsListType previousExtensions = serviceHistoryInstanceType
                                .getServiceInformationExtensions();
                        if (null != previousExtensions) {
                            for (ExtensionType extension : previousExtensions.getExtension()) {
                                printExtension(extension, document);
                            }
                        }

                        addLongMonoItem("The decoded certificate:", previousCertificate.toString(), document);
                        addLongMonoItem("The certificate in PEM format:", toPem(previousCertificate), 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);
    }
}