Example usage for java.security KeyStore aliases

List of usage examples for java.security KeyStore aliases

Introduction

In this page you can find the example usage for java.security KeyStore aliases.

Prototype

public final Enumeration<String> aliases() throws KeyStoreException 

Source Link

Document

Lists all the alias names of this keystore.

Usage

From source file:de.brendamour.jpasskit.signing.PKSigningInformationUtil.java

/**
 * Load all signing information necessary for pass generation from the filesystem or classpath.
 * //from ww  w  .j av a 2 s .  co m
 * @param pkcs12KeyStoreFilePath
 *            path to keystore (classpath or filesystem)
 * @param keyStorePassword
 *            Password used to access the key store
 * @param appleWWDRCAFilePath
 *            path to apple's WWDRCA certificate file (classpath or filesystem)
 * @return
 *        a {@link PKSigningInformation} object filled with all certificates from the provided files
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws UnrecoverableKeyException
 */
public PKSigningInformation loadSigningInformationFromPKCS12AndIntermediateCertificate(
        final String pkcs12KeyStoreFilePath, final String keyStorePassword, final String appleWWDRCAFilePath)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        NoSuchProviderException, UnrecoverableKeyException {

    KeyStore pkcs12KeyStore = loadPKCS12File(pkcs12KeyStoreFilePath, keyStorePassword);
    Enumeration<String> aliases = pkcs12KeyStore.aliases();

    PrivateKey signingPrivateKey = null;
    X509Certificate signingCert = null;

    // find the certificate
    while (aliases.hasMoreElements()) {
        String aliasName = aliases.nextElement();

        Key key = pkcs12KeyStore.getKey(aliasName, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            signingPrivateKey = (PrivateKey) key;
            Object cert = pkcs12KeyStore.getCertificate(aliasName);
            if (cert instanceof X509Certificate) {
                signingCert = (X509Certificate) cert;
                break;
            }
        }
    }

    X509Certificate appleWWDRCACert = loadDERCertificate(appleWWDRCAFilePath);
    return checkCertsAndReturnSigningInformationObject(signingPrivateKey, signingCert, appleWWDRCACert);
}

From source file:de.brendamour.jpasskit.signing.PKSigningInformationUtil.java

/**
 * Load all signing information necessary for pass generation using two input streams for the key store and the Apple WWDRCA certificate.
 * /*w  w  w .j  a v  a  2s  .c o m*/
 * The caller is responsible for closing the stream after this method returns successfully or fails.
 * 
 * @param pkcs12KeyStoreInputStream
 *            <code>InputStream</code> of the key store
 * @param keyStorePassword
 *            Password used to access the key store
 * @param appleWWDRCAFileInputStream
 *            <code>InputStream</code> of the Apple WWDRCA certificate.
 * @return Signing informatino necessary to sign a pass.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws UnrecoverableKeyException
 */
public PKSigningInformation loadSigningInformationFromPKCS12AndIntermediateCertificate(
        final InputStream pkcs12KeyStoreInputStream, final String keyStorePassword,
        final InputStream appleWWDRCAFileInputStream) throws IOException, NoSuchAlgorithmException,
        CertificateException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException {

    KeyStore pkcs12KeyStore = loadPKCS12File(pkcs12KeyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases = pkcs12KeyStore.aliases();

    PrivateKey signingPrivateKey = null;
    X509Certificate signingCert = null;

    while (aliases.hasMoreElements()) {
        String aliasName = aliases.nextElement();

        Key key = pkcs12KeyStore.getKey(aliasName, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            signingPrivateKey = (PrivateKey) key;
            Object cert = pkcs12KeyStore.getCertificate(aliasName);
            if (cert instanceof X509Certificate) {
                signingCert = (X509Certificate) cert;
                break;
            }
        }
    }

    X509Certificate appleWWDRCACert = loadDERCertificate(appleWWDRCAFileInputStream);
    return checkCertsAndReturnSigningInformationObject(signingPrivateKey, signingCert, appleWWDRCACert);
}

From source file:test.integ.be.e_contract.mycarenet.sts.EHealthCertificateTest.java

@Test
public void testReadCertificate() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    LOG.debug("eHealth PKCS12 path: " + this.config.getEHealthPKCS12Path());
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    keyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = keyStore.aliases();
    while (aliasesEnum.hasMoreElements()) {
        String alias = aliasesEnum.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
        LOG.debug("certificate: " + certificate);
        Certificate[] certificateChain = keyStore.getCertificateChain(alias);
        for (Certificate cert : certificateChain) {
            LOG.debug("certificate chain: " + cert);
        }//from  www. j a  v a2 s . co m
    }
}

