Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. ...
  2. KeyStore loadKeyStore (String ksFile, String pwd) {
  3.    try {
  4.       KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
  5.       InputStream stream = new FileInputStream( ksFile );
  6.      
  7.       /** verify the integrity of a keystore */
  8.       ks.load( stream, pwd.toCharArray() );
  9.    } catch (Exception ex) {
  10.       ex.printStackTrace();
  11.    }
  12. }
  13.  
  14. void storeKeyStore (KeyStore ks, String ksFile, String pwd) {
  15.    try {
  16.       OutputStream stream = new FileOutputStream(ksFile);
  17.       ks.store( stream, pwd.toCharArray() );
  18.    } catch (Exception ex) {
  19.        ex.printStackTrace();
  20.    }
  21. }
  22.  
  23. void printKeyEntry (KeyStore ks, String alias, String pwd) {
  24.    System.out.println( "Private key: " + ks.getKey(alias,pwd.toCharArray() );
  25.    Certificate certs[] = ks.getCertificateChain(alias);
  26.    for (int i = 0; i < certs.length; i++) {
  27.       if (c intanceof X509Certificate) {
  28.          X509Certificate c = (X509Certificate) certs[i];
  29.          System.out.println(
  30.             "Subject DN: " + c.getSubjectDN() + ", Issuer DN: " + c.getIssuerDN()
  31.          );
  32.       }
  33.    }
  34. }
  35.  
  36. void printCertificateEntry (KeyStore ks, String alias) {
  37.    Certificate c = ks.getCertificate(alias);
  38.    if (c instanceof X509Certificate) {
  39.       X509Certificate x509 = (X509Certificate) c;
  40.       System.out.println(
  41.          "Subject DN: " + x509.getSubjectDN() "Issuer DN: " + x509.getIssuerDN()
  42.       );
  43.    }
  44. }
  45.  
  46. public static void main (String[] args) {
  47.    String ksFile = System.getProperty("user.home")
  48.       + File.separator + ".keystore";
  49.      
  50.    KeyStore ks = loadKeyStore( ksFile, "secret password" );
  51.    String alias = "edek";
  52.    if ( ks.isKeyEntry(alias) ) {
  53.       printKeyEntry(
  54.          ks,alias, "my very secret password protecting private key"
  55.       );
  56.    } else if ( ks.isCertificateEntry(alias) ) {
  57.       printCertificateEntry( ks,alias );
  58.    } else {
  59.       System.out.println(
  60.          "There is no entry for the alias: \"" + alias + "\" in the keystore"
  61.       );
  62.    }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement