Example usage for java.security.cert X509Certificate getPublicKey

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

Introduction

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

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:net.sf.keystore_explorer.gui.actions.GenerateCsrAction.java

/**
 * Do action./* w  ww .j a va 2  s . c o  m*/
 */
@Override
protected void doAction() {
    File csrFile = null;
    FileOutputStream fos = null;

    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();
        Provider provider = history.getExplicitProvider();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());

        String keyPairAlg = privateKey.getAlgorithm();
        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        if (keyPairType == null) {
            throw new CryptoException(MessageFormat
                    .format(res.getString("GenerateCsrAction.NoCsrForKeyPairAlg.message"), keyPairAlg));
        }

        // determine dir of current keystore as proposal for CSR file location
        String path = CurrentDirectory.get().getAbsolutePath();
        File keyStoreFile = history.getFile();
        if (keyStoreFile != null) {
            path = keyStoreFile.getAbsoluteFile().getParent();
        }

        DGenerateCsr dGenerateCsr = new DGenerateCsr(frame, alias, privateKey, keyPairType, path, provider);
        dGenerateCsr.setLocationRelativeTo(frame);
        dGenerateCsr.setVisible(true);

        if (!dGenerateCsr.generateSelected()) {
            return;
        }

        CsrType format = dGenerateCsr.getFormat();
        SignatureType signatureType = dGenerateCsr.getSignatureType();
        String challenge = dGenerateCsr.getChallenge();
        String unstructuredName = dGenerateCsr.getUnstructuredName();
        boolean useCertificateExtensions = dGenerateCsr.isAddExtensionsWanted();
        csrFile = dGenerateCsr.getCsrFile();

        X509Certificate firstCertInChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)))[0];

        fos = new FileOutputStream(csrFile);

        if (format == CsrType.PKCS10) {
            String csr = Pkcs10Util.getCsrEncodedDerPem(Pkcs10Util.generateCsr(firstCertInChain, privateKey,
                    signatureType, challenge, unstructuredName, useCertificateExtensions, provider));

            fos.write(csr.getBytes());
        } else {
            SpkacSubject subject = new SpkacSubject(
                    X500NameUtils.x500PrincipalToX500Name(firstCertInChain.getSubjectX500Principal()));
            PublicKey publicKey = firstCertInChain.getPublicKey();

            // TODO handle other providers (PKCS11 etc)
            Spkac spkac = new Spkac(challenge, signatureType, subject, publicKey, privateKey);

            spkac.output(fos);
        }
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("GenerateCsrAction.NoWriteFile.message"), csrFile),
                res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("GenerateCsrAction.CsrGenerationSuccessful.message"),
            res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:net.link.util.test.pkix.PkiTestUtils.java

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        PrivateKey issuerPrivateKey, @Nullable X509Certificate issuerCert, DateTime notBefore,
        DateTime notAfter, @Nullable String signatureAlgorithm, boolean includeAuthorityKeyIdentifier,
        boolean caCert, boolean timeStampingPurpose, @Nullable URI ocspUri)
        throws IOException, CertificateException, OperatorCreationException {

    String finalSignatureAlgorithm = signatureAlgorithm;
    if (null == signatureAlgorithm)
        finalSignatureAlgorithm = "SHA512WithRSAEncryption";

    X509Principal issuerDN;//  www . ja va2  s.  c o  m
    if (null != issuerCert)
        issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().toString());
    else
        issuerDN = new X509Principal(subjectDn);

    // new bc 2.0 API
    X509Principal subject = new X509Principal(subjectDn);
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    BigInteger serialNumber = new BigInteger(SERIALNUMBER_NUM_BITS, new SecureRandom());

    X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
            X500Name.getInstance(issuerDN.toASN1Primitive()), serialNumber, notBefore.toDate(),
            notAfter.toDate(), X500Name.getInstance(subject.toASN1Primitive()), publicKeyInfo);

    // prepare signer
    ContentSigner signer = new JcaContentSignerBuilder(finalSignatureAlgorithm).build(issuerPrivateKey);

    // add extensions
    certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    if (null != issuerCert)
        issuerPublicKey = issuerCert.getPublicKey();
    else
        issuerPublicKey = subjectPublicKey;
    if (includeAuthorityKeyIdentifier)
        certificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                createAuthorityKeyId(issuerPublicKey));

    certificateBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(caCert));

    if (timeStampingPurpose)
        certificateBuilder.addExtension(X509Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier,
                new DERIA5String(ocspUri.toString()));
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateBuilder.addExtension(X509Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    // build
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateBuilder.build(signer));
}

From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java

/**
 *  ?     ? ?  ?? ?_1 //from   w w w. jav  a 2 s  . c  o m
 * ?    ? ?
 *
 * @param signers
 * @param clientCerts
 * @return
 * @throws CertStoreException
 */
