Example usage for java.security.cert X509Certificate getSubjectX500Principal

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

Introduction

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

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

From source file:demo.sts.provider.cert.CrlVerifier.java

public void verifyCertificateCRLs(X509Certificate cert, X509Certificate parentCert,
        String defaultDistributionPoint) throws CertificateVerificationException {
    File file = null;/*from   ww  w .  ja  va 2  s  . c  o m*/
    FileInputStream fileInputStream = null;
    try {
        List<String> crlDistPoints = getCrlDistributionPoints(cert);
        if (crlDistPoints.isEmpty() && !TextUtils.isEmpty(defaultDistributionPoint)) {
            crlDistPoints = new ArrayList<String>();
            crlDistPoints.add(defaultDistributionPoint);
        }
        for (String crlDP : crlDistPoints) {
            try {
                file = downloadCrl(new URL(crlDP));
                fileInputStream = new FileInputStream(file);

                X509CRL crl = getCrlFromStream(fileInputStream);

                crlIssuerVerifier.verify(crl, parentCert);

                if (crl.isRevoked(cert)) {
                    throw new CertificateVerificationException("The certificate is revoked by CRL: " + crlDP);
                }
            } finally {
                IOUtils.closeQuietly(fileInputStream);
                deleteFile(file);
            }
        }
    } catch (Exception e) {
        throw new CertificateVerificationException(
                "Can not verify CRL for certificate: " + cert.getSubjectX500Principal(), e);
    }
}

From source file:test.unit.test.be.fedict.eid.applet.model.XmlSignatureServiceBeanTest.java

private X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, DateTime notBefore,
        DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag,
        int pathLength, String ocspUri, KeyUsage keyUsage) throws IOException, InvalidKeyException,
        IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();//from w  w w  .  j a v  a2 s .c o m
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());
    X509Principal issuerDN;
    if (null != issuerCertificate) {
        issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    issuerPublicKey = subjectPublicKey;
    certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerPublicKey));

    if (caFlag) {
        if (-1 == pathLength) {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, false,
                    new BasicConstraints(true));
        } else {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, false,
                    new BasicConstraints(pathLength));
        }
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateGenerator.addExtension(X509Extensions.AuthorityInfoAccess.getId(), false,
                authorityInformationAccess);
    }

    if (null != keyUsage) {
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, keyUsage);
    }

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
}

From source file:org.texai.x509.X509Utils.java

/** Generates an intermediate CA certificate, that is to be used to sign end-use certificates.
 *
 * @param myPublicKey the public key for this certificate
 * @param issuerPrivateKey the issuer's private key
 * @param issuerCertificate the issuer's certificate, which is either the root CA certificate or another intermediate
 * CA certificate/*from  w ww . j a v  a  2  s . co m*/
 * @param pathLengthConstraint the maximum number of CA certificates that may follow this certificate in a certification
 * path. (Note: One end-entity certificate will follow the final CA certificate in the path. The last certificate in a path
 * is considered an end-entity certificate, whether the subject of the certificate is a CA or not.)
 * @return an intermediate CA certificate
 *
 * @throws CertificateParsingException when the certificate cannot be parsed
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */
public static X509Certificate generateIntermediateX509Certificate(final PublicKey myPublicKey,
        final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, int pathLengthConstraint)
        throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert myPublicKey != null : "myPublicKey must not be null";
    assert issuerPrivateKey != null : "issuerPrivateKey must not be null";
    assert issuerCertificate != null : "issuerCertificate must not be null";

    //final X500Name issuer = new X500Name(issuerCertificate.getSubjectX500Principal().getName());
    final X500Name issuer = new X500Name(
            StringUtils.reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName()));
    final UUID intermediateUUID = UUID.randomUUID();
    // provide items to X500Principal in reverse order
    final X500Principal x500Principal = new X500Principal(
            "UID=" + intermediateUUID + ", DC=IntermediateCertificate, CN=texai.org");
    final X500Name subject = new X500Name(x500Principal.getName());
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(myPublicKey.getEncoded()));
    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            subject, publicKeyInfo);

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();

    // Add authority key identifier
    x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate));

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(pathLengthConstraint)); // is a CA certificate with specified certification path length

    // add key usage
    final KeyUsage keyUsage = new KeyUsage(
            // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
            // certificates
            KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                   // information
                    KeyUsage.cRLSign);

    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate x509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey);
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        x509Certificate = makeCanonicalX509Certificate(
                jcaX509CertificateConverter.getCertificate(x509CertificateHolder));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        x509Certificate.checkValidity();
        x509Certificate.verify(issuerCertificate.getPublicKey());
    } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new TexaiException(ex);
    }

    return x509Certificate;
}

