Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

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

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:org.apache.cxf.fediz.systests.oidc.OIDCTest.java

private void validateIdToken(String idToken, String audience)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    Assert.assertEquals("alice", jwt.getClaim("preferred_username"));
    Assert.assertEquals("accounts.fediz.com", jwt.getClaim(JwtConstants.CLAIM_ISSUER));
    Assert.assertEquals(audience, jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
    Assert.assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
    Assert.assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(Loader.getResource("oidc.jks").openStream(), "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    Assert.assertNotNull(cert);/*  w  w  w . j a va2s.  co m*/

    Assert.assertTrue(jwtConsumer.verifySignatureWith((X509Certificate) cert, SignatureAlgorithm.RS256));
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Get the Certificate Authority public key certificate
 * /*www .j a v a 2 s.  c  o m*/
 * @return
 */
private X509Certificate getCaCert(KeyStore trustedKs) {
    X509Certificate caCert = null;
    String certAlias = config.getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_CERT_ALIAS);

    try {
        caCert = (X509Certificate) trustedKs.getCertificate(certAlias);
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    }

    return caCert;
}

From source file:org.digidoc4j.impl.BDocContainerTest.java

static X509Certificate getSignerCert() {
    try {//from   ww w. j  ava 2  s. c  o  m
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (FileInputStream stream = new FileInputStream("testFiles/signout.p12")) {
            keyStore.load(stream, "test".toCharArray());
        }
        return (X509Certificate) keyStore.getCertificate("1");
    } catch (Exception e) {
        throw new DigiDoc4JException("Loading signer cert failed");
    }
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

private String findAliasForCert(KeyStore ks, Certificate cert) throws KeyStoreException {
    Enumeration e = ks.aliases();
    while (e.hasMoreElements()) {
        String alias = (String) e.nextElement();
        X509Certificate cert2 = (X509Certificate) ks.getCertificate(alias);
        if (cert2.equals(cert)) {
            return alias;
        }//  www  . j  av  a2s . co  m
    }
    return null;
}

From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java

/**
 * Returns an {@link X509CertificateHolder} containing the issuer of the given {@param name}.
 * Search is performed in the given {@param truststore}.
 *
 * @param name - the {@link X500Name} of the issuer.
 * @param truststore - the {@link KeyStore} to check.
 * @return {@link X509CertificateHolder} of the certificate with the given {@param name}.
 * @throws OcspCheckerException if the {@param name} cannot be found in the {@param truststore}.
 *//*from w  w  w .  ja v  a 2  s  . c  om*/
private X509CertificateHolder getCertFromTruststoreWithX500Name(X500Name name, KeyStore truststore)
        throws OcspCheckerException {
    Enumeration<String> aliases;

    try {
        aliases = truststore.aliases();
    } catch (KeyStoreException e) {
        throw new OcspCheckerException("Problem getting aliases from truststore." + NOT_VERIFIED_MSG, e);
    }

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

        try {
            java.security.cert.Certificate currentCert = truststore.getCertificate(currentAlias);
            X509CertificateHolder currentCertHolder = new X509CertificateHolder(currentCert.getEncoded());
            X500Name currentName = currentCertHolder.getSubject();
            if (name.equals(currentName)) {
                return currentCertHolder;
            }
        } catch (CertificateEncodingException | IOException | KeyStoreException e) {
            LOGGER.debug("Problem loading truststore certificate." + CONTINUING_MSG, e);
        }
    }

    throw new OcspCheckerException(
            String.format("Could not find cert matching X500Name of %s.", name) + NOT_VERIFIED_MSG);
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

/**
 * Integration test for automatic recovery of a {@link PrivateKey} instance.
 * <p/>/*from w  ww. jav a 2s. c  o m*/
 * Automatic recovery should work on the same eID card.
 * <p/>
 * When inserting another eID card however, the automatic recovery should
 * fail.
 * 
 * @throws Exception
 */
@Test
public void testAutoRecovery() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    keyStoreParameter.setAutoRecovery(true);
    keyStoreParameter.setCardReaderStickiness(true);
    keyStore.load(keyStoreParameter);

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    PublicKey authnPublicKey = keyStore.getCertificate("Authentication").getPublicKey();
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));

    JOptionPane.showMessageDialog(null, "Please remove/insert eID card...");

    signature.initSign(authnPrivateKey);
    signature.update(toBeSigned);
    signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:org.freebxml.omar.server.security.authentication.AuthenticationServiceImpl.java

