Java Code Examples for java.security.KeyStore#Entry

The following examples show how to use java.security.KeyStore#Entry . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MetadataStoreLoadTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
 
Example 2
Source File: InternalLocker.java    From cashuwallet with MIT License 6 votes vote down vote up
private KeyPair getSecretKeyPair() {
    KeyStore keyStore = getKeyStore();
    if (keyStore == null) return createSecretKeyPair();
    KeyStore.Entry entry;
    try {
        entry = keyStore.getEntry(keyName, null);
    } catch (KeyStoreException|NoSuchAlgorithmException|UnrecoverableEntryException e) {
        entry = null;
    }
    KeyStore.PrivateKeyEntry secretEntry = entry instanceof KeyStore.PrivateKeyEntry ? (KeyStore.PrivateKeyEntry) entry : null;
    if (secretEntry == null) {
        if (entry != null) deleteSecretKeyPair();
        return createSecretKeyPair();
    }
    return new KeyPair(secretEntry.getCertificate().getPublicKey(), secretEntry.getPrivateKey());
}
 
Example 3
Source File: MetadataStoreLoadTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
 
Example 4
Source File: MetadataEmptyTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example 5
Source File: MetadataEmptyTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example 6
Source File: TlsCertificateAuthorityTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void validateClient(Certificate caCertificate) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException,
        UnrecoverableEntryException, InvalidKeyException, NoSuchProviderException, SignatureException {
    clientConfig = objectMapper.readValue(new ByteArrayInputStream(clientConfigFileOutputStream.toByteArray()), TlsClientConfig.class);

    KeyStore clientKeyStore = KeyStoreUtils.getKeyStore(clientConfig.getKeyStoreType());
    clientKeyStore.load(new ByteArrayInputStream(clientKeyStoreOutputStream.toByteArray()), clientConfig.getKeyStorePassword().toCharArray());
    String keyPassword = clientConfig.getKeyPassword();
    KeyStore.Entry clientKeyStoreEntry = clientKeyStore.getEntry(TlsToolkitStandalone.NIFI_KEY,
            new KeyStore.PasswordProtection(keyPassword == null ? clientConfig.getKeyStorePassword().toCharArray() : keyPassword.toCharArray()));

    assertTrue(clientKeyStoreEntry instanceof KeyStore.PrivateKeyEntry);
    KeyStore.PrivateKeyEntry clientPrivateKeyEntry = (KeyStore.PrivateKeyEntry) clientKeyStoreEntry;
    Certificate[] certificateChain = clientPrivateKeyEntry.getCertificateChain();
    assertEquals(2, certificateChain.length);
    assertEquals(caCertificate, certificateChain[1]);
    certificateChain[0].verify(caCertificate.getPublicKey());
    assertPrivateAndPublicKeyMatch(clientPrivateKeyEntry.getPrivateKey(), certificateChain[0].getPublicKey());

    KeyStore clientTrustStore = KeyStoreUtils.getTrustStore(KeystoreType.JKS.toString());
    clientTrustStore.load(new ByteArrayInputStream(clientTrustStoreOutputStream.toByteArray()), clientConfig.getTrustStorePassword().toCharArray());
    assertEquals(caCertificate, clientTrustStore.getCertificate(TlsToolkitStandalone.NIFI_CERT));
}
 