From source file:org.zuinnote.hadoop.office.format.common.util.CertificateChainVerificationUtil.java

public static boolean verifyCertificateChain(X509Certificate theCertificate,
        Set<X509Certificate> chainCertificates) throws CertificateException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidAlgorithmParameterException {

    // check if we can establish a trust chain
    if (isSelfSigned(theCertificate)) {
        LOG.error("Certificate is self-signed - no trust chain can be established with provided truststore");
        return false;
    }//from  w  w w. j  a  v  a  2  s.c o m
    if (chainCertificates.size() < 2) {
        LOG.error(
                "One needs at least three certificates (including certificate used for signing to establish a trust chain. Please check that you included them");
        return false;
    }
    HashSet<X509Certificate> rootCertificates = new HashSet<>();
    HashSet<X509Certificate> subCertificates = new HashSet<>();
    subCertificates.add(theCertificate);
    for (X509Certificate currentCertificate : chainCertificates) {
        if (CertificateChainVerificationUtil.isSelfSigned(currentCertificate)) {
            LOG.debug("Root: " + currentCertificate.getSubjectDN().getName());
            rootCertificates.add(currentCertificate);
        } else {
            LOG.debug("Sub: " + currentCertificate.getSubjectDN().getName());
            subCertificates.add(currentCertificate);
        }
    }
    // Configure verification
    X509CertSelector selector = new X509CertSelector();
    selector.setCertificate(theCertificate);

    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
    HashSet<TrustAnchor> trustAnchors = new HashSet<>();
    for (X509Certificate currentCertificate : rootCertificates) {
        trustAnchors.add(new TrustAnchor(currentCertificate, null));
    }

    PKIXBuilderParameters builderParams = new PKIXBuilderParameters(trustAnchors, selector);

    CertStore subCertStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(subCertificates), "BC");
    builderParams.addCertStore(subCertStore);

    try {
        PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(builderParams);
        return true;
    } catch (CertPathBuilderException e) {
        LOG.error("Exception: ", e);
        LOG.error("Cannot verify certification chain for " + theCertificate.getSubjectX500Principal());
    }
    return false;
}

From source file:controller.CCInstance.java

