Search in sources :

Example 31 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project robovm by robovm.

the class TestKeyStore method dump.

/**
     * Dump a key store for debugging.
     */
public static void dump(String context, KeyStore keyStore, char[] keyPassword) throws KeyStoreException, NoSuchAlgorithmException {
    PrintStream out = System.out;
    out.println("context=" + context);
    out.println("\tkeyStore=" + keyStore);
    out.println("\tkeyStore.type=" + keyStore.getType());
    out.println("\tkeyStore.provider=" + keyStore.getProvider());
    out.println("\tkeyPassword=" + ((keyPassword == null) ? null : new String(keyPassword)));
    out.println("\tsize=" + keyStore.size());
    for (String alias : Collections.list(keyStore.aliases())) {
        out.println("alias=" + alias);
        out.println("\tcreationDate=" + keyStore.getCreationDate(alias));
        if (keyStore.isCertificateEntry(alias)) {
            out.println("\tcertificate:");
            out.println("==========================================");
            out.println(keyStore.getCertificate(alias));
            out.println("==========================================");
            continue;
        }
        if (keyStore.isKeyEntry(alias)) {
            out.println("\tkey:");
            out.println("==========================================");
            String key;
            try {
                key = ("Key retrieved using password\n" + keyStore.getKey(alias, keyPassword));
            } catch (UnrecoverableKeyException e1) {
                try {
                    key = ("Key retrieved without password\n" + keyStore.getKey(alias, null));
                } catch (UnrecoverableKeyException e2) {
                    key = "Key could not be retrieved";
                }
            }
            out.println(key);
            out.println("==========================================");
            Certificate[] chain = keyStore.getCertificateChain(alias);
            if (chain == null) {
                out.println("No certificate chain associated with key");
                out.println("==========================================");
            } else {
                for (int i = 0; i < chain.length; i++) {
                    out.println("Certificate chain element #" + i);
                    out.println(chain[i]);
                    out.println("==========================================");
                }
            }
            continue;
        }
        out.println("\tunknown entry type");
    }
}
Also used : PrintStream(java.io.PrintStream) UnrecoverableKeyException(java.security.UnrecoverableKeyException) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 32 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project cdap by caskdata.

the class FileSecureStore method deleteSecureData.

/**
   * Deletes the element with the given name. Flushes the keystore after deleting the key from the in memory keystore.
   * If the flush fails, we attempt to insert to key back to the in memory store and notify the user that delete failed.
   * If the insertion in the key store fails after a flush failure then there would be a discrepancy between the
   * in memory store and the file on the disk. This will be remedied the next time a flush happens.
   * If another flush does not happen and the system is restarted, the only time that file is read,
   * then we will have an extra key in the keystore.
   * @param namespace The namespace this key belongs to.
   * @param name Name of the element to be deleted.
   * @throws NamespaceNotFoundException If the specified namespace does not exist.
   * @throws NotFoundException If the key to be deleted is not found.
   * @throws IOException If their was a problem during deleting the key from the in memory store
   * or if there was a problem persisting the keystore after deleting the element.
   */
@Override
public void deleteSecureData(String namespace, String name) throws Exception {
    checkNamespaceExists(namespace);
    String keyName = getKeyName(namespace, name);
    Key key = null;
    writeLock.lock();
    try {
        if (!keyStore.containsAlias(keyName)) {
            throw new NotFoundException(new SecureKeyId(namespace, name));
        }
        key = deleteFromStore(keyName, password);
        flush();
        LOG.debug(String.format("Successfully deleted key %s from namespace %s", name, namespace));
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IOException("Failed to delete the key. ", e);
    } catch (IOException ioe) {
        try {
            keyStore.setKeyEntry(keyName, key, password, null);
        } catch (KeyStoreException e) {
            ioe.addSuppressed(e);
        }
        throw ioe;
    } finally {
        writeLock.unlock();
    }
}
Also used : SecureKeyId(co.cask.cdap.proto.id.SecureKeyId) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) NotFoundException(co.cask.cdap.common.NotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) Key(java.security.Key)

Example 33 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project ddf by codice.

the class ClaimsHandlerManager method createKeyManagerFactory.

public static KeyManagerFactory createKeyManagerFactory(String keyStoreLoc, String keyStorePass) throws IOException {
    KeyManagerFactory kmf;
    try {
        // keystore stuff
        KeyStore keyStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType"));
        LOGGER.debug("keyStoreLoc = {}", keyStoreLoc);
        FileInputStream keyFIS = new FileInputStream(keyStoreLoc);
        try {
            LOGGER.debug("Loading keyStore");
            keyStore.load(keyFIS, keyStorePass.toCharArray());
        } catch (CertificateException e) {
            throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e);
        } finally {
            IOUtils.closeQuietly(keyFIS);
        }
        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePass.toCharArray());
        LOGGER.debug("key manager factory initialized");
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e);
    } catch (UnrecoverableKeyException e) {
        throw new IOException("Unable to load keystore. " + keyStoreLoc, e);
    } catch (KeyStoreException e) {
        throw new IOException("Unable to read keystore. " + keyStoreLoc, e);
    }
    return kmf;
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 34 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project ddf by codice.