private boolean checkNucOneCertificateType(SignerInformationStore signers, CertStore clientCerts)
        throws CertStoreException {

    Iterator it = signers.getSigners().iterator();
    boolean result = false;
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertSelector signerConstraints = signer.getSID();
        Collection certCollection = clientCerts.getCertificates(signerConstraints);
        Iterator certIt = certCollection.iterator();
        if (certCollection.size() == 0) {
            throw new RuntimeException(
                    "    ?  ? .");
        }
        while (certIt.hasNext()) {
            X509Certificate userCert = (X509Certificate) certIt.next();
            X509Certificate certForCheck = null;
            boolean isMyVersion = false;
            try {
                if (TypeOfRespondent.FIRM.equals(typeOfRespondent)) {
                    X509Certificate certNuc1Gost = (X509Certificate) createCerificate_nuc1_gost();
                    userCert.verify(certNuc1Gost.getPublicKey(), providerName);
                    certForCheck = certNuc1Gost;
                } else {
                    X509Certificate certNuc1Rsa = (X509Certificate) createCerificate_nuc1_rsa();
                    userCert.verify(certNuc1Rsa.getPublicKey(), providerName);
                    certForCheck = certNuc1Rsa;
                }

                isMyVersion = true;
            } catch (Exception ex) {
                //  ? ? ?  ? 1
                result = false;
            }
            if (isMyVersion) { // ?   ? ?  ?? ?_1  
                try {
                    certForCheck.checkValidity(); // ? ? ?
                } catch (CertificateExpiredException ex) {
                    throw new RuntimeException(
                            " ? ? ? 1.0,   ? ? 1.0  ? ??");
                } catch (CertificateNotYetValidException ex) {
                    throw new RuntimeException(
                            " ? ? ? 1.0,   ? ? 1.0   ?.");
                }
                try {
                    if (isNotRevokedCertNucOne(userCert)) { // ? ? ?
                        return true;
                    } else {
                        throw new RuntimeException(
                                "C ?   .");
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex.getMessage());
                }
            }
        }
    }
    return result;
}

From source file:be.fedict.trust.PublicKeyTrustLinker.java

public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData) {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }/* w  w  w  .j a  v a  2  s.  c o  m*/
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }
    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate not a CA");
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate
            .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData) {
        LOG.debug("child certificate is CA and MUST contain an Authority Key Identifier");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {

        AuthorityKeyIdentifierStructure authorityKeyIdentifierStructure;
        try {
            authorityKeyIdentifierStructure = new AuthorityKeyIdentifierStructure(authorityKeyIdentifierData);
        } catch (IOException e) {
            LOG.debug("Error parsing authority key identifier structure");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "Error parsing authority key identifier structure");
        }
        String akidId = new String(Hex.encodeHex(authorityKeyIdentifierStructure.getKeyIdentifier()));

        SubjectKeyIdentifierStructure subjectKeyIdentifierStructure;
        try {
            subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(subjectKeyIdentifierData);
        } catch (IOException e) {
            LOG.debug("Error parsing subject key identifier structure");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "Error parsing subject key identifier structure");
        }
        String skidId = new String(Hex.encodeHex(subjectKeyIdentifierStructure.getKeyIdentifier()));

        if (!skidId.equals(akidId)) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    return null;
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Returns a {@code Certificate} with the received data.
 *
 * @param keypair/*from w  w w .  ja  v a  2  s  .co  m*/
 *            key pair for the certificate
 * @param issuer
 *            issuer for the certificate
 * @return a {@code Certificate} with the received data
 * @throws IOException
 *             if there is an I/O or format problem with the certificate
 *             data
 * @throws OperatorCreationException
 *             if there was a problem creation a bouncy castle operator
 * @throws CertificateException
 *             if any of the certificates in the keystore could not be
 *             loaded
 * @throws InvalidKeyException
 *             if there was a problem with the key
 * @throws NoSuchAlgorithmException
 *             if an algorithm required to create the key store could not be
 *             found
 * @throws NoSuchProviderException
 *             if a required provider is missing
 * @throws SignatureException
 *             if any problem occurs while signing the certificate
 */
private final Certificate getCertificate(final KeyPair keypair, final String issuer)
        throws IOException, OperatorCreationException, CertificateException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    final X509v3CertificateBuilder builder; // Certificate builder
    final X509Certificate certificate; // Certificate

    // Generates the certificate builder
    builder = getCertificateBuilder(keypair.getPublic(), issuer);

    // Generates the signed certificate
    certificate = getSignedCertificate(builder, keypair.getPrivate());

    // Verifies the certificate
    certificate.checkValidity(getCurrentDate());
    certificate.verify(keypair.getPublic());

    LOGGER.debug("Created certificate of type {} with encoded value {}", certificate.getType(),
            Arrays.asList(certificate.getEncoded()));
    LOGGER.debug("Created certificate with public key:{}", certificate.getPublicKey());

    return certificate;
}