Example 7
Source File: TlsClientManager.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void write(OutputStreamFactory outputStreamFactory) throws IOException, GeneralSecurityException {
    super.write(outputStreamFactory);

    String trustStorePassword = tlsClientConfig.getTrustStorePassword();
    boolean trustStorePasswordGenerated = false;
    if (StringUtils.isEmpty(trustStorePassword)) {
        trustStorePassword = getPasswordUtil().generatePassword();
        trustStorePasswordGenerated = true;
    }

    trustStorePassword = TlsHelper.writeKeyStore(trustStore, outputStreamFactory, new File(tlsClientConfig.getTrustStore()), trustStorePassword, trustStorePasswordGenerated);
    tlsClientConfig.setTrustStorePassword(trustStorePassword);

    for (ConfigurationWriter<TlsClientConfig> configurationWriter : configurationWriters) {
        configurationWriter.write(tlsClientConfig, outputStreamFactory);
    }

    if (certificateAuthorityDirectory != null) {
        // Write out all trusted certificates from truststore
        for (String alias : Collections.list(trustStore.aliases())) {
            try {
                KeyStore.Entry trustStoreEntry = trustStore.getEntry(alias, null);
                if (trustStoreEntry instanceof KeyStore.TrustedCertificateEntry) {
                    Certificate trustedCertificate = ((KeyStore.TrustedCertificateEntry) trustStoreEntry).getTrustedCertificate();
                    try (OutputStream outputStream = outputStreamFactory.create(new File(certificateAuthorityDirectory, alias + ".pem"));
                         OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
                         PemWriter pemWriter = new PemWriter(outputStreamWriter)) {
                        pemWriter.writeObject(new JcaMiscPEMGenerator(trustedCertificate));
                    }
                }
            } catch (UnrecoverableEntryException e) {
                // Ignore, not a trusted cert
            }
        }
    }
}
 
Example 8
Source File: MixedcaseAlias.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] ignored) throws Exception {
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(null, null);

    keystore.setCertificateEntry(ALIAS, loadCertificate(CERT));
    KeyStore.Entry entry = keystore.getEntry(ALIAS, null);

    if (entry == null) {
        throw new Exception(
            "Error retrieving keystore entry using a mixed-case alias");
    }

    System.out.println("OK");
}
 
Example 9
Source File: P12SecretKey.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void run(String keystoreType) throws Exception {
    char[] pw = "password".toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(null, pw);

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128);
    SecretKey key = kg.generateKey();

    KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
    KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
    ks.setEntry(ALIAS, ske, kspp);

    File ksFile = File.createTempFile("test", ".test");
    try (FileOutputStream fos = new FileOutputStream(ksFile)) {
        ks.store(fos, pw);
        fos.flush();
    }

    // now see if we can get it back
    try (FileInputStream fis = new FileInputStream(ksFile)) {
        KeyStore ks2 = KeyStore.getInstance(keystoreType);
        ks2.load(fis, pw);
        KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
        SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();
        if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
            System.err.println("OK: worked just fine with " + keystoreType +
                               " keystore");
        } else {
            System.err.println("ERROR: keys are NOT equal after storing in "
                               + keystoreType + " keystore");
        }
    }
}
 
Example 10
Source File: PKCS12KeyStore.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets a <code>KeyStore.Entry</code> for the specified alias
 * with the specified protection parameter.
 *
 * @param alias get the <code>KeyStore.Entry</code> for this alias
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @return the <code>KeyStore.Entry</code> for the specified alias,
 *          or <code>null</code> if there is no such entry
 *
 * @exception KeyStoreException if the operation failed
 * @exception NoSuchAlgorithmException if the algorithm for recovering the
 *          entry cannot be found
 * @exception UnrecoverableEntryException if the specified
 *          <code>protParam</code> were insufficient or invalid
 * @exception UnrecoverableKeyException if the entry is a
 *          <code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
 *          and the specified <code>protParam</code> does not contain
 *          the information needed to recover the key (e.g. wrong password)
 *
 * @since 1.5
 */
@Override
public KeyStore.Entry engineGetEntry(String alias,
                    KeyStore.ProtectionParameter protParam)
            throws KeyStoreException, NoSuchAlgorithmException,
            UnrecoverableEntryException {

    if (!engineContainsAlias(alias)) {
        return null;
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (protParam == null) {
        if (engineIsCertificateEntry(alias)) {
            if (entry instanceof CertEntry &&
                ((CertEntry) entry).trustedKeyUsage != null) {

                if (debug != null) {
                    debug.println("Retrieved a trusted certificate at " +
                        "alias '" + alias + "'");
                }

                return new KeyStore.TrustedCertificateEntry(
                    ((CertEntry)entry).cert, getAttributes(entry));
            }
        } else {
            throw new UnrecoverableKeyException
                    ("requested entry requires a password");
        }
    }

    if (protParam instanceof KeyStore.PasswordProtection) {
        if (engineIsCertificateEntry(alias)) {
            throw new UnsupportedOperationException
                ("trusted certificate entries are not password-protected");
        } else if (engineIsKeyEntry(alias)) {
            KeyStore.PasswordProtection pp =
                    (KeyStore.PasswordProtection)protParam;
            char[] password = pp.getPassword();

            Key key = engineGetKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate[] chain = engineGetCertificateChain(alias);

                return new KeyStore.PrivateKeyEntry((PrivateKey)key, chain,
                    getAttributes(entry));

            } else if (key instanceof SecretKey) {

                return new KeyStore.SecretKeyEntry((SecretKey)key,
                    getAttributes(entry));
            }
        } else if (!engineIsKeyEntry(alias)) {
            throw new UnsupportedOperationException
                ("untrusted certificate entries are not " +
                    "password-protected");
        }
    }

    throw new UnsupportedOperationException();
}
 