public boolean isTrustedCertificate(final X509Certificate x509c) {
    ArrayList<Certificate> alTrustedCertificates;
    try {/*from  w w  w.jav  a2 s  . c o  m*/
        alTrustedCertificates = getTrustedCertificatesFromKeystore(getKeystore());
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | InvalidAlgorithmParameterException ex) {
        return false;
    }

    if (alTrustedCertificates.isEmpty()) {
        return false;
    }

    for (final Certificate c : alTrustedCertificates) {
        try {
            final X509Certificate x509cc = (X509Certificate) c;
            if (x509c.getSubjectX500Principal().equals(x509cc.getSubjectX500Principal())) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }
    return false;
}

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

/**
 * Produce a human readable export of the given tsl to the given file.
 * //  ww  w . ja va  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:org.ejbca.ui.cli.HSMKeyTool.java

private static boolean doIt(final String[] orgArgs) throws Exception {
    // Get and remove optional switches
    final List<String> argsList = CliTools.getAsModifyableList(orgArgs);
    final KeyStore.ProtectionParameter protectionParameter;
    final String password = CliTools.getAndRemoveParameter("-password", argsList);
    if (password != null) {
        protectionParameter = new KeyStore.PasswordProtection(password.toCharArray());
    } else {/* w  ww .  j  a va  2s .co  m*/
        protectionParameter = null;
    }
    final String[] args = CliTools.getAsArgs(argsList);
    if (args[1].toLowerCase().trim().contains(GENERATE_BATCH_SWITCH)) {
        if (args.length < 4) {
            printCommandString(args, "<name of batch file> [", TOKEN_ID_PARAM, "]");
            printTokenIdDescription();
            sunConfigFileUseDescription();
            System.err.println(
                    "The batch file is a file which specifies alias and key specification for each key to be generated.");
            System.err
                    .println("Each row is starting with a key alias then the key specification is following.");
            System.err.println("The specification of the key is done like this: " + KEY_SPEC_DESC);
            tooFewArguments(args);
        }
        final String storeId;
        final Pkcs11SlotLabelType slotType;
        if (args.length > 4) {
            storeId = trimStoreId(args[4]);
            slotType = getTokenLabelType(args[4]);
        } else {
            storeId = null;
            slotType = Pkcs11SlotLabelType.SUN_FILE;
        }
        final KeyStoreTools store = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter, "batch-" + new Date().getTime());
        generateBatch(args[3], store);
        return true;
    }
    if (args[1].toLowerCase().trim().contains(GENERATE_SWITCH)) {
        if (args.length < 4) {
            printCommandString(args, Character.valueOf('<'), KEY_SPEC_DESC, "> <key entry name> [",
                    TOKEN_ID_PARAM, "]");
            printTokenIdDescription();
            sunConfigFileUseDescription();
            tooFewArguments(args);
        }
        final String keyEntryName = args.length > 4 ? args[4] : "myKey";
        final String storeId;
        final Pkcs11SlotLabelType slotType;
        if (args.length > 5) {
            storeId = trimStoreId(args[5]);
            slotType = getTokenLabelType(args[5]);
        } else {
            storeId = null;
            slotType = Pkcs11SlotLabelType.SUN_FILE;
        }
        System.out.println("Using Slot Reference Type: " + slotType + '.');
        final KeyStoreTools store = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter, "priv-" + keyEntryName);
        store.generateKeyPair(args[3], keyEntryName);
        System.out.println("Created certificate with entry " + keyEntryName + '.');
        return true;
    }
    if (args[1].toLowerCase().trim().equals(DELETE_SWITCH)) {
        if (args.length < 4) {
            printCommandString(args, TOKEN_ID_PARAM, " [<key entry name>]");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String alias = args.length > 4 ? args[4] : null;
        System.out.println("Deleting certificate with alias " + alias + '.');
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);

        KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter)
                .deleteEntry(alias);
        return true;
    }
    if (args[1].toLowerCase().trim().equals(CERT_REQ)) {
        // First we check if we have a switch for "-explicitecc" for explicit ecc parameters used in ICAO epassports.
        final List<String> argsListLocal = CliTools.getAsModifyableList(args);
        final boolean explicitEccParameters = argsListLocal.remove("-explicitecc");
        final boolean forAllKeys = argsListLocal.remove("-all");
        final String modArgs[] = argsListLocal.toArray(new String[argsListLocal.size()]);
        if (modArgs.length < 4 || (modArgs.length < 5 && !forAllKeys)) {
            printCommandString(args, TOKEN_ID_PARAM, " <key entry name> [<CN>] [-explicitecc]");
            printCommandString(args, TOKEN_ID_PARAM, " [-all] [-explicitecc]");
            printTokenIdDescription();
            tooFewArguments(modArgs);
        }
        final String storeId = trimStoreId(modArgs[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(modArgs[3]);
        final KeyStoreTools container = KeyStoreToolsFactory.getInstance(modArgs[2], storeId, slotType, null,
                protectionParameter);
        final List<String> entries;
        if (forAllKeys) {
            entries = new LinkedList<>();
            final CachingKeyStoreWrapper ks = container.getKeyStore();
            final Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                final String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    entries.add(alias);
                }
            }
        } else {
            entries = Collections.singletonList(modArgs[4]);
        }

        for (String entry : entries) {
            container.generateCertReq(entry, modArgs.length > 5 ? modArgs[5] : null, explicitEccParameters);
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(INSTALL_CERT)) {
        if (args.length < 5) {
            printCommandString(args, TOKEN_ID_PARAM,
                    " <certificate chain files in PEM format (one chain per file)>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final KeyStoreTools container = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter);
        boolean failure = false;
        for (int i = 4; i < args.length; i++) {
            try {
                container.installCertificate(args[i]);
            } catch (Exception ex) {
                failure = true;
                log.error("File " + args[i] + " failed.", ex);
            }
        }
        if (failure) {
            throw new Exception("At least one certificate could not be installed. See the log for more info.");
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(INSTALL_TRUSTED_ROOT)) {
        if (args.length < 5) {
            printCommandString(args, TOKEN_ID_PARAM, " <trusted root certificate in PEM format>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter)
                .installTrustedRoot(args[4]);
        return true;
    }
    if (args[1].toLowerCase().trim().equals(ENCRYPT_SWITCH)) {
        String symmAlgOid = CMSEnvelopedGenerator.AES128_CBC;
        if (args.length < 5) {
            System.err.println("There are two ways of doing the encryption:");
            printCommandString(args, TOKEN_ID_PARAM,
                    " <input file> <output file> <key alias> [optional symm algorithm oid]");
            printCommandStringNoSharedLib(args,
                    "<input file> <output file> <file with certificate with public key to use> [optional symm algorithm oid]");
            printTokenIdDescription();
            System.err.println(
                    "Optional symmetric encryption algorithm OID can be for example 2.16.840.1.101.3.4.1.42 (AES256_CBC) or 1.2.392.200011.61.1.1.1.4 (CAMELLIA256_CBC). Default is to use AES256_CBC.");
            tooFewArguments(args);
        }
        if (args.length < 7) {
            Security.addProvider(new BouncyCastleProvider());
            if (args.length > 5) {
                // We have a symmAlg as last parameter
                symmAlgOid = args[5];
            }
            System.out.println("Using symmetric encryption algorithm: " + symmAlgOid);
            try (final InputStream certIS = new FileInputStream(args[4]);
                    final InputStream is = new FileInputStream(args[2]);
                    final OutputStream os = new FileOutputStream(args[3])) {
                final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                        .generateCertificate(new BufferedInputStream(certIS));
                CMS.encrypt(is, os, cert, symmAlgOid);
            }
        } else {
            if (args.length > 7) {
                // We have a symmAlg as last parameter
                symmAlgOid = args[7];
            }
            System.out.println("Using symmstric encryption algorithm: " + symmAlgOid);
            final String storeId = trimStoreId(args[3]);
            final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
            try (final InputStream is = new FileInputStream(args[4]);
                    final OutputStream os = new FileOutputStream(args[5]);) {
                final Certificate cert = KeyStoreToolsFactory
                        .getInstance(args[2], storeId, slotType, null, protectionParameter).getKeyStore()
                        .getCertificate(args[6]);
                CMS.encrypt(is, os, (X509Certificate) cert, symmAlgOid);
            }
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(DECRYPT_SWITCH)) {
        if (args.length < 7) {
            printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        try (final InputStream is = new FileInputStream(args[4]);
                final OutputStream os = new FileOutputStream(args[5])) {
            final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                    protectionParameter);
            CMS.decrypt(is, os, (PrivateKey) keyStore.getKeyStore().getKey(args[6], null),
                    keyStore.getProviderName());
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(SIGN_SWITCH)) {
        if (args.length < 7) {
            printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter);
        final String alias = args[6];
        final PrivateKey key = (PrivateKey) keyStore.getKeyStore().getKey(alias, null);
        final X509Certificate cert = (X509Certificate) keyStore.getKeyStore().getCertificate(alias);
        try (final InputStream is = new FileInputStream(args[4]);
                final OutputStream os = new FileOutputStream(args[5]);) {
            CMS.sign(is, os, key, keyStore.getProviderName(), cert);
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(LINKCERT_SWITCH)) {
        if (args.length < 8) {
            printCommandString(args, TOKEN_ID_PARAM,
                    " <old ca-cert> <new ca-cert> <output link-cert> <key alias> [<sig alg override>]");
            printTokenIdDescription();
            System.err.println();
            System.err.println("Creates a link certificate that links the old and new certificate files.");
            System.err.println("You should use this command with the old HSM key. It does not need any");
            System.err.println("access to the new key.");
            System.err.println();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final KeyStoreTools ksc = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter);
        final String alias = args[7];
        final String oldCertPath = args[4];
        final String newCertPath = args[5];
        final String outputPath = args[6];
        final String signProviderName = ksc.getProviderName();
        final String sigAlgOverride = (args.length > 8 ? args[8] : "null");

        // Parse certificates
        final byte[] oldCertBytes;
        try (final InputStream is = new FileInputStream(oldCertPath)) {
            oldCertBytes = IOUtils.toByteArray(is);
        }
        final byte[] newCertBytes;
        try (final InputStream is = new FileInputStream(newCertPath)) {
            newCertBytes = IOUtils.toByteArray(is);
        }
        final Certificate oldCert = CertTools.getCertfromByteArray(oldCertBytes,
                BouncyCastleProvider.PROVIDER_NAME, Certificate.class);
        final Certificate newCert = CertTools.getCertfromByteArray(newCertBytes,
                BouncyCastleProvider.PROVIDER_NAME, Certificate.class);
        final boolean isCVCA = (oldCert instanceof CardVerifiableCertificate);
        if (isCVCA != (newCert instanceof CardVerifiableCertificate)) {
            log.error("Error: Old and new certificates are not of the same type (X509 / CVC)");
            return true; // = valid command-line syntax
        }
        System.out.println("Type of certificates: " + (isCVCA ? "CVC" : "X509"));

        // Detect name change
        final String oldDN = CertTools.getSubjectDN(oldCert);
        final String newDN = CertTools.getSubjectDN(newCert);
        System.out.println("Old DN: " + oldDN);
        System.out.println("New DN: " + newDN);
        final boolean nameChange;
        if (!oldDN.equals(newDN)) {
            if (isCVCA) {
                System.out.println("Name change detected.");
            } else {
                System.out.println("Name change detected. Will add Name Change extension.");
            }
            nameChange = true;
        } else {
            System.out.println("No name change detected.");
            nameChange = false;
        }

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Get new and old key
        final PublicKey newPubKey = newCert.getPublicKey();
        if (newPubKey == null) {
            System.err.println("Error: Failed to extract public key from new certificate");
            return true;
        }
        final Key oldKey = ksc.getKeyStore().getKey(alias, null);
        if (oldKey == null) {
            System.err.println("Error: Could not find the key named " + alias);
            return true;
        }
        final PrivateKey oldPrivKey = (PrivateKey) oldKey;

        if (isCVCA) {
            final CVCertificate oldCertCVC = ((CardVerifiableCertificate) oldCert).getCVCertificate();
            final CVCertificate newCertCVC = ((CardVerifiableCertificate) newCert).getCVCertificate();

            final String linkSigAlg;
            if (sigAlgOverride.equalsIgnoreCase("null")) {
                final OIDField oldKeyTypeOid = oldCertCVC.getCertificateBody().getPublicKey()
                        .getObjectIdentifier();
                linkSigAlg = AlgorithmUtil.getAlgorithmName(oldKeyTypeOid);
            } else {
                System.err.println("Error: Overriding the signature algorithm is not supported for CVC");
                return true;
            }
            System.out.println("Using signature algorithm " + linkSigAlg);

            final HolderReferenceField caHolder = oldCertCVC.getCertificateBody().getHolderReference();
            final CAReferenceField caRef = new CAReferenceField(caHolder.getCountry(), caHolder.getMnemonic(),
                    caHolder.getSequence());
            final HolderReferenceField certHolder = newCertCVC.getCertificateBody().getHolderReference();
            final AuthorizationRole authRole = newCertCVC.getCertificateBody().getAuthorizationTemplate()
                    .getAuthorizationField().getAuthRole();
            final AccessRights rights = newCertCVC.getCertificateBody().getAuthorizationTemplate()
                    .getAuthorizationField().getAccessRights();
            final Date validFrom = new Date(new Date().getTime() - 60L * 15L * 1000L); // back date by 15 minutes to allow for clock skew
            final Date validTo = oldCertCVC.getCertificateBody().getValidTo();

            final CVCertificate linkCert = CertificateGenerator.createCertificate(newPubKey, oldPrivKey,
                    linkSigAlg, caRef, certHolder, authRole, rights, validFrom, validTo, signProviderName);
            try (final DataOutputStream dos = new DataOutputStream(baos)) {
                linkCert.encode(dos);
            }
        } else {
            // X509 CA
            final X509Certificate oldCertX509 = (X509Certificate) oldCert;
            final X509Certificate newCertX509 = (X509Certificate) newCert;

            final String linkSigAlg;
            if (sigAlgOverride.equalsIgnoreCase("null")) {
                // Actually, we should use signature algorithm of new cert if the old key allows that.
                // Instead of doing that we allow the user to manually override the signature algorithm if needed.
                linkSigAlg = oldCertX509.getSigAlgName();
            } else {
                System.err.println("Warning: Signature algorithm manually overridden!");
                linkSigAlg = sigAlgOverride;
            }
            System.out.println("Using signature algorithm " + linkSigAlg);

            final BigInteger serno = SernoGeneratorRandom.instance().getSerno();
            final SubjectPublicKeyInfo pkinfo = SubjectPublicKeyInfo.getInstance(newPubKey.getEncoded());
            final Date validFrom = new Date(new Date().getTime() - 60L * 15L * 1000L); // back date by 15 minutes to allow for clock skew
            final Date validTo = oldCertX509.getNotAfter();

            final X500Name oldDNName = X500Name.getInstance(oldCertX509.getSubjectX500Principal().getEncoded());
            final X500Name newDNName = X500Name.getInstance(newCertX509.getSubjectX500Principal().getEncoded());

            final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(oldDNName, serno,
                    validFrom, validTo, newDNName, pkinfo);

            // Copy all extensions except AKID
            final ExtensionsGenerator extgen = new ExtensionsGenerator();
            final Set<String> oids = new LinkedHashSet<>();
            final Set<String> criticalOids = newCertX509.getCriticalExtensionOIDs();
            oids.addAll(criticalOids);
            oids.addAll(newCertX509.getNonCriticalExtensionOIDs());
            for (final String extOidStr : oids) {
                final ASN1ObjectIdentifier extoid = new ASN1ObjectIdentifier(extOidStr);
                if (!extoid.equals(Extension.authorityKeyIdentifier)) {
                    final byte[] extbytes = newCertX509.getExtensionValue(extOidStr);
                    final ASN1OctetString str = (ASN1OctetString) ASN1Primitive.fromByteArray(extbytes);
                    extgen.addExtension(extoid, criticalOids.contains(extOidStr),
                            ASN1Primitive.fromByteArray(str.getOctets()));
                }
            }

            if (nameChange) {
                // id-icao-mrtd-security-extensions-nameChange = 2.23.136.1.1.6.1
                extgen.addExtension(ICAOObjectIdentifiers.id_icao_extensions_namechangekeyrollover, false,
                        DERNull.INSTANCE);
            }

            // Some checks
            if (newCertX509.getExtensionValue(Extension.subjectKeyIdentifier.getId()) == null) {
                System.err.println(
                        "Warning: Certificate of new CSCA is missing the Subject Key Identifier extension, which is mandatory.");
            }
            if (newCertX509.getExtensionValue(Extension.authorityKeyIdentifier.getId()) == null) {
                System.err.println(
                        "Warning: Certificate of new CSCA is missing the Authority Key Identifier extension, which is mandatory.");
            }

            // If the new cert has an AKID, then add that extension but with the key id value of the old cert
            final byte[] oldSKIDBytes = oldCertX509.getExtensionValue(Extension.subjectKeyIdentifier.getId());
            if (oldSKIDBytes != null) {
                final ASN1OctetString str = (ASN1OctetString) ASN1Primitive.fromByteArray(oldSKIDBytes);
                final ASN1OctetString innerStr = (ASN1OctetString) ASN1Primitive.fromByteArray(str.getOctets());
                final AuthorityKeyIdentifier akidExt = new AuthorityKeyIdentifier(innerStr.getOctets());
                extgen.addExtension(Extension.authorityKeyIdentifier, false, akidExt);
            } else {
                System.err.println(
                        "Warning: The old certificate doesn't have any SubjectKeyIdentifier. The link certificate will not have any AuthorityKeyIdentifier.");
            }

            // Add extensions to the certificate
            final Extensions exts = extgen.generate();
            for (final ASN1ObjectIdentifier extoid : exts.getExtensionOIDs()) {
                final Extension ext = exts.getExtension(extoid);
                certbuilder.addExtension(extoid, ext.isCritical(), ext.getParsedValue());
            }

            // Sign the certificate
            final ContentSigner signer = new BufferingContentSigner(
                    new JcaContentSignerBuilder(linkSigAlg).setProvider(signProviderName).build(oldPrivKey),
                    20480);
            final X509CertificateHolder certHolder = certbuilder.build(signer);
            baos.write(certHolder.getEncoded());

            // Save to output file
            try (final FileOutputStream fos = new FileOutputStream(outputPath)) {
                baos.writeTo(fos);
            }
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(VERIFY_SWITCH)) {
        final CMS.VerifyResult verifyResult;
        if (args.length < 5) {
            System.err.println("There are two ways of doing the encryption:");
            printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>");
            printTokenIdDescription();
            printCommandStringNoSharedLib(args,
                    "<input file> <output file> <file with certificate with public key to use>");
            tooFewArguments(args);
        }
        if (args.length < 7) {
            Security.addProvider(new BouncyCastleProvider());
            try (final InputStream certIS = new FileInputStream(args[4]);
                    final InputStream is = new FileInputStream(args[2]);
                    final OutputStream os = new FileOutputStream(args[3]);) {
                final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                        .generateCertificate(new BufferedInputStream(certIS));
                verifyResult = CMS.verify(is, os, cert);
            }
        } else {
            final String storeId = trimStoreId(args[3]);
            final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
            final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                    protectionParameter);
            final X509Certificate cert = (X509Certificate) keyStore.getKeyStore().getCertificate(args[6]);
            try (final InputStream is = new FileInputStream(args[4]);
                    final OutputStream os = new FileOutputStream(args[5])) {
                verifyResult = CMS.verify(is, os, cert);
            }
        }
        if (verifyResult == null) {
            System.err.println("Not possible to parse signed file.");
            System.exit(4); // Not verifying // NOPMD, it's not a JEE app
            return false;//will never be executes. just to avoid warning.
        }
        System.out.println(
                "The signature of the input " + (verifyResult.isVerifying ? "has been" : "could not be")
                        + " verified. The file was signed on '" + verifyResult.signDate
                        + "'. The public part of the signing key is in a certificate with serial number "
                        + verifyResult.signerId.getSerialNumber() + " issued by '"
                        + verifyResult.signerId.getIssuer() + "'.");
        if (!verifyResult.isVerifying) {
            System.exit(4); // Not verifying // NOPMD, it's not a JEE app
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(TEST_SWITCH)) {
        if (args.length < 4) {
            printCommandString(args, TOKEN_ID_PARAM,
                    " [<'m:n' m # of threads, n # of tests>] [<alias for stress test>] [<type of stress test>]");
            printTokenIdDescription();
            System.err.println(
                    "    If a file named \"./testData\" exists then the data that is signed, is read from this file.");
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final NrOfThreadsAndNrOfTests notanot = new NrOfThreadsAndNrOfTests(args.length > 4 ? args[4] : null);
        KeyStoreContainerTest.test(args[2], storeId, slotType, notanot.threads, notanot.tests,
                args.length > 5 ? args[5].trim() : null, args.length > 6 ? args[6].trim() : null,
                protectionParameter);
        return true;
    }
    if (args[1].toLowerCase().trim().equals(RENAME)) {
        if (args.length < 6) {
            printCommandString(args, TOKEN_ID_PARAM, " <old key alias> <new key alias>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter);

        keyStore.renameEntry(args[4], args[5]);
        return true;
    }
    if (args[1].toLowerCase().trim().equals(MOVE_SWITCH)) {
        if (args.length < 5) {
            printCommandString(args, "<from PKCS#11 token identifier> <to PKCS#11 token identifier>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final KeyStoreTools fromKS = KeyStoreToolsFactory.getInstance(args[2], trimStoreId(args[3]),
                getTokenLabelType(args[3]), null, protectionParameter);
        final KeyStoreTools toKS = KeyStoreToolsFactory.getInstance(args[2], trimStoreId(args[4]),
                getTokenLabelType(args[4]), null, protectionParameter);
        System.out.println("Moving entry with alias '" + args[3] + "' to alias '" + args[4] + '.');
        final Enumeration<String> e = fromKS.getKeyStore().aliases();
        while (e.hasMoreElements()) {
            final String alias = e.nextElement();
            if (fromKS.getKeyStore().isKeyEntry(alias)) {
                final Key key = fromKS.getKeyStore().getKey(alias, null);
                final Certificate chain[] = fromKS.getKeyStore().getCertificateChain(alias);
                toKS.setKeyEntry(alias, key, chain);
            }
            fromKS.getKeyStore().deleteEntry(alias);
        }
        fromKS.getKeyStore().store(null, null);
        toKS.getKeyStore().store(null, null);
        return true;
    }
    return false;
}

From source file:org.josso.auth.scheme.X509CertificateAuthScheme.java

/**
 * @throws SSOAuthenticationException//  w  w  w  .j ava 2s  .c o m
 */
public boolean authenticate() throws SSOAuthenticationException {

    setAuthenticated(false);

    //String username = getUsername(_inputCredentials);
    X509Certificate x509Certificate = getX509Certificate(_inputCredentials);

    // Check if all credentials are present.
    if (x509Certificate == null) {

        if (logger.isDebugEnabled())
            logger.debug("X.509 Certificate not provided");

        // We don't support empty values !
        return false;
    }

    // validate certificate
    if (_validators != null) {
        for (X509CertificateValidator validator : _validators) {
            try {
                validator.validate(x509Certificate);
            } catch (X509CertificateValidationException e) {
                logger.error("Certificate is not valid!", e);
                return false;
            }
        }
    }

    List<X509Certificate> knownX509Certificates = getX509Certificates(getKnownCredentials());

    StringBuffer buf = new StringBuffer("\n\tSupplied Credential: ");
    buf.append(x509Certificate.getSerialNumber().toString(16));
    buf.append("\n\t\t");
    buf.append(x509Certificate.getSubjectX500Principal().getName());
    buf.append("\n\n\tExisting Credentials: ");
    for (int i = 0; i < knownX509Certificates.size(); i++) {
        X509Certificate knownX509Certificate = knownX509Certificates.get(i);
        buf.append(i + 1);
        buf.append("\n\t\t");
        buf.append(knownX509Certificate.getSerialNumber().toString(16));
        buf.append("\n\t\t");
        buf.append(knownX509Certificate.getSubjectX500Principal().getName());
        buf.append("\n");
    }

    logger.debug(buf.toString());

    // Validate user identity ...
    boolean valid = false;
    X509Certificate validCertificate = null;
    for (X509Certificate knownX509Certificate : knownX509Certificates) {
        if (validateX509Certificate(x509Certificate, knownX509Certificate)) {
            validCertificate = knownX509Certificate;
            break;
        }
    }

    if (validCertificate == null) {
        return false;
    }

    // Find UID
    // (We could just use getUID() to authenticate user
    // without previous validation against known certificates?)
    _uid = getUID();
    if (_uid == null) {
        return false;
    }

    if (logger.isDebugEnabled())
        logger.debug(
                "[authenticate()], Principal authenticated : " + x509Certificate.getSubjectX500Principal());

    // We have successfully authenticated this user.
    setAuthenticated(true);
    return true;
}

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  a2  s .  c  o  m
    }

    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:be.fedict.trust.TrustValidator.java

private void checkTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate)
        throws CertPathValidatorException {
    if (null == childCertificate) {
        return;//from w  w  w.  j  a v  a 2s . c  o  m
    }
    // check certificate signature
    this.result = checkSignatureAlgorithm(childCertificate.getSigAlgName());
    if (!this.result.isValid()) {
        throw new CertPathValidatorException(this.result.getMessage());
    }

    boolean sometrustLinkerTrusts = false;
    for (TrustLinker trustLinker : this.trustLinkers) {
        LOG.debug("trying trust linker: " + trustLinker.getClass().getSimpleName());
        this.result = trustLinker.hasTrustLink(childCertificate, certificate, validationDate,
                this.revocationData);
        if (null == this.result) {
            continue;
        }
        if (this.result.isValid()) {
            sometrustLinkerTrusts = true;
        } else {
            throw new CertPathValidatorException(this.result.getMessage());
        }
    }
    if (false == sometrustLinkerTrusts) {
        this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "no trust between "
                + childCertificate.getSubjectX500Principal() + " and " + certificate.getSubjectX500Principal());
        throw new CertPathValidatorException(this.result.getMessage());
    }
}