From source file:test.integ.be.e_contract.mycarenet.sts.RequestFactoryTest.java

@Test
public void testCreateRequest() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*from w w  w.j  a  v  a2s. co m*/
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    RequestFactory requestFactory = new RequestFactory();

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element requestElement = requestFactory.createRequest(authnCertificate, eHealthPrivateKey,
            eHealthCertificate, attributes, attributeDesignators);

    assertNotNull(requestElement);

    LOG.debug("request: " + toString(requestElement));
}

From source file:AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from   w ww  .  j a  v a  2 s  .  co m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            Enumeration aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null) {
                    System.out.println("Certificate chain '" + alias + "':");
                    for (int c = 0; c < certs.length; c++) {
                        if (certs[c] instanceof X509Certificate) {
                            X509Certificate cert = (X509Certificate) certs[c];
                            System.out.println(" Certificate " + (c + 1) + ":");
                            System.out.println("  Subject DN: " + cert.getSubjectDN());
                            System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                            System.out.println("  Valid from: " + cert.getNotBefore());
                            System.out.println("  Valid until: " + cert.getNotAfter());
                            System.out.println("  Issuer: " + cert.getIssuerDN());
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            Enumeration aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                System.out.println("Trusted certificate '" + alias + "':");
                Certificate trustedcert = keystore.getCertificate(alias);
                if (trustedcert != null && trustedcert instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) trustedcert;
                    System.out.println("  Subject DN: " + cert.getSubjectDN());
                    System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                    System.out.println("  Valid from: " + cert.getNotBefore());
                    System.out.println("  Valid until: " + cert.getNotAfter());
                    System.out.println("  Issuer: " + cert.getIssuerDN());
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        e.printStackTrace();
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * @throws java.lang.Exception//from   w  w w  .  ja v a2  s . c o  m
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    // Just in case, add the BouncyCastle provider
    // It gets added from the CredentialManagerImpl constructor as well
    // but we may need some crypto operations before we invoke the Cred. Manager 
    Security.addProvider(new BouncyCastleProvider());

    // Create a test username and password for a service
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {

        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub

        }
    };
}

From source file:gui.configurar.GerarAssinatura.java

String assinar() {
    String senha = tSenha.getText();
    String c = tContribuinte.getText() + tDev.getText();
    if (certificado == null) {
        Msg.show("Escolha o certificado");
        return "";
    }/* w  w w . j a va  2  s  . c  om*/
    try {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new FileInputStream(certificado), senha.toCharArray());
        ArrayList<String> apelidos = new ArrayList<String>();
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            apelidos.add(aliases.nextElement());
        }
        PrivateKey key = (PrivateKey) keystore.getKey(apelidos.get(0), senha.toCharArray());
        Signature assinatura = Signature.getInstance("SHA256withRSA");
        assinatura.initSign(key);
        byte[] bytes = c.getBytes();
        assinatura.update(bytes);
        byte[] assinado = assinatura.sign();
        String strAssinado = Base64.encodeBase64String(assinado);
        return strAssinado;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:test.integ.be.e_contract.mycarenet.cxf.EHealthSTSClientTest.java

@Test
public void testClient() throws Exception {
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*  w  w  w .  java  2  s  .  c om*/
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertionElement = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertionElement);

    LOG.debug("assertion: " + toString(assertionElement));

    LOG.debug("not after: " + client.getNotAfter(assertionElement));
}

From source file:org.commonjava.util.jhttpc.it.AbstractIT.java

@Test
public void decodeSiteCertificatePems() throws Exception {
    String pem = getServerCertsPem();
    KeyStore store = SSLUtils.decodePEMTrustStore(pem, "somehost");
    Enumeration<String> aliases = store.aliases();
    while (aliases.hasMoreElements()) {
        System.out.println(aliases.nextElement());
    }/*from   w  ww  . j ava 2  s  .c om*/
}