Example 11
Source File: PKCS12KeyStore.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Saves a <code>KeyStore.Entry</code> under the specified alias.
 * The specified protection parameter is used to protect the
 * <code>Entry</code>.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the <code>KeyStore.Entry</code> under this alias
 * @param entry the <code>Entry</code> to save
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
@Override
public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
    KeyStore.ProtectionParameter protParam) throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        if (protParam != null && pProtect.getPassword() != null) {
            // pre-1.5 style setCertificateEntry did not allow password
            throw new KeyStoreException
                ("trusted certificate entries are not password-protected");
        } else {
            KeyStore.TrustedCertificateEntry tce =
                    (KeyStore.TrustedCertificateEntry)entry;
            setCertEntry(alias, tce.getTrustedCertificate(),
                tce.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create PrivateKeyEntry");
        } else {
            KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
            setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                pke.getCertificateChain(), pke.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create SecretKeyEntry");
        } else {
            KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
            setKeyEntry(alias, ske.getSecretKey(), pProtect,
                (Certificate[])null, ske.getAttributes());

            return;
        }
    }

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
Example 12
Source File: PKCS12KeyStore.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Saves a <code>KeyStore.Entry</code> under the specified alias.
 * The specified protection parameter is used to protect the
 * <code>Entry</code>.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the <code>KeyStore.Entry</code> under this alias
 * @param entry the <code>Entry</code> to save
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
@Override
public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
    KeyStore.ProtectionParameter protParam) throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        if (protParam != null && pProtect.getPassword() != null) {
            // pre-1.5 style setCertificateEntry did not allow password
            throw new KeyStoreException
                ("trusted certificate entries are not password-protected");
        } else {
            KeyStore.TrustedCertificateEntry tce =
                    (KeyStore.TrustedCertificateEntry)entry;
            setCertEntry(alias, tce.getTrustedCertificate(),
                tce.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create PrivateKeyEntry");
        } else {
            KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
            setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                pke.getCertificateChain(), pke.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create SecretKeyEntry");
        } else {
            KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
            setKeyEntry(alias, ske.getSecretKey(), pProtect,
                (Certificate[])null, ske.getAttributes());

            return;
        }
    }

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
Example 13
Source File: PKCS12KeyStore.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Saves a <code>KeyStore.Entry</code> under the specified alias.
 * The specified protection parameter is used to protect the
 * <code>Entry</code>.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the <code>KeyStore.Entry</code> under this alias
 * @param entry the <code>Entry</code> to save
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
@Override
public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
    KeyStore.ProtectionParameter protParam) throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        if (protParam != null && pProtect.getPassword() != null) {
            // pre-1.5 style setCertificateEntry did not allow password
            throw new KeyStoreException
                ("trusted certificate entries are not password-protected");
        } else {
            KeyStore.TrustedCertificateEntry tce =
                    (KeyStore.TrustedCertificateEntry)entry;
            setCertEntry(alias, tce.getTrustedCertificate(),
                tce.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create PrivateKeyEntry");
        } else {
            KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
            setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                pke.getCertificateChain(), pke.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create SecretKeyEntry");
        } else {
            KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
            setKeyEntry(alias, ske.getSecretKey(), pProtect,
                (Certificate[])null, ske.getAttributes());

            return;
        }
    }

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
Example 14
Source File: PKCS12KeyStore.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Saves a <code>KeyStore.Entry</code> under the specified alias.
 * The specified protection parameter is used to protect the
 * <code>Entry</code>.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the <code>KeyStore.Entry</code> under this alias
 * @param entry the <code>Entry</code> to save
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
@Override
public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
    KeyStore.ProtectionParameter protParam) throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        if (protParam != null && pProtect.getPassword() != null) {
            // pre-1.5 style setCertificateEntry did not allow password
            throw new KeyStoreException
                ("trusted certificate entries are not password-protected");
        } else {
            KeyStore.TrustedCertificateEntry tce =
                    (KeyStore.TrustedCertificateEntry)entry;
            setCertEntry(alias, tce.getTrustedCertificate(),
                tce.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create PrivateKeyEntry");
        } else {
            KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
            setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                pke.getCertificateChain(), pke.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create SecretKeyEntry");
        } else {
            KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
            setKeyEntry(alias, ske.getSecretKey(), pProtect,
                (Certificate[])null, ske.getAttributes());

            return;
        }
    }

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
Example 15
Source File: PKCS12KeyStore.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Saves a <code>KeyStore.Entry</code> under the specified alias.
 * The specified protection parameter is used to protect the
 * <code>Entry</code>.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the <code>KeyStore.Entry</code> under this alias
 * @param entry the <code>Entry</code> to save
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
@Override
public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
    KeyStore.ProtectionParameter protParam) throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        if (protParam != null && pProtect.getPassword() != null) {
            // pre-1.5 style setCertificateEntry did not allow password
            throw new KeyStoreException
                ("trusted certificate entries are not password-protected");
        } else {
            KeyStore.TrustedCertificateEntry tce =
                    (KeyStore.TrustedCertificateEntry)entry;
            setCertEntry(alias, tce.getTrustedCertificate(),
                tce.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create PrivateKeyEntry");
        } else {
            KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
            setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                pke.getCertificateChain(), pke.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create SecretKeyEntry");
        } else {
            KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
            setKeyEntry(alias, ske.getSecretKey(), pProtect,
                (Certificate[])null, ske.getAttributes());

            return;
        }
    }

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
Example 16
Source File: PKCS12KeyStore.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets a <code>KeyStore.Entry</code> for the specified alias
 * with the specified protection parameter.
 *
 * @param alias get the <code>KeyStore.Entry</code> for this alias
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @return the <code>KeyStore.Entry</code> for the specified alias,
 *          or <code>null</code> if there is no such entry
 *
 * @exception KeyStoreException if the operation failed
 * @exception NoSuchAlgorithmException if the algorithm for recovering the
 *          entry cannot be found
 * @exception UnrecoverableEntryException if the specified
 *          <code>protParam</code> were insufficient or invalid
 * @exception UnrecoverableKeyException if the entry is a
 *          <code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
 *          and the specified <code>protParam</code> does not contain
 *          the information needed to recover the key (e.g. wrong password)
 *
 * @since 1.5
 */