private void loadPublicKeyToCertMap() throws RegistryException {
    try {//from  w  w  w.jav  a2 s. c o m
        KeyStore store = getKeyStore();

        for (Enumeration e = store.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            X509Certificate cert = (X509Certificate) store.getCertificate(alias);
            PublicKey publicKey = cert.getPublicKey();
            publicKeyToCertMap.put(publicKey, cert);
        }
    } catch (KeyStoreException e) {
        throw new RegistryException(e);
    }

}

From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandaloneTest.java

private Properties checkHostDirAndReturnNifiProperties(String hostname, String dnPrefix, String dnSuffix,
        X509Certificate rootCert) throws Exception {
    File hostDir = new File(tempDir, hostname);
    Properties nifiProperties = new Properties();
    try (InputStream inputStream = new FileInputStream(
            new File(hostDir, TlsToolkitStandalone.NIFI_PROPERTIES))) {
        nifiProperties.load(inputStream);
    }// w ww  . j a v  a  2s.c om

    String trustStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    assertEquals(KeystoreType.JKS.toString().toLowerCase(), trustStoreType.toLowerCase());
    KeyStore trustStore = KeyStoreUtils.getTrustStore(trustStoreType);
    try (InputStream inputStream = new FileInputStream(new File(hostDir, "truststore." + trustStoreType))) {
        trustStore.load(inputStream,
                nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD).toCharArray());
    }

    String trustStoreFilename = BaseCommandLine.TRUSTSTORE + trustStoreType;
    assertEquals("./conf/" + trustStoreFilename,
            nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));

    Certificate certificate = trustStore.getCertificate(TlsToolkitStandalone.NIFI_CERT);
    assertEquals(rootCert, certificate);

    String keyStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    String keyStoreFilename = BaseCommandLine.KEYSTORE + keyStoreType;
    File keyStoreFile = new File(hostDir, keyStoreFilename);
    assertEquals("./conf/" + keyStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE));

    KeyStore keyStore = KeyStoreUtils.getKeyStore(keyStoreType);
    char[] keyStorePassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray();
    try (InputStream inputStream = new FileInputStream(keyStoreFile)) {
        keyStore.load(inputStream, keyStorePassword);
    }

    char[] keyPassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEY_PASSWD).toCharArray();
    if (keyPassword == null || keyPassword.length == 0) {
        keyPassword = keyStorePassword;
    }

    KeyStore.Entry entry = keyStore.getEntry(TlsToolkitStandalone.NIFI_KEY,
            new KeyStore.PasswordProtection(keyPassword));
    assertEquals(KeyStore.PrivateKeyEntry.class, entry.getClass());

    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;

    Certificate[] certificateChain = privateKeyEntry.getCertificateChain();

    assertEquals(2, certificateChain.length);
    assertEquals(rootCert, certificateChain[1]);
    certificateChain[1].verify(rootCert.getPublicKey());
    certificateChain[0].verify(rootCert.getPublicKey());
    TlsConfig tlsConfig = new TlsConfig();
    tlsConfig.setDnPrefix(dnPrefix);
    tlsConfig.setDnSuffix(dnSuffix);
    assertEquals(tlsConfig.calcDefaultDn(hostname), CertificateUtils
            .convertAbstractX509Certificate(certificateChain[0]).getSubjectX500Principal().getName());
    TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(),
            certificateChain[0].getPublicKey());
    return nifiProperties;
}

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 {//from   w w  w .j  a  v  a2 s  .  c om
        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.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

@Override
public KeyPair getKeyPair(KeyStore ks, String keyAlias, String certAlias, String keyPassword)
        throws CertException {
    KeyPair keyPair = null;//from ww  w .  j  av  a 2  s  . c o  m
    try {
        if (!ks.containsAlias(keyAlias)) {
            throw new CertException("Missing keystore key entry for key alias:" + keyAlias);
        }
        if (!ks.containsAlias(certAlias)) {
            throw new CertException("Missing keystore certificate entry for :" + certAlias);
        }
        PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray());
        X509Certificate cert = (X509Certificate) ks.getCertificate(certAlias);
        PublicKey publicKey = cert.getPublicKey();
        keyPair = new KeyPair(publicKey, privateKey);
    } catch (UnrecoverableKeyException e) {
        throw new CertException(e);
    } catch (KeyStoreException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    }
    return keyPair;
}