From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java

/**
 *  ?     ? ?  ?? ?_2 /*from w  w  w .  j a va2  s  .c om*/
 * ?    ? ?
 *
 * @param signers
 * @param clientCerts
 * @return
 * @throws CertStoreException
 */
private boolean checkNucTwoCertificateType(SignerInformationStore signers, CertStore clientCerts)
        throws CertStoreException {
    Iterator it = signers.getSigners().iterator();
    boolean result = false;
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertSelector signerConstraints = signer.getSID();
        Collection certCollection = clientCerts.getCertificates(signerConstraints);
        Iterator certIt = certCollection.iterator();
        //System.out.println(  );
        if (certCollection.size() == 0) {
            throw new RuntimeException(
                    "    ?  ? .");
        }
        while (certIt.hasNext()) {
            X509Certificate userCert = (X509Certificate) certIt.next();
            boolean isMyVersion = false;
            X509Certificate certForCheck = null;
            try {
                if (TypeOfRespondent.FIRM.equals(typeOfRespondent)) {
                    X509Certificate certNuc2Gost = (X509Certificate) createCerificate_nuc2_gost();
                    X509Certificate certKucGost = (X509Certificate) createCerificate_kuc_gost();
                    userCert.verify(certNuc2Gost.getPublicKey(), providerName);
                    certNuc2Gost.verify(certKucGost.getPublicKey(), providerName);
                    certForCheck = certNuc2Gost;
                } else {
                    X509Certificate certNuc2Rsa = (X509Certificate) createCerificate_nuc2_rsa();
                    X509Certificate certKucRsa = (X509Certificate) createCerificate_kuc_rsa();
                    userCert.verify(certNuc2Rsa.getPublicKey(), providerName);
                    certNuc2Rsa.verify(certKucRsa.getPublicKey(), providerName);
                    certForCheck = certNuc2Rsa;
                }

                isMyVersion = true;
            } catch (Exception ex) {
                result = false;

            }
            if (isMyVersion) { // ?   ? ?  ?? ?_1  
                try {
                    certForCheck.checkValidity();
                } catch (CertificateExpiredException ex) {
                    throw new RuntimeException(
                            " ? ? ? 2.0,   ? ? 2.0  ? ??");
                } catch (CertificateNotYetValidException ex) {
                    throw new RuntimeException(
                            " ? ? ? 2.0,   ? ? 2.0   ?.");
                }

                try {
                    if (isNotRevokedCertNucTwo(userCert)) {
                        result = true;
                        return true;
                    } else {
                        throw new RuntimeException(
                                "C ?   .");
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex.getMessage());
                }
            }

        }
    }
    return result;
}

From source file:be.fedict.trust.linker.PublicKeyTrustLinker.java

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }/* ww w.ja  va  2 s.  c  om*/
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }

    algorithmPolicy.checkSignatureAlgorithm(childCertificate.getSigAlgOID(), validationDate);

    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA: " + certificate.getSubjectX500Principal());
        /*
         * http://www.valicert.com/ Root CA has no CA flag set. Actually
         * this is in violation with 4.2.1.10 Basic Constraints of RFC2459.
         */
        try {
            certificate.verify(certificate.getPublicKey());
            LOG.warn("allowing self-signed Root CA without CA flag set");
        } catch (Exception e) {
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "certificate not a CA");
        }
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(Extension.authorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData && null != subjectKeyIdentifierData) {
        LOG.error("child certificate is CA and MUST contain an Authority Key Identifier");
        // return new TrustLinkerResult(false,
        // TrustLinkerResultReason.INVALID_TRUST,
        // "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {
        AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdentifierData));
        SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdentifierData));
        if (!Arrays.equals(authorityKeyIdentifier.getKeyIdentifier(),
                subjectKeyIdentifier.getKeyIdentifier())) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    /*
     * Keep in mind that this trust linker can never return TRUSTED.
     */
    return TrustLinkerResult.UNDECIDED;
}