@Override
public KeyStore.Entry engineGetEntry(String alias,
                    KeyStore.ProtectionParameter protParam)
            throws KeyStoreException, NoSuchAlgorithmException,
            UnrecoverableEntryException {

    if (!engineContainsAlias(alias)) {
        return null;
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (protParam == null) {
        if (engineIsCertificateEntry(alias)) {
            if (entry instanceof CertEntry &&
                ((CertEntry) entry).trustedKeyUsage != null) {

                if (debug != null) {
                    debug.println("Retrieved a trusted certificate at " +
                        "alias '" + alias + "'");
                }

                return new KeyStore.TrustedCertificateEntry(
                    ((CertEntry)entry).cert, getAttributes(entry));
            }
        } else {
            throw new UnrecoverableKeyException
                    ("requested entry requires a password");
        }
    }

    if (protParam instanceof KeyStore.PasswordProtection) {
        if (engineIsCertificateEntry(alias)) {
            throw new UnsupportedOperationException
                ("trusted certificate entries are not password-protected");
        } else if (engineIsKeyEntry(alias)) {
            KeyStore.PasswordProtection pp =
                    (KeyStore.PasswordProtection)protParam;
            char[] password = pp.getPassword();

            Key key = engineGetKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate[] chain = engineGetCertificateChain(alias);

                return new KeyStore.PrivateKeyEntry((PrivateKey)key, chain,
                    getAttributes(entry));

            } else if (key instanceof SecretKey) {

                return new KeyStore.SecretKeyEntry((SecretKey)key,
                    getAttributes(entry));
            }
        } else if (!engineIsKeyEntry(alias)) {
            throw new UnsupportedOperationException
                ("untrusted certificate entries are not " +
                    "password-protected");
        }
    }

    throw new UnsupportedOperationException();
}
 
