Example usage for java.security.cert Certificate getType

List of usage examples for java.security.cert Certificate getType

Introduction

In this page you can find the example usage for java.security.cert Certificate getType.

Prototype

public final String getType() 

Source Link

Document

Returns the type of this certificate.

Usage

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private void checkValidity() throws SecureLocalStorageException {
    try {/*from   w  ww .java 2 s  .  c  o  m*/
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);

        if (keyStore.containsAlias(SECURELOCALSTORAGEALIAS)) {
            Certificate c = keyStore.getCertificate(SECURELOCALSTORAGEALIAS);
            if (c.getType().equals("X.509")) {
                ((X509Certificate) c).checkValidity();
            }
        }
    } catch (Exception e) {
        throw new SecureLocalStorageException(e.getMessage(), e);
    }
}

From source file:cz.hobrasoft.pdfmu.operation.OperationInspect.java

private Signature display(PdfPKCS7 pkcs7) {
    Signature signature = new Signature();

    // digitalsignatures20130304.pdf : Code sample 5.3
    to.println("Signature metadata:");
    {//from www  .j ava 2 s.  c  om
        SignatureMetadata metadata = new SignatureMetadata();

        to.indentMore();

        // Only name may be null.
        // The values are set in {@link PdfPKCS7#verifySignature}.
        { // name
            String name = pkcs7.getSignName(); // May be null
            metadata.name = name;
            if (name == null) {
                to.println("Name is not set.");
            } else {
                to.println(String.format("Name: %s", name));
            }
        }

        // TODO?: Print "N/A" if the value is an empty string
        // TODO?: Determine whether the value is set in the signature
        to.println(String.format("Reason: %s", pkcs7.getReason()));
        metadata.reason = pkcs7.getReason();
        to.println(String.format("Location: %s", pkcs7.getLocation()));
        metadata.location = pkcs7.getLocation();

        { // Date
            Date date = pkcs7.getSignDate().getTime();
            to.println(String.format("Date and time: %s", date));
            metadata.date = date.toString();
        }

        to.indentLess();

        signature.metadata = metadata;
    }
    { // Certificate chain
        to.indentMore("Certificate chain:");
        Certificate[] certificates = pkcs7.getSignCertificateChain();
        to.println(String.format("Number of certificates: %d", certificates.length));
        int i = 0;
        List<CertificateResult> certificatesResult = new ArrayList<>();
        for (Certificate certificate : certificates) {
            to.indentMore(String.format("Certificate %d%s:", i, (i == 0 ? " (the signing certificate)" : "")));
            CertificateResult certRes;
            String type = certificate.getType();
            to.println(String.format("Type: %s", type));
            // http://docs.oracle.com/javase/1.5.0/docs/guide/security/CryptoSpec.html#AppA
            if ("X.509".equals(type)) {
                X509Certificate certificateX509 = (X509Certificate) certificate;
                certRes = showCertInfo(certificateX509);
            } else {
                certRes = new CertificateResult();
            }
            certRes.type = type;
            to.indentLess();
            certificatesResult.add(certRes);
            ++i;
        }
        signature.certificates = certificatesResult;
        to.indentLess();
    }

    return signature;
}

From source file:com.springcryptoutils.core.certificate.CertificateRegistryByAliasImplTest.java

