List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
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 ww .j a v a 2s. c om } }
From source file:Main.java
public static void main(String[] argv) throws Exception { FileInputStream is = new FileInputStream("yourfile" + ".keystore"); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = "my-keystore-password"; keystore.load(is, password.toCharArray()); Enumeration e = keystore.aliases(); for (; e.hasMoreElements();) { String alias = (String) e.nextElement(); boolean b = keystore.isKeyEntry(alias); b = keystore.isCertificateEntry(alias); }//from ww w . j a v a2s .c om is.close(); }
From source file:kellinwood.zipsigner.cmdline.Main.java
public static void main(String[] args) { try {// ww w . j a va 2s . c o m Options options = new Options(); CommandLine cmdLine = null; Option helpOption = new Option("h", "help", false, "Display usage information"); Option modeOption = new Option("m", "keymode", false, "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none"); modeOption.setArgs(1); Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file"); keyOption.setArgs(1); Option pwOption = new Option("p", "keypass", false, "Private key password"); pwOption.setArgs(1); Option certOption = new Option("c", "cert", false, "X.509 public key certificate file"); certOption.setArgs(1); Option sbtOption = new Option("t", "template", false, "Signature block template file"); sbtOption.setArgs(1); Option keystoreOption = new Option("s", "keystore", false, "Keystore file"); keystoreOption.setArgs(1); Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore"); aliasOption.setArgs(1); options.addOption(helpOption); options.addOption(modeOption); options.addOption(keyOption); options.addOption(certOption); options.addOption(sbtOption); options.addOption(pwOption); options.addOption(keystoreOption); options.addOption(aliasOption); Parser parser = new BasicParser(); try { cmdLine = parser.parse(options, args); } catch (MissingOptionException x) { System.out.println("One or more required options are missing: " + x.getMessage()); usage(options); } catch (ParseException x) { System.out.println(x.getClass().getName() + ": " + x.getMessage()); usage(options); } if (cmdLine.hasOption(helpOption.getOpt())) usage(options); Properties log4jProperties = new Properties(); log4jProperties.load(new FileReader("log4j.properties")); PropertyConfigurator.configure(log4jProperties); LoggerManager.setLoggerFactory(new Log4jLoggerFactory()); List<String> argList = cmdLine.getArgList(); if (argList.size() != 2) usage(options); ZipSigner signer = new ZipSigner(); signer.addAutoKeyObserver(new Observer() { @Override public void update(Observable observable, Object o) { System.out.println("Signing with key: " + o); } }); Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Provider bcProvider = (Provider) bcProviderClass.newInstance(); KeyStoreFileManager.setProvider(bcProvider); signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider"); PrivateKey privateKey = null; if (cmdLine.hasOption(keyOption.getOpt())) { if (!cmdLine.hasOption(certOption.getOpt())) { System.out.println("Certificate file is required when specifying a private key"); usage(options); } String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL(); privateKey = signer.readPrivateKey(privateKeyUrl, keypw); } X509Certificate cert = null; if (cmdLine.hasOption(certOption.getOpt())) { if (!cmdLine.hasOption(keyOption.getOpt())) { System.out.println("Private key file is required when specifying a certificate"); usage(options); } URL certUrl = new File(certOption.getValue()).toURI().toURL(); cert = signer.readPublicKey(certUrl); } byte[] sigBlockTemplate = null; if (cmdLine.hasOption(sbtOption.getOpt())) { URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL(); sigBlockTemplate = signer.readContentAsBytes(sbtUrl); } if (cmdLine.hasOption(keyOption.getOpt())) { signer.setKeys("custom", cert, privateKey, sigBlockTemplate); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption(modeOption.getOpt())) { signer.setKeymode(modeOption.getValue()); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption((keystoreOption.getOpt()))) { String alias = null; if (!cmdLine.hasOption(aliasOption.getOpt())) { KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null); for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { alias = e.nextElement(); System.out.println("Signing with key: " + alias); break; } } else alias = aliasOption.getValue(); String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(), "SHA1withRSA", argList.get(0), argList.get(1)); } else { signer.setKeymode("auto-testkey"); signer.signZip(argList.get(0), argList.get(1)); } } catch (Throwable t) { t.printStackTrace(); } }
From source file:PKCS12Import.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]"); System.exit(1);/*from ww w . j a v a 2s . c o m*/ } File fileIn = new File(args[0]); File fileOut; if (args.length > 1) { fileOut = new File(args[1]); } else { fileOut = new File("newstore.jks"); } if (!fileIn.canRead()) { System.err.println("Unable to access input keystore: " + fileIn.getPath()); System.exit(2); } if (fileOut.exists() && !fileOut.canWrite()) { System.err.println("Output file is not writable: " + fileOut.getPath()); System.exit(2); } KeyStore kspkcs12 = KeyStore.getInstance("pkcs12"); KeyStore ksjks = KeyStore.getInstance("jks"); System.out.print("Enter input keystore passphrase: "); char[] inphrase = readPassphrase(); System.out.print("Enter output keystore passphrase: "); char[] outphrase = readPassphrase(); kspkcs12.load(new FileInputStream(fileIn), inphrase); ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase); Enumeration eAliases = kspkcs12.aliases(); int n = 0; while (eAliases.hasMoreElements()) { String strAlias = (String) eAliases.nextElement(); System.err.println("Alias " + n++ + ": " + strAlias); if (kspkcs12.isKeyEntry(strAlias)) { System.err.println("Adding key for alias " + strAlias); Key key = kspkcs12.getKey(strAlias, inphrase); Certificate[] chain = kspkcs12.getCertificateChain(strAlias); ksjks.setKeyEntry(strAlias, key, outphrase, chain); } } OutputStream out = new FileOutputStream(fileOut); ksjks.store(out, outphrase); out.close(); }
From source file:createSod.java
/** * @param args// w w w . jav a 2 s .c om * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java
/** * For debuging only. Prints out keystore certificate chain. * * @param keystore Keystore to print out. * @throws KeyStoreException If the keystore is broken. *//*from w ww . java2s .co m*/ public static void printTrustCerts(KeyStore keystore) throws KeyStoreException { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); String message = "Trusted certificate '" + alias + "':"; Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; message += "\n Subject DN: " + cert.getSubjectDN(); message += "\n Signature Algorithm: " + cert.getSigAlgName(); message += "\n Valid from: " + cert.getNotBefore(); message += "\n Valid until: " + cert.getNotAfter(); message += "\n Issuer: " + cert.getIssuerDN(); } log.info(message); } }
From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java
/** * For debuging only. Prints out keystore certificate chain. * * @param keystore Keystore to print out. * @throws KeyStoreException If the keystore is broken. *//*from w ww . ja va2 s. c o m*/ public static void printKeyCertificates(KeyStore keystore) throws KeyStoreException { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { String message = "Certificate chain '" + alias + "':"; int i = 1; for (Certificate cert : certs) { if (cert instanceof X509Certificate) { X509Certificate Xcert = (X509Certificate) cert; message += "\n Certificate " + i++ + ":"; message += "\n Subject DN: " + Xcert.getSubjectDN(); message += "\n Signature Algorithm: " + Xcert.getSigAlgName(); message += "\n Valid from: " + Xcert.getNotBefore(); message += "\n Valid until: " + Xcert.getNotAfter(); message += "\n Issuer: " + Xcert.getIssuerDN(); } } log.info(message); } } }
From source file:com.cloudbees.jenkins.support.impl.RootCAs.java
public static void getRootCAList(StringWriter writer) { KeyStore instance = null; try {//from ww w . j a v a2s . co m instance = KeyStore.getInstance(KeyStore.getDefaultType()); Enumeration<String> aliases = instance.aliases(); while (aliases.hasMoreElements()) { String s = aliases.nextElement(); writer.append("========"); writer.append("Alias: " + s); writer.append(instance.getCertificate(s).getPublicKey().toString()); writer.append("Trusted certificate: " + instance.isCertificateEntry(s)); } } catch (KeyStoreException e) { writer.write(Functions.printThrowable(e)); } }
From source file:com.pieframework.runtime.utils.CertificateUtils.java
public static X509Certificate getCertificate(File certificateFile, String pass, String certAlias) { X509Certificate certificate = null; try {/*from w w w . j a v a 2 s .co m*/ FileInputStream cert = new FileInputStream(certificateFile); KeyStore pfxStore = KeyStore.getInstance("pkcs12"); pfxStore.load(cert, pass.toCharArray()); if (StringUtils.empty(certAlias) && pfxStore.size() > 0) { certAlias = pfxStore.aliases().nextElement(); } certificate = (X509Certificate) pfxStore.getCertificate(certAlias); cert.close(); } catch (Exception e) { e.printStackTrace(); } return certificate; }
From source file:mitm.common.tools.PfxTool.java
private static void printKeystoreDetails(KeyStore keyStore) throws KeyStoreException { Enumeration<String> aliases = keyStore.aliases(); int count = 0; System.out.println("**** BEGIN ENTRIES ***"); while (aliases.hasMoreElements()) { count++;/* w ww. j a v a 2 s . com*/ String alias = aliases.nextElement(); StrBuilder sb = new StrBuilder(); sb.append("Alias: ").append(alias).append(", key entry: ").append(keyStore.isKeyEntry(alias)); System.out.println(sb.toString()); } System.out.println("**** END ENTRIES ***"); System.out.println("Nr of entries: " + count); }