Example usage for java.security UnrecoverableKeyException getMessage

List of usage examples for java.security UnrecoverableKeyException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.continuent.tungsten.common.security.KeystoreManagerCtrl.java

/**
 * Password Manager entry point/* w  w w  .j ava 2  s  .  c  o m*/
 * 
 * @param argv
 * @throws Exception
 */
public static void main(String argv[]) throws Exception {
    keystoreManager = new KeystoreManagerCtrl();

    // --- Options ---
    CommandLine line = null;

    try {
        CommandLineParser parser = new GnuParser();
        // --- Parse the command line arguments ---

        // --- Help
        line = parser.parse(keystoreManager.helpOptions, argv, true);
        if (line.hasOption(_HELP)) {
            DisplayHelpAndExit(EXIT_CODE.EXIT_OK);
        }

        // --- Program command line options
        line = parser.parse(keystoreManager.options, argv);

        // --- Compulsory arguments : Get options ---
        if (line.hasOption(_KEYSTORE_LOCATION))
            keystoreManager.keystoreLocation = line.getOptionValue(_KEYSTORE_LOCATION);

        if (line.hasOption(_KEY_ALIAS))
            keystoreManager.keyAlias = line.getOptionValue(_KEY_ALIAS);

        if (line.hasOption(_KEY_TYPE)) {
            String keyType = line.getOptionValue(_KEY_TYPE);
            // This will throw an exception if the type is not recognised
            KEYSTORE_TYPE certificateTYpe = KEYSTORE_TYPE.fromString(keyType);
            keystoreManager.keyType = certificateTYpe;
        }

        if (line.hasOption(_KEYSTORE_PASSWORD))
            keystoreManager.keystorePassword = line.getOptionValue(_KEYSTORE_PASSWORD);
        if (line.hasOption(_KEY_PASSWORD))
            keystoreManager.keyPassword = line.getOptionValue(_KEY_PASSWORD);

    } catch (ParseException exp) {
        logger.error(exp.getMessage());
        DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR);
    } catch (Exception e) {
        // Workaround for Junit test
        if (e.toString().contains("CheckExitCalled")) {
            throw e;
        } else
        // Normal behaviour
        {
            logger.error(e.getMessage());
            Exit(EXIT_CODE.EXIT_ERROR);
        }

    }

    // --- Perform commands ---

    // ######### Check password ##########
    if (line.hasOption(_CHECK)) {
        try {
            if (keystoreManager.keystorePassword == null || keystoreManager.keyPassword == null) {
                // --- Get passwords from stdin if not given on command line
                List<String> listPrompts = Arrays.asList("Keystore password:",
                        MessageFormat.format("Password for key {0}:", keystoreManager.keyAlias));
                List<String> listUserInput = keystoreManager.getUserInputFromStdin(listPrompts);

                if (listUserInput.size() == listPrompts.size()) {
                    keystoreManager.keystorePassword = listUserInput.get(0);
                    keystoreManager.keyPassword = listUserInput.get(1);
                } else {
                    throw new NoSuchElementException();
                }
            }
            try {
                // --- Check that all keys in keystore use the keystore
                // password
                logger.info(MessageFormat.format("Using keystore:{0}", keystoreManager.keystoreLocation));

                SecurityHelper.checkKeyStorePasswords(keystoreManager.keystoreLocation, keystoreManager.keyType,
                        keystoreManager.keystorePassword, keystoreManager.keyAlias,
                        keystoreManager.keyPassword);
                logger.info(MessageFormat.format("OK : Identical password for Keystore and key={0}",
                        keystoreManager.keyAlias));
            } catch (UnrecoverableKeyException uke) {
                logger.error(MessageFormat.format("At least 1 key has a wrong password.{0}", uke.getMessage()));
                Exit(EXIT_CODE.EXIT_ERROR);
            } catch (Exception e) {
                logger.error(MessageFormat.format("{0}", e.getMessage()));
                Exit(EXIT_CODE.EXIT_ERROR);
            }

        } catch (NoSuchElementException nse) {
            logger.error(nse.getMessage());
            Exit(EXIT_CODE.EXIT_ERROR);
        } catch (Exception e) {
            logger.error(MessageFormat.format("Error while running the program: {0}", e.getMessage()));
            Exit(EXIT_CODE.EXIT_ERROR);
        }
    }

    Exit(EXIT_CODE.EXIT_OK);
}