Example 17
Source File: TlsToolkitStandaloneTest.java    From nifi with Apache License 2.0 4 votes vote down vote up
private Properties checkHostDirAndReturnNifiProperties(String hostname, String dnPrefix, String dnSuffix, X509Certificate rootCert) throws Exception {
    File hostDir = new File(tempDir, hostname);
    Properties nifiProperties = new Properties();
    try (InputStream inputStream = new FileInputStream(new File(hostDir, TlsToolkitStandalone.NIFI_PROPERTIES))) {
        nifiProperties.load(inputStream);
    }

    String trustStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    assertEquals(KeystoreType.JKS.toString().toLowerCase(), trustStoreType.toLowerCase());
    KeyStore trustStore = KeyStoreUtils.getTrustStore(trustStoreType);
    try (InputStream inputStream = new FileInputStream(new File(hostDir, "truststore." + trustStoreType))) {
        trustStore.load(inputStream, nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD).toCharArray());
    }

    String trustStoreFilename = BaseTlsToolkitCommandLine.TRUSTSTORE + trustStoreType;
    assertEquals("./conf/" + trustStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));

    Certificate certificate = trustStore.getCertificate(TlsToolkitStandalone.NIFI_CERT);
    assertEquals(rootCert, certificate);

    String keyStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    String keyStoreFilename = BaseTlsToolkitCommandLine.KEYSTORE + keyStoreType;
    File keyStoreFile = new File(hostDir, keyStoreFilename);
    assertEquals("./conf/" + keyStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE));

    KeyStore keyStore = KeyStoreUtils.getKeyStore(keyStoreType);
    char[] keyStorePassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray();
    try (InputStream inputStream = new FileInputStream(keyStoreFile)) {
        keyStore.load(inputStream, keyStorePassword);
    }

    char[] keyPassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEY_PASSWD).toCharArray();
    if (keyPassword == null || keyPassword.length == 0) {
        keyPassword = keyStorePassword;
    }

    KeyStore.Entry entry = keyStore.getEntry(TlsToolkitStandalone.NIFI_KEY, new KeyStore.PasswordProtection(keyPassword));
    assertEquals(KeyStore.PrivateKeyEntry.class, entry.getClass());

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

    Certificate[] certificateChain = privateKeyEntry.getCertificateChain();

    assertEquals(2, certificateChain.length);
    assertEquals(rootCert, certificateChain[1]);
    certificateChain[1].verify(rootCert.getPublicKey());
    certificateChain[0].verify(rootCert.getPublicKey());
    TlsConfig tlsConfig = new TlsConfig();
    tlsConfig.setDnPrefix(dnPrefix);
    tlsConfig.setDnSuffix(dnSuffix);
    assertEquals(tlsConfig.calcDefaultDn(hostname), CertificateUtils.convertAbstractX509Certificate(certificateChain[0]).getSubjectX500Principal().getName());
    TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(), certificateChain[0].getPublicKey());
    return nifiProperties;
}
 
Example 18
Source File: PKCS12KeyStore.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets a <code>KeyStore.Entry</code> for the specified alias
 * with the specified protection parameter.
 *
 * @param alias get the <code>KeyStore.Entry</code> for this alias
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @return the <code>KeyStore.Entry</code> for the specified alias,
 *          or <code>null</code> if there is no such entry
 *
 * @exception KeyStoreException if the operation failed
 * @exception NoSuchAlgorithmException if the algorithm for recovering the
 *          entry cannot be found
 * @exception UnrecoverableEntryException if the specified
 *          <code>protParam</code> were insufficient or invalid
 * @exception UnrecoverableKeyException if the entry is a
 *          <code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
 *          and the specified <code>protParam</code> does not contain
 *          the information needed to recover the key (e.g. wrong password)
 *
 * @since 1.5
 */