the class SolrHttpWrapper method getSslContext.

private SSLContext getSslContext() {
    String keystorePath = System.getProperty(SecurityConstants.KEYSTORE_PATH);
    String keystorePassword = System.getProperty(SecurityConstants.KEYSTORE_PASSWORD);
    String truststorePath = System.getProperty(SecurityConstants.TRUSTSTORE_PATH);
    String truststorePassword = System.getProperty(SecurityConstants.TRUSTSTORE_PASSWORD);
    if (keystorePath == null || keystorePassword == null || truststorePath == null || truststorePassword == null) {
        throw new IllegalArgumentException("KeyStore and TrustStore system properties must be set.");
    }
    KeyStore trustStore = getKeyStore(truststorePath, truststorePassword);
    KeyStore keyStore = getKeyStore(keystorePath, keystorePassword);
    SSLContext sslContext;
    try {
        sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, keystorePassword.toCharArray()).loadTrustMaterial(trustStore).useTLS().build();
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        LOGGER.error("Unable to create secure HttpClient for Solr. The server should not be used in this state.", e);
        return null;
    }
    sslContext.getDefaultSSLParameters().setNeedClientAuth(true);
    sslContext.getDefaultSSLParameters().setWantClientAuth(true);
    return sslContext;
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException)

Example 35 with UnrecoverableKeyException

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

the class PKCS12KeyStore method engineLoad.

