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.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java

public KeyStore generateClientKeystore(String alias, String clientPassphrase) throws GeneralSecurityException {
    if (isAliasInKeystore(alias)) {
        throw new KeyStoreException("Alias '" + alias + "' already exists in module keystore");
    }//from  www . j a  v a2  s  . c o  m
    //        Certificate[] clientCertificateChain = {};
    //        PrivateKey clientPrivateKey = null;
    KeyStore ks = null;
    try {
        // generate a key pair for the client
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(CLIENT_KEY_GENERATOR_ALGORITHM);
        //            SecureRandom random = SecureRandom.getInstance(CLIENT_SECURE_RANDOM_ALGORITHM);
        keyGen.initialize(CLIENT_KEY_PAIR_KEY_SIZE);
        //            keyGen.initialize(new RSAKeyGenParameterSpec(512,RSAKeyGenParameterSpec.F0));
        KeyPair pair = keyGen.generateKeyPair();

        //            PublicKey clientPublicKey = pair.getPublic();
        //            clientPrivateKey = pair.getPrivate();
        //            // generate the Certificate
        //            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
        ////            X509Name nameInfo = new X509Name(false,"CN=" + alias);
        //            certificateGenerator.setSignatureAlgorithm("MD5WithRSA");
        //            certificateGenerator.setSerialNumber(new java.math.BigInteger("1"));
        //            X509Principal nameInfo = new X509Principal("CN=" + alias);
        //            certificateGenerator.setIssuerDN(nameInfo);
        //            certificateGenerator.setSubjectDN(nameInfo);                       // note: same as issuer
        //            certificateGenerator.setNotBefore(new Date());
        //            Calendar c = Calendar.getInstance();
        //            c.add(Calendar.DATE, CLIENT_CERT_EXPIRATION_DAYS);
        //            certificateGenerator.setNotAfter(c.getTime());
        //            certificateGenerator.setPublicKey(clientPublicKey);
        //            X509Certificate cert = certificateGenerator.generateX509Certificate(clientPrivateKey);
        //            clientCertificateChain = new Certificate[]{cert};
        //
        //            // generate client keyStore file
        //            ks = KeyStore.getInstance(getModuleKeyStoreType());
        //            ks.load(null, clientPassphrase.toCharArray());
        //            // set client private key on keyStore file
        //            ks.setEntry(alias, new KeyStore.PrivateKeyEntry(clientPrivateKey, clientCertificateChain), new KeyStore.PasswordProtection(clientPassphrase.toCharArray()));
        Certificate cert = generateCertificate(pair, alias);
        ks = generateKeyStore(cert, pair.getPrivate(), alias, clientPassphrase);

        // set the module certificate on the client keyStore file
        ks.setEntry(getModuleKeyStoreAlias(),
                new KeyStore.TrustedCertificateEntry(getCertificate(getModuleKeyStoreAlias())), null);

        // add the client certificate to the module keyStore
        addClientCertificateToModuleKeyStore(alias, cert);

        return ks;
    } catch (IOException e) {
        throw new RuntimeException("Could not create new KeyStore", e);
    }
}

From source file:org.hyperic.util.security.KeystoreManager.java

private void createInternalKeystore(KeystoreConfig keystoreConfig) throws KeyStoreException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String javaHome = System.getProperty("java.home");
    String keytool = javaHome + File.separator + "bin" + File.separator + "keytool";
    String[] args = { keytool, "-genkey", "-dname", getDName(keystoreConfig), "-alias",
            keystoreConfig.getAlias(), "-keystore", keystoreConfig.getFilePath(), "-storepass",
            keystoreConfig.getFilePassword(), "-keypass", keystoreConfig.getFilePassword(), "-keyalg", "RSA",
            "-validity", "3650" //10 years
    };/*from w  w  w  .j av  a 2 s . c o  m*/

    int timeout = 5 * 60 * 1000; //5min
    ExecuteWatchdog wdog = new ExecuteWatchdog(timeout);
    Execute exec = new Execute(new PumpStreamHandler(output), wdog);

    exec.setCommandline(args);

    //TODO shouldn't have password in log
    log.debug("Generating keystore: " + keystoreConfig.getFilePath());

    int rc;

    try {
        rc = exec.execute();
    } catch (Exception e) {
        rc = -1;
        log.error(e);
    }

    if (rc != 0) {
        String msg = output.toString().trim();

        if (msg.length() == 0) {
            msg = "timeout after " + timeout + "ms";
        }

        // TODO This is super fugly but considering how we're creating the keystore file, there isn't a clean way of accomplishing this
        //      Basically, there is a small window of opportunity where two agent processes could discover no keystore file and try to
        //      generate one using the ExceuteWatchdog.  One will succeed, the other will fail, if that happens we shouldn't kill the process.  
        //      For any other exception throw it...
        if (!msg.toLowerCase().contains("key pair not generated, alias <"
                + keystoreConfig.getAlias().toLowerCase() + "> already exists")) {
            //can't have password in log
            throw new KeyStoreException("Failed to create keystore:" + keystoreConfig.getAlias() + ", " + msg);
        }
    }
}

From source file:SignatureInfos.java

