Example usage for java.security KeyStoreException KeyStoreException

List of usage examples for java.security KeyStoreException KeyStoreException

Introduction

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

Prototype

public KeyStoreException(Throwable cause) 

Source Link

Document

Creates a KeyStoreException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.hyperic.hq.security.server.session.DbKeystoreManagerImpl.java

/**
 * reason for REQUIRES_NEW here is HHQ-4185, spring transaction manager
 * doesn't upgrade session when it comes across a rw transaction from a ro
 * transactional context//from   w  w  w.  j  ava 2s. c  o m
 */
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void create(String alias, String type, Certificate cert, Certificate[] chain) throws KeyStoreException {
    final KeystoreEntryImpl keystoreEntry = new KeystoreEntryImpl();
    keystoreEntry.setAlias(alias);
    keystoreEntry.setType(type);
    try {
        keystoreEntry.setCertificate(cert);
        keystoreEntry.setCertificateChain(chain);
    } catch (IOException ioe) {
        throw new KeyStoreException(ioe);
    } // EO catch block
    dbKeystoreDao.save(keystoreEntry);
}

From source file:org.opensc.pkcs11.spi.PKCS11KeyStoreSpi.java

@Override
public void engineDeleteEntry(String name) throws KeyStoreException {
    throw new KeyStoreException("deleteEntry is unimplemented.");
}

From source file:org.nuxeo.common.codec.Crypto.java

/**
 * Extract secret keys from a keystore looking for {@code keyAlias + algorithm}
 *
 * @param keystorePath Path to the keystore
 * @param keystorePass Keystore password
 * @param keyAlias Key alias prefix. It is suffixed with the algorithm.
 * @param keyPass Key password//from w ww . j a  va 2  s. com
 * @throws GeneralSecurityException
 * @throws IOException
 * @see #IMPLEMENTED_ALGOS
 */
public static Map<String, SecretKey> getKeysFromKeyStore(String keystorePath, char[] keystorePass,
        String keyAlias, char[] keyPass) throws GeneralSecurityException, IOException {
    KeyStore keystore = KeyStore.getInstance("JCEKS");
    try (InputStream keystoreStream = new FileInputStream(keystorePath)) {
        keystore.load(keystoreStream, keystorePass);
    }
    Map<String, SecretKey> secretKeys = new HashMap<>();
    for (String algo : IMPLEMENTED_ALGOS) {
        if (keystore.containsAlias(keyAlias + algo)) {
            SecretKey key = (SecretKey) keystore.getKey(keyAlias + algo, keyPass);
            secretKeys.put(algo, key);
        }
    }
    if (secretKeys.isEmpty()) {
        throw new KeyStoreException(String.format("No alias \"%s<algo>\" found in %s", keyAlias, keystorePath));
    }
    return secretKeys;
}

From source file:org.taverna.server.master.worker.SecurityContextDelegate.java

/**
 * Adds a credential to the current keystore.
 * //from   w  ww  .  ja va2  s.c o m
 * @param alias
 *            The alias to create within the keystore.
 * @param c
 *            The key-pair.
 * @throws KeyStoreException
 */
protected final void addKeypairToKeystore(String alias, Credential c) throws KeyStoreException {
    if (c.loadedKey == null)
        throw new KeyStoreException("critical: credential was not verified");
    if (uriToAliasMap.containsKey(c.serviceURI))
        log.warn("duplicate URI in alias mapping: " + c.serviceURI);
    keystore.addKey(alias, c.loadedKey, c.loadedTrustChain);
    uriToAliasMap.put(c.serviceURI, alias);
}

From source file:mitm.common.security.KeyAndCertStoreImpl.java

/**
 * @See KeyAndCertStore.getKeyAndCertificate
 *//*  w w w .jav a  2s  . c om*/
@Override
public KeyAndCertificate getKeyAndCertificate(X509CertStoreEntry certStoreEntry)
        throws CertStoreException, KeyStoreException {
    KeyAndCertificate keyAndCertificate = null;

    if (certStoreEntry != null) {
        PrivateKey privateKey;

        try {
            privateKey = getPrivateKey(certStoreEntry);
        } catch (UnrecoverableKeyException e) {
            throw new KeyStoreException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new KeyStoreException(e);
        }

        keyAndCertificate = new KeyAndCertificateImpl(privateKey, certStoreEntry.getCertificate());
    }

    return keyAndCertificate;

}

From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java