@Test
public void testCertificateRegistryIsProperlyLoaded() {
    assertNotNull(registryByAlias);/*from  w w  w  . j a va  2s. c  om*/
    Certificate certificate1 = registryByAlias.get(new KeyStoreChooser() {
        public String getKeyStoreName() {
            return "keystoreOne";
        }
    }, new CertificateChooserByAlias() {
        public String getAlias() {
            return "test";
        }
    });
    Certificate certificate2 = registryByAlias.get(new KeyStoreChooser() {
        public String getKeyStoreName() {
            return "keystoreTwo";
        }
    }, new CertificateChooserByAlias() {
        public String getAlias() {
            return "test";
        }
    });
    assertNotNull(certificate1);
    assertNotNull(certificate2);
    assertEquals("cert type", "X.509", certificate1.getType());
    assertEquals("cert type", "X.509", certificate2.getType());
    assertSame(certificate1, certificate2);
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private List<Map<String, Object>> getKeyStoreInfo(KeyStore store) {
    List<Map<String, Object>> storeEntries = new ArrayList<>();
    try {/* w  w w  . j a  v  a 2 s .  c o m*/
        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            Map<String, Object> aliasMap = new HashMap<>();
            Certificate certificate = store.getCertificate(alias);
            boolean isKey = store.isKeyEntry(alias);
            aliasMap.put("alias", alias);
            aliasMap.put("isKey", isKey);
            aliasMap.put("type", certificate.getType());
            aliasMap.put("format", certificate.getPublicKey().getFormat());
            aliasMap.put("algorithm", certificate.getPublicKey().getAlgorithm());
            storeEntries.add(aliasMap);
        }
    } catch (KeyStoreException e) {
        LOGGER.error("Unable to read entries from keystore.", e);
    }
    return storeEntries;
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Returns a JsonValue map representing a certificate
 * /*from  ww w . j  a  va  2 s  .  com*/
 * @param alias  the certificate alias
 * @param cert  The certificate
 * @return a JsonValue map representing the certificate
 * @throws Exception
 */
protected JsonValue returnCertificate(String alias, Certificate cert) throws Exception {
    JsonValue content = new JsonValue(new LinkedHashMap<String, Object>());
    content.put(ResourceResponse.FIELD_CONTENT_ID, alias);
    content.put("type", cert.getType());
    content.put("cert", getCertString(cert));
    content.put("publicKey", getKeyMap(cert.getPublicKey()));
    if (cert instanceof X509Certificate) {
        Map<String, Object> issuer = new HashMap<>();
        X500Name name = X500Name.getInstance(PrincipalUtil.getIssuerX509Principal((X509Certificate) cert));
        addAttributeToIssuer(issuer, name, "C", BCStyle.C);
        addAttributeToIssuer(issuer, name, "ST", BCStyle.ST);
        addAttributeToIssuer(issuer, name, "L", BCStyle.L);
        addAttributeToIssuer(issuer, name, "OU", BCStyle.OU);
        addAttributeToIssuer(issuer, name, "O", BCStyle.O);
        addAttributeToIssuer(issuer, name, "CN", BCStyle.CN);
        content.put("issuer", issuer);
        content.put("notBefore", ((X509Certificate) cert).getNotBefore());
        content.put("notAfter", ((X509Certificate) cert).getNotAfter());
    }
    return content;
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

private void logCertificateContents(Certificate cert) {
    if (cert instanceof X509Certificate) {
        X509Certificate x509Cert = (X509Certificate) cert;
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug(" X509 Certificate :");
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Subject DN: " + x509Cert.getSubjectDN());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class)
                .debug("  Signature Algorithm: " + x509Cert.getSigAlgName());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class)
                .debug("  Signature: " + x509Cert.getPublicKey().toString());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Valid from: " + x509Cert.getNotBefore());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Valid until: " + x509Cert.getNotAfter());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Issuer: " + x509Cert.getIssuerDN());
    } else//from   ww  w .  j a v a 2 s  .  com
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug(" Certificate :" + cert.getType());
}

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

/**
 * Method to create certificate path and to check it's validity from a list of certificates.
 * The list of certificates should only contain one root certificate.
 *
 * @param certlist/*  w  w w  . jav a  2 s. c  o m*/
 * @return the certificatepath with the root CA at the end, either collection of Certificate or byte[] (der encoded certs)
 * @throws CertPathValidatorException if the certificate chain can not be constructed
 * @throws InvalidAlgorithmParameterException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws CertificateException 
 */