private KeyStore getKeystore() throws KeyStoreException {
    try {//from w  ww.  j av a 2  s  .  c om
        final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        //InputStream is = this.getClass().getResourceAsStream("/key.keystore");      
        //ks.load(is, getKeystorePassword().toCharArray());
        ks.load(new FileInputStream(getKeystoreFile()), getKeystorePassword().toCharArray());
        return ks;
    } catch (final NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (final CertificateException e) {
        throw new KeyStoreException(e);
    } catch (final FileNotFoundException e) {
        throw new KeyStoreException(e);
    } catch (final IOException e) {
        throw new KeyStoreException(e);
    }
}

From source file:de.thorstenberger.examServer.pdf.signature.SignatureInfos.java

private KeyStore getKeystore() throws KeyStoreException {
    try {//from   w ww.  j  a  v  a  2s  .  co  m
        final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(getKeystoreFile()), getKeystorePassword().toCharArray());
        return ks;
    } catch (final NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (final CertificateException e) {
        throw new KeyStoreException(e);
    } catch (final FileNotFoundException e) {
        throw new KeyStoreException(e);
    } catch (final IOException e) {
        throw new KeyStoreException(e);
    }
}

From source file:org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthorityFragment.java

private boolean editAuthority(final String old_alias, final String new_alias, final int position,
        final String uri) {
    try {/*w ww . j ava 2 s  .  co  m*/
        final KeyStore ks = SettingsSmartPGPAuthoritiesActivity.readKeystore(getContext());

        if (ks == null) {
            throw new KeyStoreException("no keystore found");
        }

        Certificate old_cert = null;
        if (old_alias != null) {
            old_cert = ks.getCertificate(old_alias);
            ks.deleteEntry(old_alias);
            mAuthorities.remove(old_alias);
            mAdapter.notifyItemRemoved(position);
        }

        Certificate new_cert = null;
        if (uri == null) {
            new_cert = old_cert;
        } else {
            final InputStream fis = getContext().getContentResolver().openInputStream(Uri.parse(uri));

            final CertificateFactory cf = CertificateFactory.getInstance("X.509");
            new_cert = cf.generateCertificate(fis);
            if (!(new_cert instanceof X509Certificate)) {
                Notify.create(getActivity(), "Invalid certificate", Notify.LENGTH_LONG, Notify.Style.ERROR)
                        .show();
                return false;
            }

            fis.close();
        }

        if (new_alias == null || new_cert == null) {
            Notify.create(getActivity(), "Missing alias or certificate", Notify.LENGTH_LONG, Notify.Style.ERROR)
                    .show();
            return false;
        }

        final X509Certificate x509cert = (X509Certificate) new_cert;

        x509cert.checkValidity();

        ks.setCertificateEntry(new_alias, x509cert);

        SettingsSmartPGPAuthoritiesActivity.writeKeystore(getContext(), ks);

        mAuthorities.add(new_alias);
        mAdapter.notifyItemInserted(mAuthorities.size() - 1);

        return true;

    } catch (IOException e) {
        Notify.create(getActivity(), "failed to open certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    } catch (CertificateException e) {
        Notify.create(getActivity(), "invalid certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    } catch (KeyStoreException e) {
        Notify.create(getActivity(), "invalid keystore (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    }

    return false;
}

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

@Override
public void getPFX(final Collection<X509Certificate> certificates, final char[] password,
        final boolean includeRoot, final OutputStream pfx) throws KeyStoreException {
    Check.notNull(certificates, "certificates");
    Check.notNull(password, "password");

    try {/*from  ww  w. j a va2s  .c o  m*/
        getActionExecutor().executeTransaction(new DatabaseVoidAction() {
            @Override
            public void doAction(Session session) throws DatabaseException {
                try {
                    Session previousSession = getSessionManager().getSession();

                    getSessionManager().setSession(session);

                    try {
                        getPFXTransacted(certificates, password, includeRoot, pfx);
                    } finally {
                        /* restore the session */
                        getSessionManager().setSession(previousSession);
                    }
                } catch (KeyStoreException e) {
                    throw new DatabaseException(e);
                }
            }
        });
    } catch (DatabaseException e) {
        Throwable cause = e.getCause();

        if (cause == null) {
            cause = e;
        }

        if (cause instanceof KeyStoreException) {
            throw (KeyStoreException) cause;
        }

        throw new KeyStoreException(cause);
    }
}

From source file:mitm.common.security.keystore.hibernate.SerializableKeyEntry.java

/**
 * Returns a unprotected key. If the key is a protected key (ie. Protection != NONE) a KeyStoreException
 * will be thrown.//w ww. ja v a 2 s .c  o  m
 * 
 * @return the key
 * @throws KeyStoreException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public Key getKey()
        throws KeyStoreException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
    if (protection != Protection.NONE) {
        throw new KeyStoreException("This entry is protected.");
    }

    return getKey(rawKey);
}

From source file:mitm.common.security.keystore.hibernate.SerializableKeyEntry.java

/**
 * Returns a password protected key.//from w  w w. j ava  2  s.  co  m
 * 
 * @param password the password used to decrypt the key.
 * @param decryptor the decryptor used to decrypt the key. If null it is assumed that the 
 * key is not password protected
 * 
 * @return the key
 * @throws KeyStoreException
 * @throws InvalidKeyException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws NoSuchPaddingException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws IOException 
 */
public Key getKey(char[] password, PBEncryption decryptor) throws KeyStoreException, InvalidKeyException,
        InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        IllegalBlockSizeException, BadPaddingException, IOException {
    if (protection != Protection.ENCRYPTED) {
        throw new KeyStoreException("This entry is not an encrypted entry.");
    }

    if (decryptor == null) {
        throw new KeyStoreException("The decryptor should not be null.");
    }

    byte[] decryptedKey = decryptor.decrypt(rawKey, password);

    return getKey(decryptedKey);
}

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

@Override
public void engineSetKeyEntry(String name, Key key, char[] pin, Certificate[] certificateChain)
        throws KeyStoreException {
    throw new KeyStoreException("setKeyEntry is unimplmented.");
}

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

@Override
public void engineSetKeyEntry(String name, byte[] pin, Certificate[] certificateChain)
        throws KeyStoreException {
    throw new KeyStoreException("setKeyEntry is unimplmented.");
}