From source file:net.link.util.common.KeyUtils.java

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        PrivateKey issuerPrivateKey, @Nullable X509Certificate issuerCert, DateTime notBefore,
        DateTime notAfter, String inSignatureAlgorithm, boolean caCert, boolean timeStampingPurpose,
        @Nullable URI ocspUri) {/*  w w w  . java2s .c  om*/

    try {
        String signatureAlgorithm = inSignatureAlgorithm;
        if (null == signatureAlgorithm)
            signatureAlgorithm = String.format("SHA1With%s", issuerPrivateKey.getAlgorithm());

        X509Principal issuerDN;
        if (null != issuerCert)
            issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().toString());
        else
            issuerDN = new X509Principal(subjectDn);

        // new bc 2.0 API
        X509Principal subject = new X509Principal(subjectDn);
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
        BigInteger serialNumber = new BigInteger(SERIALNUMBER_NUM_BITS, new SecureRandom());

        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
                X500Name.getInstance(issuerDN.toASN1Primitive()), serialNumber, notBefore.toDate(),
                notAfter.toDate(), X500Name.getInstance(subject.toASN1Primitive()), publicKeyInfo);

        // prepare signer
        ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(issuerPrivateKey);
        certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                createSubjectKeyId(subjectPublicKey));
        PublicKey issuerPublicKey;
        if (null != issuerCert)
            issuerPublicKey = issuerCert.getPublicKey();
        else
            issuerPublicKey = subjectPublicKey;
        certificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                createAuthorityKeyId(issuerPublicKey));

        certificateBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(caCert));

        if (timeStampingPurpose)
            certificateBuilder.addExtension(X509Extension.extendedKeyUsage, true,
                    new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));

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

        // build
        return new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certificateBuilder.build(signer));
    } catch (CertificateException e) {
        throw new InternalInconsistencyException("X.509 is not supported.", e);
    } catch (OperatorCreationException e) {
        throw new InternalInconsistencyException(e);
    } catch (CertIOException e) {
        throw new InternalInconsistencyException(e);
    }
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

protected void checkCRL(X509Certificate cert, CertificateRevocationLists crlsList,
        TrustedCertificates trustedCerts) throws ProxyPathValidatorException {
    if (crlsList == null) {
        return;//from w  w w.j av  a 2 s .  co m
    }

    logger.debug("checkCRLs: enter");
    // Should not happen, just a sanity check.
    if (trustedCerts == null) {
        String err = "Trusted certificates are null, cannot verify CRLs";
        logger.error(err);
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, null, err);
    }

    String issuerName = cert.getIssuerDN().getName();
    X509CRL crl = crlsList.getCrl(issuerName);
    if (crl == null) {
        logger.debug("No CRL for certificate");
        return;
    }

    // get CA cert for the CRL
    X509Certificate x509Cert = trustedCerts.getCertificate(issuerName);
    if (x509Cert == null) {
        // if there is no trusted certs from that CA, then
        // the chain cannot contain a cert from that CA,
        // which implies not checking this CRL should be fine.
        logger.debug("No trusted cert with this CA signature");
        return;
    }

    // validate CRL
    try {
        crl.verify(x509Cert.getPublicKey());
    } catch (Exception exp) {
        logger.error("CRL verification failed");
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, exp);
    }

    Date now = new Date();
    // check date validity of CRL
    if ((crl.getThisUpdate().before(now))
            || ((crl.getNextUpdate() != null) && (crl.getNextUpdate().after(now)))) {
        if (crl.isRevoked(cert)) {
            throw new ProxyPathValidatorException(ProxyPathValidatorException.REVOKED, cert,
                    "This cert " + cert.getSubjectDN().getName() + " is on a CRL");
        }
    }

    logger.debug("checkCRLs: exit");
}

From source file:eu.europa.ec.markt.dss.validation.crl.OnlineCRLSource.java

@Override
public X509CRL findCrl(final X509Certificate cert, final X509Certificate issuerCert) throws DSSException {

    final String crlURL = getCrlUri(cert);
    LOG.info("CRL's URL for " + CertificateIdentifier.getIdAsString(cert) + " : " + crlURL);
    if (crlURL == null) {

        return null;
    }//from  ww  w .j a va2s  .com
    X509CRL x509CRL;
    boolean http = crlURL.startsWith("http://") || crlURL.startsWith("https://");
    if (dataLoader != null && http) {

        x509CRL = downloadCrlFromHTTP(crlURL);
    } else if (http || crlURL.startsWith("ftp://")) {

        x509CRL = downloadCRLFromURL(crlURL);
    } else if (crlURL.startsWith("ldap://")) {

        x509CRL = downloadCRLFromLDAP_(crlURL);
    } else {

        LOG.warning("DSS framework only supports HTTP, HTTPS, FTP and LDAP CRL's url.");
        return null;
    }
    if (x509CRL == null) {

        return null;
    }
    try {

        x509CRL.verify(issuerCert.getPublicKey());
    } catch (Exception e) {

        LOG.warning("The CRL signature is not valid!");
        return null;
    }
    // assert CRLSign KeyUsage bit
    final boolean[] keyUsage = issuerCert.getKeyUsage();
    if (keyUsage == null || (keyUsage != null && !keyUsage[6])) {

        LOG.warning("No KeyUsage extension for CRL issuing certificate!");
        return null;
    }
    return x509CRL;
}