From source file:org.pepstock.jem.node.security.keystore.KeyStoreUtil.java

/**
 * Returns a SSL socket factory creating asymmetric keys at runtime.
 * //from w ww. j  av  a2  s .co m
 * @return a SSL socket factory for HTTPS listener 
 * @throws KeyStoreException if any errors occurs to get keys
 */
public static SSLServerSocketFactory getSSLServerSocketFactory() throws KeyStoreException {
    try {
        // gets a key stores created at runtime
        ByteArrayInputStream baos = SelfSignedCertificate.getCertificate();
        KeyStore keystore = KeyStore.getInstance("jks");
        // loads the keystore
        keystore.load(baos, SelfSignedCertificate.CERTIFICATE_PASSWORD.toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        // initialiazes the key manager
        kmfactory.init(keystore, SelfSignedCertificate.CERTIFICATE_PASSWORD.toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        // creates SSL socket factory
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        return sslcontext.getServerSocketFactory();
    } catch (UnrecoverableKeyException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (KeyManagementException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (SecurityException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (IOException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (OperatorCreationException e) {
        throw new KeyStoreException(e.getMessage(), e);
    }
}

From source file:org.pepstock.jem.node.security.keystore.KeyStoreUtil.java

/**
 * Generate an empty key store where will be store the X509 certificate of
 * the user/*from  ww w.  ja  va  2  s.  c o m*/
 * <p>
 * This key store will be used when the client will used a private key to
 * connect to the cluster and the cluster will used the relative public key
 * present in the x509 certificate to verify the identity of the client.
 * @param keystoreInfo entity with information about keystore
 * @throws KeyStoreException if any exception occurs during key store creation
 * 
 */
public static void generate(KeyStoreInfo keystoreInfo) throws KeyStoreException {
    try {
        // if the keystore exist load it else create a new one
        KeyStore keystore = null;
        if (keystoreInfo.getFile().exists()) {
            keystore = getKeystore(keystoreInfo);
        } else {
            keystore = KeyStore.getInstance(keystoreInfo.getType());
            keystore.load(null, null);
            save(keystore, keystoreInfo);
        }
        // if the keystore does not contain the given alias, create a new key
        // with that alias otherwise does nothing
        if (keystoreInfo.getSymmetricKeyAlias() != null && keystoreInfo.getSymmetricKeyPwd() != null
                && keystore.getKey(keystoreInfo.getSymmetricKeyAlias(),
                        keystoreInfo.getSymmetricKeyPwd().toCharArray()) == null) {
            // creates simmetricKey
            Key secretKey = Crypto.generateSymmetricKey();
            // adds the key
            keystore.setKeyEntry(keystoreInfo.getSymmetricKeyAlias(), secretKey,
                    keystoreInfo.getSymmetricKeyPwd().toCharArray(), null);
            // saves the keystore
            save(keystore, keystoreInfo);
        }
    } catch (UnrecoverableKeyException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (IOException e) {
        throw new KeyStoreException(e.getMessage(), e);
    }
}

From source file:org.viafirma.nucleo.validacion.KeyStoreLoader.java

/**
 * Recupera el clave privada del certificado con el alias indicado.
 * /*w ww.j  ava2s.  c o  m*/
 * @param alias
 * @param password
 * @return
 * @throws ExcepcionErrorInterno
 */
public static PrivateKey getPrivateKey(String alias, String password) throws ExcepcionErrorInterno {
    try {
        return (PrivateKey) loadDefaultKeyStore().getKey(alias,
                password == null ? null : password.toCharArray());
    } catch (UnrecoverableKeyException e) {
        throw new ExcepcionErrorInterno(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new ExcepcionErrorInterno(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new ExcepcionErrorInterno(e.getMessage(), e);
    } catch (ExcepcionErrorInterno e) {
        throw e;
    } catch (ClassCastException e) {
        throw new ExcepcionErrorInterno(
                "El alias indicado no pertenece a un certificado que tenga una clave privada almacenada.");
    }
}

From source file:com.appfirst.communication.AFHttpClient.java

public DefaultHttpClient getAFHttpClient() {
    try {// w  w  w .ja v a2s.co  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            trustStore.load(null, null);
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        SSLSocketFactory sf = new AFSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (NoSuchAlgorithmException nsae) {
        Log.e(TAG, nsae.getMessage());
        return new DefaultHttpClient();
    } catch (KeyManagementException kme) {
        Log.e(TAG, kme.getMessage());
        return new DefaultHttpClient();
    } catch (KeyStoreException kse) {
        Log.e(TAG, kse.getMessage());
        return new DefaultHttpClient();
    } catch (UnrecoverableKeyException uke) {
        Log.e(TAG, uke.getMessage());
        return new DefaultHttpClient();
    }
}

From source file:org.alfresco.extension.countersign.action.executer.ContentSignatureActionExecuter.java

@Override
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
    NodeService nodeService = serviceRegistry.getNodeService();
    ContentService contentService = serviceRegistry.getContentService();
    byte[] sigBytes;

    if (nodeService.exists(actionedUponNodeRef) == false) {
        return;/*from w w  w  .  j a v a2 s. com*/
    }

    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);

    // get a hash of the document
    InputStream contentStream = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT)
            .getContentInputStream();

    try {
        // get the user's private key
        String user = AuthenticationUtil.getRunAsUser();
        SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user);
        KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword);
        PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray());

        // compute the document hash
        byte[] hash = signatureProvider.computeHash(contentStream);

        // sign the hash
        sigBytes = signatureProvider.signHash(hash, keyPassword);

        // create a "signature" node and associate it with the signed doc
        NodeRef sig = addSignatureNodeAssociation(actionedUponNodeRef, location, reason, "none",
                new java.util.Date(), geolocation, -1, "none");

        // save the signature
        ContentWriter writer = contentService.getWriter(sig, ContentModel.PROP_CONTENT, true);
        writer.putContent(new ByteArrayInputStream(sigBytes));

        // also save the expected hash in the signature
        nodeService.setProperty(sig, CounterSignSignatureModel.PROP_DOCHASH, new String(hash));
    } catch (UnrecoverableKeyException uke) {
        throw new AlfrescoRuntimeException(uke.getMessage());
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlfrescoRuntimeException(nsae.getMessage());
    } catch (Exception e) {
        throw new AlfrescoRuntimeException(e.getMessage());
    }
}

From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java

private SecretKey getSecretKeyByDigest(String digest) throws EncryptionException {
    try {/*  w w w . ja  v a 2  s. co  m*/
        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (!keyStore.isKeyEntry(alias)) {
                continue;
            }

            try {
                Key key = keyStore.getKey(alias, KEY_PASSWORD);
                if (!(key instanceof SecretKey)) {
                    continue;
                }

                String keyHash = getSecretKeyDigest((SecretKey) key);
                if (digest.equals(keyHash)) {
                    return (SecretKey) key;
                }
            } catch (UnrecoverableKeyException ex) {
                LOGGER.trace("Couldn't recover key {} from keystore, reason: {}",
                        new Object[] { alias, ex.getMessage() });
            }
        }
    } catch (Exception ex) {
        throw new EncryptionException(ex.getMessage(), ex);
    }

    throw new EncryptionException("Key '" + digest + "' is not in keystore.");
}

From source file:org.codice.ddf.admin.insecure.defaults.service.KeystoreValidator.java

private void validateKeyPasswords(KeyStore keystore) {
    try {// ww w  . j  a  v  a  2s .co  m
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            if (keystore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)
                    || keystore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
                if (StringUtils.isNotBlank(defaultKeyPassword)) {
                    // See if we can access the key using the default key password. If we
                    // cannot, we
                    // know that we are using a non-default password.
                    Key key = keystore.getKey(alias, defaultKeyPassword.toCharArray());
                    if (key != null) {
                        alerts.add(new Alert(Level.WARN, String.format(DEFAULT_KEY_PASSWORD_USED_MSG, alias,
                                keystorePath, defaultKeyPassword)));
                    }
                } else {
                    alerts.add(new Alert(Level.WARN, String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath)
                            + "No key password provided."));
                }
            }
        }
    } catch (UnrecoverableKeyException e) {
        // Key is not using default key password.
    } catch (KeyStoreException | NoSuchAlgorithmException e) {
        LOGGER.warn(String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath), e);
        alerts.add(new Alert(Level.WARN,
                String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath) + e.getMessage() + "."));
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String)
 *//*ww  w  .  ja  v  a2 s.  c o m*/
