Search in sources :

Example 6 with UnrecoverableEntryException

use of java.security.UnrecoverableEntryException in project bazel by bazelbuild.

the class KeystoreHelper method createNewStore.

/**
     * Creates a new store
     * @param osKeyStorePath the location of the store
     * @param storeType an optional keystore type, or <code>null</code> if the default is to
     * be used.
     * @param output an optional {@link IKeyGenOutput} object to get the stdout and stderr
     * of the keytool process call.
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws CertificateException
     * @throws UnrecoverableEntryException
     * @throws IOException
     * @throws KeytoolException
     */
public static boolean createNewStore(String osKeyStorePath, String storeType, String storePassword, String alias, String keyPassword, String description, int validityYears, final IKeyGenOutput output) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException, IOException, KeytoolException {
    // get the executable name of keytool depending on the platform.
    String os = System.getProperty("os.name");
    String keytoolCommand;
    if (os.startsWith("Windows")) {
        keytoolCommand = "keytool.exe";
    } else {
        keytoolCommand = "keytool";
    }
    String javaHome = System.getProperty("java.home");
    if (javaHome != null && !javaHome.isEmpty()) {
        keytoolCommand = javaHome + File.separator + "bin" + File.separator + keytoolCommand;
    }
    // create the command line to call key tool to build the key with no user input.
    ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(keytoolCommand);
    commandList.add("-genkey");
    commandList.add("-alias");
    commandList.add(alias);
    commandList.add("-keyalg");
    commandList.add("RSA");
    commandList.add("-dname");
    commandList.add(description);
    commandList.add("-validity");
    commandList.add(Integer.toString(validityYears * 365));
    commandList.add("-keypass");
    commandList.add(keyPassword);
    commandList.add("-keystore");
    commandList.add(osKeyStorePath);
    commandList.add("-storepass");
    commandList.add(storePassword);
    if (storeType != null) {
        commandList.add("-storetype");
        commandList.add(storeType);
    }
    String[] commandArray = commandList.toArray(new String[commandList.size()]);
    // launch the command line process
    int result = 0;
    try {
        Process process = Runtime.getRuntime().exec(commandArray);
        result = GrabProcessOutput.grabProcessOutput(process, Wait.WAIT_FOR_READERS, new IProcessOutput() {

            @Override
            public void out(@Nullable String line) {
                if (line != null) {
                    if (output != null) {
                        output.out(line);
                    } else {
                        System.out.println(line);
                    }
                }
            }

            @Override
            public void err(@Nullable String line) {
                if (line != null) {
                    if (output != null) {
                        output.err(line);
                    } else {
                        System.err.println(line);
                    }
                }
            }
        });
    } catch (Exception e) {
        // create the command line as one string for debugging purposes
        StringBuilder builder = new StringBuilder();
        boolean firstArg = true;
        for (String arg : commandArray) {
            boolean hasSpace = arg.indexOf(' ') != -1;
            if (firstArg == true) {
                firstArg = false;
            } else {
                builder.append(' ');
            }
            if (hasSpace) {
                builder.append('"');
            }
            builder.append(arg);
            if (hasSpace) {
                builder.append('"');
            }
        }
        throw new KeytoolException("Failed to create key: " + e.getMessage(), javaHome, builder.toString());
    }
    if (result != 0) {
        return false;
    }
    return true;
}
Also used : IProcessOutput(com.android.utils.GrabProcessOutput.IProcessOutput) KeytoolException(com.android.sdklib.internal.build.DebugKeyProvider.KeytoolException) ArrayList(java.util.ArrayList) Nullable(com.android.annotations.Nullable) KeytoolException(com.android.sdklib.internal.build.DebugKeyProvider.KeytoolException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableEntryException(java.security.UnrecoverableEntryException)

Example 7 with UnrecoverableEntryException

use of java.security.UnrecoverableEntryException in project OpenAM by OpenRock.

the class SoapSTSAgentCredentialsAccessImpl method decryptAgentPassword.

private String decryptAgentPassword(String encryptedAgentPassword, KeyStore soapSTSInternalKeystore) throws STSInitializationException {
    try {
        KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) soapSTSInternalKeystore.getEntry(SharedSTSConstants.AM_INTERNAL_PEK_ALIAS, new KeyStore.PasswordProtection(SharedSTSConstants.AM_INTERNAL_SOAP_STS_KEYSTORE_PW.toCharArray()));
        JCEEncryption jceEncryption = new JCEEncryption();
        final byte[] decodedPassword = Base64.decode(encryptedAgentPassword);
        try {
            jceEncryption.setPassword(new String(entry.getSecretKey().getEncoded(), StandardCharsets.UTF_8));
            final byte[] decryptedPassword = jceEncryption.decrypt(decodedPassword);
            return new String(decryptedPassword, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new STSInitializationException(ResourceException.INTERNAL_ERROR, e.getMessage(), e);
        }
    } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
        throw new STSInitializationException(ResourceException.INTERNAL_ERROR, e.getMessage(), e);
    }
}
Also used : JCEEncryption(com.iplanet.services.util.JCEEncryption) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) STSInitializationException(org.forgerock.openam.sts.STSInitializationException) KeyStoreException(java.security.KeyStoreException) ResourceException(org.forgerock.json.resource.ResourceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) STSInitializationException(org.forgerock.openam.sts.STSInitializationException) UnrecoverableEntryException(java.security.UnrecoverableEntryException)