public static Collection<Certificate> createCertChain(Collection<?> certlistin)
        throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertificateException {
    ArrayList<Certificate> returnval = new ArrayList<Certificate>();

    Collection<Certificate> certlist = orderCertificateChain(certlistin);

    // set certificate chain
    Certificate rootcert = null;
    ArrayList<Certificate> calist = new ArrayList<Certificate>();
    Iterator<Certificate> iter = certlist.iterator();
    while (iter.hasNext()) {
        Certificate next = iter.next();
        if (CertTools.isSelfSigned(next)) {
            rootcert = next;
        } else {
            calist.add(next);
        }
    }

    if (calist.isEmpty()) {
        // only one root cert, no certchain
        returnval.add(rootcert);
    } else {
        // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator
        Certificate test = calist.get(0);
        if (test.getType().equals("CVC")) {
            if (calist.size() == 1) {
                returnval.add(test);
                returnval.add(rootcert);
            } else {
                throw new CertPathValidatorException(
                        "CVC certificate chain can not be of length longer than two.");
            }
        } else {
            // Normal X509 certificates
            HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>();
            TrustAnchor trustanchor = null;
            trustanchor = new TrustAnchor((X509Certificate) rootcert, null);
            trustancors.add(trustanchor);

            // Create the parameters for the validator
            PKIXParameters params = new PKIXParameters(trustancors);

            // Disable CRL checking since we are not supplying any CRLs
            params.setRevocationEnabled(false);
            params.setDate(new Date());

            // Create the validator and validate the path
            CertPathValidator certPathValidator = CertPathValidator
                    .getInstance(CertPathValidator.getDefaultType(), "BC");
            CertificateFactory fact = CertTools.getCertificateFactory();
            CertPath certpath = fact.generateCertPath(calist);

            CertPathValidatorResult result = certPathValidator.validate(certpath, params);

            // Get the certificates validate in the path
            PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
            returnval.addAll(certpath.getCertificates());

            // Get the CA used to validate this path
            TrustAnchor ta = pkixResult.getTrustAnchor();
            X509Certificate cert = ta.getTrustedCert();
            returnval.add(cert);
        }
    }
    return returnval;
}

From source file:homenetapp.HomeNetAppGui.java

private void checkClientCert() {
    try {/*from   w  w  w  .j  a  v a  2 s.  c  o m*/
        URL url = new URL("https://" + homenetapp.clientServer + "/");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.connect();
        Certificate[] certs = conn.getServerCertificates();

        //System.out.println("Cert Chain Length: "+certs.length);

        Certificate c = certs[0];
        X509Certificate xc = (X509Certificate) c;

        String[] from = homenetapp.splitTokens(xc.getIssuerX500Principal().getName(), "=, ");
        String[] to = homenetapp.splitTokens(xc.getSubjectX500Principal().getName(), "=, ");

        certPropertiesLabel.setText("<html>Issued by: " + from[1] + "<br>For: " + to[1] + "<br>Expires: "
                + xc.getNotAfter() + "</html>");

        System.out.println("Cert: " + c.getType());

        System.out.println("Not After: " + xc.getNotAfter());
        System.out.println("Subject DN: " + xc.getSubjectX500Principal());
        System.out.println("Issuer DN: " + xc.getIssuerX500Principal());
        System.out.println("getSigAlgName: " + xc.getSigAlgName());

    } catch (Exception e) {
        certPropertiesLabel.setText("Failed to load certficate");
    }

}

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

/**
 * Gets Serial number of the certificate.
 *
 * @param cert Certificate//from  www.ja  v  a2 s  . co  m
 *
 * @return BigInteger containing the certificate serialNumber. Can be 0 for CVC certificates with alphanumering serialnumbers if the sequence does not contain any number characters at all.
 */
public static BigInteger getSerialNumber(Certificate cert) {
    BigInteger ret = null;
    if (cert instanceof X509Certificate) {
        X509Certificate xcert = (X509Certificate) cert;
        ret = xcert.getSerialNumber();
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        // For CVC certificates the sequence field of the HolderReference is kind of a serial number,
        // but if can be alphanumeric which means it can not be made into a BigInteger
        CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        try {
            String sequence = cvccert.getCVCertificate().getCertificateBody().getHolderReference()
                    .getSequence();
            ret = getSerialNumberFromString(sequence);
        } catch (NoSuchFieldException e) {
            log.error("getSerialNumber: NoSuchFieldException: ", e);
            ret = BigInteger.valueOf(0);
        }
    } else {
        throw new IllegalArgumentException(
                "getSerialNumber: Certificate of type " + cert.getType() + " is not implemented");
    }
    return ret;
}