Example usage for java.security.cert X509Certificate getIssuerDN

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

Introduction

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

Prototype

public abstract Principal getIssuerDN();

Source Link

Document

Denigrated, replaced by #getIssuerX500Principal() .

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    List mylist = new ArrayList();

    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);//from   w ww .  java2s. c om

    CertPath cp = cf.generateCertPath(mylist);

    FileInputStream kin = new FileInputStream(args[0]);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(kin, args[1].toCharArray());

    PKIXParameters params = new PKIXParameters(ks);
    params.setRevocationEnabled(false);

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);

    PublicKey pbk = result.getPublicKey();
    byte[] pkenc = pbk.getEncoded();
    BigInteger pk = new BigInteger(pkenc);
    System.out.println(pk.toString(16));

    TrustAnchor anc = result.getTrustAnchor();
    X509Certificate xc = anc.getTrustedCert();
    System.out.println(xc.getSubjectDN());
    System.out.println(xc.getIssuerDN());

}

From source file:CAList.java

/**
 * <p><!-- Method description --></p>
 *
 *
 * @param args/*from   ww w  .  j a v a  2 s  .c  om*/
 */
public static void main(String[] args) {
    try {
        // Load the JDK's cacerts keystore file
        String filename = System.getProperty("java.home")
                + "/lib/security/cacerts".replace('/', File.separatorChar);
        FileInputStream is = new FileInputStream(filename);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "changeit";
        keystore.load(is, password.toCharArray());

        // This class retrieves the most-trusted CAs from the keystore
        PKIXParameters params = new PKIXParameters(keystore);

        // Get the set of trust anchors, which contain the most-trusted CA certificates
        Iterator it = params.getTrustAnchors().iterator();
        for (; it.hasNext();) {
            TrustAnchor ta = (TrustAnchor) it.next();

            // Get certificate
            X509Certificate cert = ta.getTrustedCert();
            System.out.println("<issuer>" + cert.getIssuerDN() + "</issuer>\n");
        }
    } catch (CertificateException e) {
    } catch (KeyStoreException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidAlgorithmParameterException e) {
    } catch (IOException e) {
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    FileInputStream fr = new FileInputStream("sdo.cer");
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    X509Certificate c = (X509Certificate) cf.generateCertificate(fr);
    System.out.println("\tCertificate for: " + c.getSubjectDN());
    System.out.println("\tCertificate issued by: " + c.getIssuerDN());
    System.out.println("\tThe certificate is valid from " + c.getNotBefore() + " to " + c.getNotAfter());
    System.out.println("\tCertificate SN# " + c.getSerialNumber());
    System.out.println("\tGenerated with " + c.getSigAlgName());
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    java.security.cert.Certificate c = cf.generateCertificate(in);
    in.close();//from  www  . j  a va  2s .  com

    X509Certificate t = (X509Certificate) c;
    System.out.println(t.getVersion());
    System.out.println(t.getSerialNumber().toString(16));
    System.out.println(t.getSubjectDN());
    System.out.println(t.getIssuerDN());
    System.out.println(t.getNotBefore());
    System.out.println(t.getNotAfter());
    System.out.println(t.getSigAlgName());
    byte[] sig = t.getSignature();
    System.out.println(new BigInteger(sig).toString(16));
    PublicKey pk = t.getPublicKey();
    byte[] pkenc = pk.getEncoded();
    for (int i = 0; i < pkenc.length; i++) {
        System.out.print(pkenc[i] + ",");
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    Enumeration e = keystore.aliases();
    for (; e.hasMoreElements();) {
        String alias = (String) e.nextElement();

        java.security.cert.Certificate cert = keystore.getCertificate(alias);
        if (cert instanceof X509Certificate) {
            X509Certificate x509cert = (X509Certificate) cert;

            // Get subject
            Principal principal = x509cert.getSubjectDN();
            String subjectDn = principal.getName();

            // Get issuer
            principal = x509cert.getIssuerDN();
            String issuerDn = principal.getName();
        }//from  w  w w  .ja va2 s.co m
    }
}

From source file:org.rhq.enterprise.server.plugins.rhnhosted.RHNSSLCertReader.java

static public void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Please re-run and specify an argument for the location of a RHN SSL Cert.");
        System.exit(0);//from  w  w  w  . jav a  2s . co m
    }
    String path = args[0];
    System.out.println("path is " + path);
    String rawCert = null;
    try {
        rawCert = FileUtils.readFileToString(new File(path));
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }
    List<String> certs = RHNSSLCertReader.getCertText(rawCert);
    for (String cert : certs) {
        System.out.println("Parsed SSL Certificate: \n" + cert);
    }

    List<X509Certificate> sslCerts = new ArrayList<X509Certificate>();
    try {
        sslCerts = getSSLCertificates(rawCert);
    } catch (CertificateException e) {
        e.printStackTrace();
        System.exit(0);
    }
    for (X509Certificate c : sslCerts) {
        System.out.println("Cert SigAlgName = " + c.getSigAlgName());
        System.out.println("Cert IssuerDN = " + c.getIssuerDN());
        System.out.println("Cert NotAfter = " + c.getNotAfter());
        System.out.println("Cert NotBefore = " + c.getNotBefore());
        System.out.println("Cert PublicKey = " + c.getPublicKey());
        System.out.println("Cert SubjectDN = " + c.getSubjectDN());
    }
}

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * /* w  w  w  . j a v  a2 s  .  co m*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

    String hostName = "hostName";
    String fileName = "fileName";

    SSLSocket sslsock = (SSLSocket) factory.createSocket(hostName, 443);

    SSLSession session = sslsock.getSession();
    X509Certificate cert;
    try {//from   w  w  w.  j  av  a  2s. c o  m
        cert = (X509Certificate) session.getPeerCertificates()[0];
    } catch (SSLPeerUnverifiedException e) {
        System.err.println(session.getPeerHost() + " did not present a valid certificate.");
        return;
    }

    System.out.println(session.getPeerHost() + " has presented a certificate belonging to:");
    Principal p = cert.getSubjectDN();
    System.out.println("\t[" + p.getName() + "]");
    System.out.println("The certificate bears the valid signature of:");
    System.out.println("\t[" + cert.getIssuerDN().getName() + "]");

    System.out.print("Do you trust this certificate (y/n)? ");
    System.out.flush();
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    if (Character.toLowerCase(console.readLine().charAt(0)) != 'y')
        return;

    PrintWriter out = new PrintWriter(sslsock.getOutputStream());

    out.print("GET " + fileName + " HTTP/1.0\r\n\r\n");
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
        System.out.println(line);

    sslsock.close();
}

From source file:org.apache.xml.security.keys.storage.implementations.CertsInFilesystemDirectoryResolver.java

/**
 * Method main//from   w  w  w.  j  a  v  a  2  s .  c  o  m
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {

    CertsInFilesystemDirectoryResolver krs = new CertsInFilesystemDirectoryResolver(
            "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs");

    for (Iterator<Certificate> i = krs.getIterator(); i.hasNext();) {
        X509Certificate cert = (X509Certificate) i.next();
        byte[] ski = org.apache.xml.security.keys.content.x509.XMLX509SKI.getSKIBytesFromCert(cert);

        System.out.println();
        System.out.println("Base64(SKI())=                 \"" + Base64.encode(ski) + "\"");
        System.out.println("cert.getSerialNumber()=        \"" + cert.getSerialNumber().toString() + "\"");
        System.out.println("cert.getSubjectDN().getName()= \"" + cert.getSubjectDN().getName() + "\"");
        System.out.println("cert.getIssuerDN().getName()=  \"" + cert.getIssuerDN().getName() + "\"");
    }
}

From source file:Main.java

protected static boolean isSelfIssued(X509Certificate cert) {
    return cert.getSubjectDN().equals(cert.getIssuerDN());
}