Example 8 with UnrecoverableEntryException

use of java.security.UnrecoverableEntryException in project Resurrection_packages_apps_Settings by ResurrectionRemix.

the class CertInstallerHelper method extractCertificate.

private void extractCertificate(String certFile, String password) {
    InputStream in = null;
    final byte[] raw;
    java.security.KeyStore keystore = null;
    try {
        // Read .p12 file from SDCARD and extract with password
        in = new FileInputStream(new File(Environment.getExternalStorageDirectory(), certFile));
        raw = Streams.readFully(in);
        keystore = java.security.KeyStore.getInstance("PKCS12");
        PasswordProtection passwordProtection = new PasswordProtection(password.toCharArray());
        keystore.load(new ByteArrayInputStream(raw), passwordProtection.getPassword());
        // Install certificates and private keys
        Enumeration<String> aliases = keystore.aliases();
        if (!aliases.hasMoreElements()) {
            Assert.fail("key store failed to put in keychain");
        }
        ArrayList<String> aliasesList = Collections.list(aliases);
        // The keystore is initialized for each test case, there will
        // be only one alias in the keystore
        Assert.assertEquals(1, aliasesList.size());
        String alias = aliasesList.get(0);
        java.security.KeyStore.Entry entry = keystore.getEntry(alias, passwordProtection);
        Log.d(TAG, "extracted alias = " + alias + ", entry=" + entry.getClass());
        if (entry instanceof PrivateKeyEntry) {
            Assert.assertTrue(installFrom((PrivateKeyEntry) entry));
        }
    } catch (IOException e) {
        Assert.fail("Failed to read certficate: " + e);
    } catch (KeyStoreException e) {
        Log.e(TAG, "failed to extract certificate" + e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "failed to extract certificate" + e);
    } catch (CertificateException e) {
        Log.e(TAG, "failed to extract certificate" + e);
    } catch (UnrecoverableEntryException e) {
        Log.e(TAG, "failed to extract certificate" + e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Log.e(TAG, "close FileInputStream error: " + e);
            }
        }
    }
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(android.security.KeyStore) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) UnrecoverableEntryException(java.security.UnrecoverableEntryException) File(java.io.File) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) PasswordProtection(java.security.KeyStore.PasswordProtection)

Example 9 with UnrecoverableEntryException

use of java.security.UnrecoverableEntryException in project jdk8u_jdk by JetBrains.

the class Pair method recoverEntry.

/**
     * Recovers entry associated with given alias.
     *
     * @return an array of objects, where the 1st element in the array is the
     * recovered entry, and the 2nd element is the password used to
     * recover it (null if no password).
     */
private Pair<Entry, char[]> recoverEntry(KeyStore ks, String alias, char[] pstore, char[] pkey) throws Exception {
    if (ks.containsAlias(alias) == false) {
        MessageFormat form = new MessageFormat(rb.getString("Alias.alias.does.not.exist"));
        Object[] source = { alias };
        throw new Exception(form.format(source));
    }
    PasswordProtection pp = null;
    Entry entry;
    try {
        // First attempt to access entry without key password
        // (PKCS11 entry or trusted certificate entry, for example)
        entry = ks.getEntry(alias, pp);
        pkey = null;
    } catch (UnrecoverableEntryException une) {
        if (P11KEYSTORE.equalsIgnoreCase(ks.getType()) || KeyStoreUtil.isWindowsKeyStore(ks.getType())) {
            // should not happen, but a possibility
            throw une;
        }
        if (pkey != null) {
            // try provided key password
            pp = new PasswordProtection(pkey);
            entry = ks.getEntry(alias, pp);
        } else {
            try {
                pp = new PasswordProtection(pstore);
                entry = ks.getEntry(alias, pp);
                pkey = pstore;
            } catch (UnrecoverableEntryException une2) {
                if (P12KEYSTORE.equalsIgnoreCase(ks.getType())) {
                    throw une2;
                } else {
                    // prompt for entry password
                    pkey = getKeyPasswd(alias, null, null);
                    pp = new PasswordProtection(pkey);
                    entry = ks.getEntry(alias, pp);
                }
            }
        }
    }
    return Pair.of(entry, pkey);
}
Also used : X509CRLEntry(java.security.cert.X509CRLEntry) JarEntry(java.util.jar.JarEntry) MessageFormat(java.text.MessageFormat) UnrecoverableEntryException(java.security.UnrecoverableEntryException) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertStoreException(java.security.cert.CertStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException)