@Override
public KeyStore.Entry engineGetEntry(String alias,
                    KeyStore.ProtectionParameter protParam)
            throws KeyStoreException, NoSuchAlgorithmException,
            UnrecoverableEntryException {

    if (!engineContainsAlias(alias)) {
        return null;
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (protParam == null) {
        if (engineIsCertificateEntry(alias)) {
            if (entry instanceof CertEntry &&
                ((CertEntry) entry).trustedKeyUsage != null) {

                if (debug != null) {
                    debug.println("Retrieved a trusted certificate at " +
                        "alias '" + alias + "'");
                }

                return new KeyStore.TrustedCertificateEntry(
                    ((CertEntry)entry).cert, getAttributes(entry));
            }
        } else {
            throw new UnrecoverableKeyException
                    ("requested entry requires a password");
        }
    }

    if (protParam instanceof KeyStore.PasswordProtection) {
        if (engineIsCertificateEntry(alias)) {
            throw new UnsupportedOperationException
                ("trusted certificate entries are not password-protected");
        } else if (engineIsKeyEntry(alias)) {
            KeyStore.PasswordProtection pp =
                    (KeyStore.PasswordProtection)protParam;
            char[] password = pp.getPassword();

            Key key = engineGetKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate[] chain = engineGetCertificateChain(alias);

                return new KeyStore.PrivateKeyEntry((PrivateKey)key, chain,
                    getAttributes(entry));

            } else if (key instanceof SecretKey) {

                return new KeyStore.SecretKeyEntry((SecretKey)key,
                    getAttributes(entry));
            }
        } else if (!engineIsKeyEntry(alias)) {
            throw new UnsupportedOperationException
                ("untrusted certificate entries are not " +
                    "password-protected");
        }
    }

    throw new UnsupportedOperationException();
}
 
Example 19
Source File: KeyStoreSpi.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Saves a {@code KeyStore.Entry} under the specified alias.
 * The specified protection parameter is used to protect the
 * {@code Entry}.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the {@code KeyStore.Entry} under this alias
 * @param entry the {@code Entry} to save
 * @param protParam the {@code ProtectionParameter}
 *          used to protect the {@code Entry},
 *          which may be {@code null}
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
public void engineSetEntry(String alias, KeyStore.Entry entry,
                    KeyStore.ProtectionParameter protParam)
            throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // BEGIN Android-changed: Allow access to entries with no password.
    char[] password = (pProtect == null) ? null : pProtect.getPassword();
    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        KeyStore.TrustedCertificateEntry tce =
                (KeyStore.TrustedCertificateEntry)entry;
        engineSetCertificateEntry(alias, tce.getTrustedCertificate());
        return;
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        engineSetKeyEntry
            (alias,
            ((KeyStore.PrivateKeyEntry)entry).getPrivateKey(),
            password,
            ((KeyStore.PrivateKeyEntry)entry).getCertificateChain());
        return;
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        engineSetKeyEntry
            (alias,
            ((KeyStore.SecretKeyEntry)entry).getSecretKey(),
            password,
            (Certificate[])null);
        return;
    }
    // END Android-changed: Allow access to entries with no password.

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
Example 20
Source File: BaseTlsManager.java    From nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Adds the private key of the KeyPair to the KeyStore and returns the entry
 *
 * @param keyPair the KeyPair
 * @param alias the alias
 * @param certificates the certificate chain
 * @return the entry
 * @throws GeneralSecurityException if there is a problem performing the operation
 */
public KeyStore.Entry addPrivateKeyToKeyStore(KeyPair keyPair, String alias, Certificate... certificates) throws GeneralSecurityException {
    String passphrase = getKeyPassword();
    keyStore.setKeyEntry(alias, keyPair.getPrivate(), passphrase == null ? null : passphrase.toCharArray(), certificates);
    return getEntry(alias);
}