private void getPFXTransacted(Collection<X509Certificate> certificates, char[] password, boolean includeRoot,
        OutputStream pfx) throws KeyStoreException {
    try {/* w w  w. ja  va2  s  . com*/
        KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

        keyStore.load(null);

        for (X509Certificate certificate : certificates) {
            if (certificate == null) {
                continue;
            }

            X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate);

            if (entry != null && entry.getCertificate() != null) {
                KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry);

                if (keyAndCertificate != null) {
                    if (!certificate.equals(keyAndCertificate.getCertificate())) {
                        throw new IllegalStateException("Certificate mismatch.");
                    }

                    X509Certificate[] chain = null;

                    /*
                     * Build a certificate chain so we add the chain (if valid)
                     */
                    try {
                        CertificatePathBuilder pathBuilder = pathBuilderFactory.createCertificatePathBuilder();

                        CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate);

                        X509Certificate root = null;

                        if (includeRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) {
                            TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult)
                                    .getTrustAnchor();

                            if (trustAnchor != null) {
                                root = trustAnchor.getTrustedCert();
                            }
                        }

                        CertPath certPath = pathBuilderResult.getCertPath();

                        if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) {
                            List<X509Certificate> completePath = new LinkedList<X509Certificate>();

                            for (Certificate fromPath : certPath.getCertificates()) {
                                if (!(fromPath instanceof X509Certificate)) {
                                    /*
                                     * only X509Certificates are supported
                                     */
                                    continue;
                                }

                                completePath.add((X509Certificate) fromPath);
                            }

                            if (root != null && includeRoot) {
                                completePath.add(root);
                            }

                            chain = new X509Certificate[completePath.size()];

                            chain = completePath.toArray(chain);
                        }
                    } catch (CertPathBuilderException e) {
                        logger.warn(
                                "Could not build a path. Message: " + ExceptionUtils.getRootCauseMessage(e));
                    }

                    if (ArrayUtils.getLength(chain) == 0) {
                        chain = new X509Certificate[] { certificate };
                    }

                    String alias = X509CertificateInspector.getThumbprint(certificate);

                    if (keyAndCertificate.getPrivateKey() != null) {
                        keyStore.setKeyEntry(alias, keyAndCertificate.getPrivateKey(), password, chain);
                    } else {
                        keyStore.setCertificateEntry(alias, certificate);
                    }
                }
            }
        }

        keyStore.store(pfx, password);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e);
    } catch (IOException e) {
        throw new KeyStoreException(e);
    } catch (CertStoreException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchProviderException e) {
        throw new NoSuchProviderRuntimeException(e);
    } catch (SecurityFactoryFactoryException e) {
        throw new KeyStoreException(e);
    }
}

From source file:org.apache.accumulo.test.util.CertUtils.java

static Certificate findCert(KeyStore keyStore) throws KeyStoreException {
    Enumeration<String> aliases = keyStore.aliases();
    Certificate cert = null;/*from ww w  . jav  a2 s  .  c  om*/
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isCertificateEntry(alias)) {
            if (cert == null) {
                cert = keyStore.getCertificate(alias);
            } else {
                log.warn("Found multiple certificates in keystore.  Ignoring " + alias);
            }
        }
    }
    if (cert == null) {
        throw new KeyStoreException("Could not find cert in keystore");
    }
    return cert;
}

From source file:org.apache.accumulo.test.util.CertUtils.java

static PrivateKey findPrivateKey(KeyStore keyStore, char[] keystorePassword)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    Enumeration<String> aliases = keyStore.aliases();
    PrivateKey key = null;//w ww. ja v  a 2s .com
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {
            if (key == null) {
                key = (PrivateKey) keyStore.getKey(alias, keystorePassword);
            } else {
                log.warn("Found multiple keys in keystore.  Ignoring " + alias);
            }
        }
    }
    if (key == null) {
        throw new KeyStoreException("Could not find private key in keystore");
    }
    return key;
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private KeyStore getKeyStore(String keyStorePath, String keyStorePassword)
        throws KeyStoreException, IOException {
    FileInputStream keyStoreFileInputStream = null;

    try {/*from   w  w  w .  j a va 2 s .  c  o m*/
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        File file = new File(keyStorePath);
        char[] password = null;

        if (!file.exists()) {
            // ...if file doesn't exist, and path was user specified throw IOException...
            if (StringUtils.hasText(keyStorePath)) {
                throw new IOException("User specified keystore [" + keyStorePath + "] does not exist.");
            }

            password = keyStorePassword.toCharArray();
        }

        // ...keystore file exist, so init the file input stream...
        keyStoreFileInputStream = new FileInputStream(file);

        keystore.load(keyStoreFileInputStream, password);

        return keystore;
    } catch (NoSuchAlgorithmException e) {
        // can't check integrity of keystore, if this happens we're kind of screwed
        // is there anything we can do to self heal this problem?
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        // there are some corrupted certificates in the keystore, a bad thing
        // is there anything we can do to self heal this problem?
        throw new KeyStoreException(e);
    } finally {
        if (keyStoreFileInputStream != null) {
            keyStoreFileInputStream.close();
            keyStoreFileInputStream = null;
        }
    }
}

From source file:mitm.common.tools.SMIME.java

private static void sign(MimeMessage source, KeyStore keyStore, String alias, String password,
        String digestAlgo, String outFile) throws Exception {
    if (StringUtils.isEmpty(alias)) {
        throw new MissingArgumentException("alias is missing.");
    }/*  w w  w.  java2  s . c  o m*/

    KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));

    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        throw new KeyStoreException("Key is not a PrivateKeyEntry.");
    }

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

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    PrivateKey key = privateKeyEntry.getPrivateKey();

    if (certificate == null) {
        throw new KeyStoreException("Entry does not have a certificate.");
    }

    if (key == null) {
        throw new KeyStoreException("Entry does not have a private key.");
    }

    SMIMESigningAlgorithm signingAlgorithm;

    if (StringUtils.isNotEmpty(digestAlgo)) {
        signingAlgorithm = SMIMESigningAlgorithm.fromName(digestAlgo);

        if (signingAlgorithm == null) {
            throw new IllegalArgumentException(digestAlgo + " is not a valid digest.");
        }
    } else {
        signingAlgorithm = SMIMESigningAlgorithm.SHA1WITHRSA;
    }

    SMIMEBuilder builder = new SMIMEBuilderImpl(source);

    builder.addCertificates(certificate);
    builder.addSigner(key, certificate, signingAlgorithm);

    builder.sign(SMIMESignMode.CLEAR);

    MimeMessage signed = builder.buildMessage();

    if (signed == null) {
        throw new SMIMEException("Message could not be signed");
    }

    MailUtils.writeMessage(signed, new File(outFile));
}