public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile,
        final File keystoreFile, final String storePassword) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", commonName);
        DEBUGGER.debug("Value: {}", certificateFile);
        DEBUGGER.debug("Value: {}", keystoreFile);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final File certificateDirectory = FileUtils
            .getFile(certConfig.getCertificateDirectory() + "/" + commonName);
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName);

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("certificateDirectory: {}", certificateDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("certificateFile: {}", certificateFile);
        DEBUGGER.debug("keystoreFile: {}", keystoreFile);
    }

    boolean isComplete = false;
    FileInputStream certStream = null;
    FileOutputStream storeStream = null;
    FileInputStream keystoreInput = null;
    FileInputStream rootCertStream = null;
    FileInputStream intermediateCertStream = null;

    try {
        if (!(rootDirectory.exists())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(rootDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(certConfig.getRootCertificateFile().exists())) {
            throw new CertificateManagementException("Root certificate file does not exist. Cannot continue.");
        }

        if (!(certConfig.getIntermediateCertificateFile().exists())) {
            throw new CertificateManagementException(
                    "Intermediate certificate file does not exist. Cannot continue.");
        }

        if (!(storeDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Keystore directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(keystoreFile.canWrite())) {
            throw new CertificateManagementException(
                    "Unable to write to applicable keystore. Cannot continue.");
        }

        keystoreInput = FileUtils.openInputStream(keystoreFile);
        certStream = FileUtils.openInputStream(certificateFile);

        if (DEBUG) {
            DEBUGGER.debug("keystoreInput: {}", keystoreInput);
            DEBUGGER.debug("certStream: {}", certStream);
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keystoreInput, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray());
        CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

        if (DEBUG) {
            DEBUGGER.debug("CertificateFactory: {}", certFactory);
        }

        rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()));
        intermediateCertStream = FileUtils
                .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile()));

        if (DEBUG) {
            DEBUGGER.debug("rootCertStream: {}", rootCertStream);
            DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream);
        }

        X509Certificate[] responseCert = new X509Certificate[] {
                (X509Certificate) certFactory.generateCertificate(rootCertStream),
                (X509Certificate) certFactory.generateCertificate(intermediateCertStream),
                (X509Certificate) certFactory.generateCertificate(certStream) };

        if (DEBUG) {
            DEBUGGER.debug("X509Certificate[]", (Object) responseCert);
        }

        storeStream = FileUtils.openOutputStream(keystoreFile);
        keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert);
        keyStore.store(storeStream, storePassword.toCharArray());

        isComplete = true;
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } catch (UnrecoverableKeyException ukx) {
        throw new CertificateManagementException(ukx.getMessage(), ukx);
    } finally {
        if (storeStream != null) {
            IOUtils.closeQuietly(storeStream);
        }

        if (intermediateCertStream != null) {
            IOUtils.closeQuietly(intermediateCertStream);
        }

        if (rootCertStream != null) {
            IOUtils.closeQuietly(rootCertStream);
        }

        if (certStream != null) {
            IOUtils.closeQuietly(certStream);
        }

        if (keystoreInput != null) {
            IOUtils.closeQuietly(keystoreInput);
        }
    }

    return isComplete;
}