Example 10 with UnrecoverableEntryException

use of java.security.UnrecoverableEntryException in project midpoint by Evolveum.

the class KeyStoreDumper method execute.

public void execute() {
    try {
        ApplicationContext context = new ClassPathXmlApplicationContext(CONTEXTS);
        Protector protector = context.getBean("protector", Protector.class);
        KeyStore keyStore = protector.getKeyStore();
        System.out.println("###################################################");
        System.out.println("Printing keys from key store");
        if (protector instanceof ProtectorImpl) {
            ProtectorImpl aesProtector = (ProtectorImpl) protector;
            System.out.println("Using key store from location: " + aesProtector.getKeyStorePath());
        //			System.out.println("Cipher: " + aesProtector.getXmlCipher());
        }
        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            System.out.println("===== ALIAS: " + alias + "=====");
            System.out.println("Creation date: " + keyStore.getCreationDate(alias));
            System.out.println("Type: " + keyStore.getType());
            if (keyStore.getCertificate(alias) != null) {
                System.out.println("Certificate: " + keyStore.getCertificate(alias));
            }
            if (keyStore.getCertificateChain(alias) != null) {
                System.out.println("Certificate chain: " + keyStore.getCertificateChain(alias));
            }
            ProtectionParameter protParam = new KeyStore.PasswordProtection("midpoint".toCharArray());
            Entry entry = keyStore.getEntry(alias, protParam);
            if (entry instanceof SecretKeyEntry) {
                System.out.println("Secret key entry: ");
                SecretKeyEntry skEntry = (SecretKeyEntry) entry;
                SecretKey key = skEntry.getSecretKey();
                System.out.println("	Algorithm: " + key.getAlgorithm());
                System.out.println("	Format: " + key.getFormat());
                System.out.println("	Key length: " + key.getEncoded().length * 8);
                if (protector instanceof ProtectorImpl) {
                    System.out.println("	Key name: " + ((ProtectorImpl) protector).getSecretKeyDigest(key));
                }
            //				Cipher cipher = Cipher.getInstance(key.getAlgorithm());
            //				System.out.println("	Cipher algorithm" + cipher.getAlgorithm());
            }
            //TODO: add dump also for other types of keys
            Provider provider = keyStore.getProvider();
            System.out.println("Provder name: " + provider.getName() + "\n");
        }
        System.out.println("###################################################");
    } catch (KeyStoreException ex) {
        System.out.println("Failed to print information about keyStore. Reason: " + ex.getMessage());
        return;
    } catch (UnrecoverableEntryException ex) {
        System.out.println("Failed to print information about keyStore. Reason: " + ex.getMessage());
        return;
    } catch (NoSuchAlgorithmException ex) {
        System.out.println("Failed to print information about keyStore. Reason: " + ex.getMessage());
        return;
    } catch (EncryptionException ex) {
        System.out.println("Failed to print information about keyStore. Reason: " + ex.getMessage());
        return;
    }
}
Also used : ProtectorImpl(com.evolveum.midpoint.prism.crypto.ProtectorImpl) SecretKeyEntry(java.security.KeyStore.SecretKeyEntry) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) Provider(java.security.Provider) ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) SecretKeyEntry(java.security.KeyStore.SecretKeyEntry) Entry(java.security.KeyStore.Entry) SecretKey(javax.crypto.SecretKey) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) Protector(com.evolveum.midpoint.prism.crypto.Protector) ProtectionParameter(java.security.KeyStore.ProtectionParameter)

Aggregations

UnrecoverableEntryException (java.security.UnrecoverableEntryException)18 KeyStoreException (java.security.KeyStoreException)16 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)16 IOException (java.io.IOException)10 CertificateException (java.security.cert.CertificateException)10 KeyStore (java.security.KeyStore)8 KeyManagementException (java.security.KeyManagementException)5 TrustManager (javax.net.ssl.TrustManager)4 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)4 X509TrustManager (javax.net.ssl.X509TrustManager)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 PasswordProtection (java.security.KeyStore.PasswordProtection)3 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)3 Certificate (java.security.cert.Certificate)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 KeyPair (java.security.KeyPair)2 KeyPairGenerator (java.security.KeyPairGenerator)2 Entry (java.security.KeyStore.Entry)2 ProtectionParameter (java.security.KeyStore.ProtectionParameter)2