/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public synchronized void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    DataInputStream dis;
    CertificateFactory cf = null;
    ByteArrayInputStream bais = null;
    byte[] encoded = null;
    if (stream == null)
        return;
    // reset the counter
    counter = 0;
    DerValue val = new DerValue(stream);
    DerInputStream s = val.toDerInputStream();
    int version = s.getInteger();
    if (version != VERSION_3) {
        throw new IOException("PKCS12 keystore not in version 3 format");
    }
    entries.clear();
    /*
         * Read the authSafe.
         */
    byte[] authSafeData;
    ContentInfo authSafe = new ContentInfo(s);
    ObjectIdentifier contentType = authSafe.getContentType();
    if (contentType.equals((Object) ContentInfo.DATA_OID)) {
        authSafeData = authSafe.getData();
    } else /* signed data */
    {
        throw new IOException("public key protected PKCS12 not supported");
    }
    DerInputStream as = new DerInputStream(authSafeData);
    DerValue[] safeContentsArray = as.getSequence(2);
    int count = safeContentsArray.length;
    // reset the counters at the start
    privateKeyCount = 0;
    secretKeyCount = 0;
    certificateCount = 0;
    /*
         * Spin over the ContentInfos.
         */
    for (int i = 0; i < count; i++) {
        byte[] safeContentsData;
        ContentInfo safeContents;
        DerInputStream sci;
        byte[] eAlgId = null;
        sci = new DerInputStream(safeContentsArray[i].toByteArray());
        safeContents = new ContentInfo(sci);
        contentType = safeContents.getContentType();
        safeContentsData = null;
        if (contentType.equals((Object) ContentInfo.DATA_OID)) {
            if (debug != null) {
                debug.println("Loading PKCS#7 data content-type");
            }
            safeContentsData = safeContents.getData();
        } else if (contentType.equals((Object) ContentInfo.ENCRYPTED_DATA_OID)) {
            if (password == null) {
                if (debug != null) {
                    debug.println("Warning: skipping PKCS#7 encryptedData" + " content-type - no password was supplied");
                }
                continue;
            }
            if (debug != null) {
                debug.println("Loading PKCS#7 encryptedData content-type");
            }
            DerInputStream edi = safeContents.getContent().toDerInputStream();
            int edVersion = edi.getInteger();
            DerValue[] seq = edi.getSequence(2);
            ObjectIdentifier edContentType = seq[0].getOID();
            eAlgId = seq[1].toByteArray();
            if (!seq[2].isContextSpecific((byte) 0)) {
                throw new IOException("encrypted content not present!");
            }
            byte newTag = DerValue.tag_OctetString;
            if (seq[2].isConstructed())
                newTag |= 0x20;
            seq[2].resetTag(newTag);
            safeContentsData = seq[2].getOctetString();
            // parse Algorithm parameters
            DerInputStream in = seq[1].toDerInputStream();
            ObjectIdentifier algOid = in.getOID();
            AlgorithmParameters algParams = parseAlgParameters(algOid, in);
            while (true) {
                try {
                    // Use JCE
                    SecretKey skey = getPBEKey(password);
                    Cipher cipher = Cipher.getInstance(algOid.toString());
                    cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
                    safeContentsData = cipher.doFinal(safeContentsData);
                    break;
                } catch (Exception e) {
                    if (password.length == 0) {
                        // Retry using an empty password
                        // without a NULL terminator.
                        password = new char[1];
                        continue;
                    }
                    throw new IOException("keystore password was incorrect", new UnrecoverableKeyException("failed to decrypt safe contents entry: " + e));
                }
            }
        } else {
            throw new IOException("public key protected PKCS12" + " not supported");
        }
        DerInputStream sc = new DerInputStream(safeContentsData);
        loadSafeContents(sc, password);
    }
    // The MacData is optional.
    if (password != null && s.available() > 0) {
        MacData macData = new MacData(s);
        try {
            String algName = macData.getDigestAlgName().toUpperCase(Locale.ENGLISH);
            // Change SHA-1 to SHA1
            algName = algName.replace("-", "");
            // generate MAC (MAC key is created within JCE)
            Mac m = Mac.getInstance("HmacPBE" + algName);
            PBEParameterSpec params = new PBEParameterSpec(macData.getSalt(), macData.getIterations());
            SecretKey key = getPBEKey(password);
            m.init(key, params);
            m.update(authSafeData);
            byte[] macResult = m.doFinal();
            if (debug != null) {
                debug.println("Checking keystore integrity " + "(MAC algorithm: " + m.getAlgorithm() + ")");
            }
            if (!MessageDigest.isEqual(macData.getDigest(), macResult)) {
                throw new UnrecoverableKeyException("Failed PKCS12" + " integrity checking");
            }
        } catch (Exception e) {
            throw new IOException("Integrity check failed: " + e, e);
        }
    }
    /*
         * Match up private keys with certificate chains.
         */
    PrivateKeyEntry[] list = keyList.toArray(new PrivateKeyEntry[keyList.size()]);
    for (int m = 0; m < list.length; m++) {
        PrivateKeyEntry entry = list[m];
        if (entry.keyId != null) {
            ArrayList<X509Certificate> chain = new ArrayList<X509Certificate>();
            X509Certificate cert = findMatchedCertificate(entry);
            mainloop: while (cert != null) {
                // Check for loops in the certificate chain
                if (!chain.isEmpty()) {
                    for (X509Certificate chainCert : chain) {
                        if (cert.equals(chainCert)) {
                            if (debug != null) {
                                debug.println("Loop detected in " + "certificate chain. Skip adding " + "repeated cert to chain. Subject: " + cert.getSubjectX500Principal().toString());
                            }
                            break mainloop;
                        }
                    }
                }
                chain.add(cert);
                X500Principal issuerDN = cert.getIssuerX500Principal();
                if (issuerDN.equals(cert.getSubjectX500Principal())) {
                    break;
                }
                cert = certsMap.get(issuerDN);
            }
            /* Update existing KeyEntry in entries table */
            if (chain.size() > 0)
                entry.chain = chain.toArray(new Certificate[chain.size()]);
        }
    }
    if (debug != null) {
        if (privateKeyCount > 0) {
            debug.println("Loaded " + privateKeyCount + " protected private key(s)");
        }
        if (secretKeyCount > 0) {
            debug.println("Loaded " + secretKeyCount + " protected secret key(s)");
        }
        if (certificateCount > 0) {
            debug.println("Loaded " + certificateCount + " certificate(s)");
        }
    }
    certEntries.clear();
    certsMap.clear();
    keyList.clear();
}
Also used : CertificateFactory(java.security.cert.CertificateFactory) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ContentInfo(sun.security.pkcs.ContentInfo) DerValue(sun.security.util.DerValue) DerInputStream(sun.security.util.DerInputStream) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) ObjectIdentifier(sun.security.util.ObjectIdentifier) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) DestroyFailedException(javax.security.auth.DestroyFailedException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Mac(javax.crypto.Mac) X509Certificate(java.security.cert.X509Certificate) SecretKey(javax.crypto.SecretKey) X500Principal(javax.security.auth.x500.X500Principal) Cipher(javax.crypto.Cipher) AlgorithmParameters(java.security.AlgorithmParameters)

Aggregations

UnrecoverableKeyException (java.security.UnrecoverableKeyException)109 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)87 KeyStoreException (java.security.KeyStoreException)86 IOException (java.io.IOException)69 CertificateException (java.security.cert.CertificateException)58 KeyStore (java.security.KeyStore)30 InvalidKeyException (java.security.InvalidKeyException)29 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)29 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)27 BadPaddingException (javax.crypto.BadPaddingException)26 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)26 KeyManagementException (java.security.KeyManagementException)25 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)20 SSLContext (javax.net.ssl.SSLContext)20 SecretKey (javax.crypto.SecretKey)17 RemoteException (android.os.RemoteException)15 FileNotFoundException (java.io.FileNotFoundException)13 InputStream (java.io.InputStream)13 Key (java.security.Key)13 PrivateKey (java.security.PrivateKey)12