Java Code Examples for java.security.KeyStore.SecretKeyEntry

The following are Jave code examples for showing how to use SecretKeyEntry of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: osc-core   File: KeyStoreProvider.java   View Source Code Vote up 6 votes
/**
 * Gets the secret password stored in keystore under given alias.
 * @param alias
 * @param entryPassword entry password to access the secret password stored in keystore
 * @return the secret password or null if secret password does not exists in keystore
 * @throws KeyStoreProviderException
 */
public String getPassword(String alias, String entryPassword) throws KeyStoreProviderException {
    try {
        LOG.info(String.format("Getting password with alias %s from keystore ...", alias));

        SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_PASSWORD_ALGORITHM);

        Optional<KeyStore.SecretKeyEntry> ske = Optional.fromNullable((KeyStore.SecretKeyEntry) this.keystore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword.toCharArray())));

        if(!ske.isPresent()) {
            return null;
        }

        PBEKeySpec keySpec = (PBEKeySpec)factory.getKeySpec(ske.get().getSecretKey(),PBEKeySpec.class);
        char[] password = keySpec.getPassword();

        if(ArrayUtils.isEmpty(password)) {
            throw new KeyStoreProviderException("Recovered password is blank.");
        }

        return new String(password);
    } catch (NoSuchAlgorithmException nsae) {
        throw new KeyStoreProviderException("Algorithm used to create PBE secret cannot be found.", nsae);
    } catch (UnrecoverableEntryException uee) {
        throw new KeyStoreProviderException("Invalid entry password to recover secret.", uee);
    } catch (KeyStoreException kse) {
        throw new KeyStoreProviderException("Failed to get PBE secret to keystore.", kse);
    } catch (InvalidKeySpecException ikse) {
        throw new KeyStoreProviderException("Failed to get key spec from PBE secret.", ikse);
    } catch (Exception e) {
        throw new KeyStoreProviderException("Failed to get PBE secret.", e);
    }
}
 
Example 2
Project: osc-core   File: KeyStoreProvider.java   View Source Code Vote up 6 votes
/**
 * Gets the secret key stored in keystore under given alias.
 * @param alias
 * @param entryPassword entry password to access the secret key stored in keystore
 * @return the secret key or null if secret key does not exists in keystore
 * @throws KeyStoreProviderException
 */
public SecretKey getSecretKey(String alias, String entryPassword) throws KeyStoreProviderException {
    try {
        LOG.info(String.format("Getting secret key with alias %s from keystore ...", alias));

        Optional<KeyStore.SecretKeyEntry> entry = Optional.fromNullable((KeyStore.SecretKeyEntry)this.keystore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword.toCharArray())));

        if (!entry.isPresent()) {
            return null;
        }

        return entry.get().getSecretKey();

    } catch (NoSuchAlgorithmException nsae) {
        throw new KeyStoreProviderException("Algorithm for recovering the secret key cannot be found.", nsae);
    } catch (UnrecoverableEntryException uee) {
        throw new KeyStoreProviderException("Invalid entry password to recover secret.", uee);
    } catch (KeyStoreException kse) {
        throw new KeyStoreProviderException("Failed to get secret key entry.", kse);
    } catch (Exception e) {
        throw new KeyStoreProviderException("Failed to get secret key.", e);
    }
}
 
Example 3
Project: lams   File: KeyStoreCredentialResolver.java   View Source Code Vote up 6 votes
/**
 * Build a credential instance from the key store entry.
 * 
 * @param keyStoreEntry the key store entry to process
 * @param entityID the entityID to include in the credential
 * @param usage the usage type to include in the credential
 * @return the new credential instance, appropriate to the type of key store entry being processed
 * @throws SecurityException throw if there is a problem building a credential from the key store entry
 */
protected Credential buildCredential(KeyStore.Entry keyStoreEntry, String entityID, UsageType usage)
        throws SecurityException {

    log.debug("Building credential from keystore entry for entityID {}, usage type {}", entityID, usage);

    Credential credential = null;
    if (keyStoreEntry instanceof KeyStore.PrivateKeyEntry) {
        credential = processPrivateKeyEntry((KeyStore.PrivateKeyEntry) keyStoreEntry, entityID, keystoreUsage);
    } else if (keyStoreEntry instanceof KeyStore.TrustedCertificateEntry) {
        credential = processTrustedCertificateEntry((KeyStore.TrustedCertificateEntry) keyStoreEntry, entityID,
                keystoreUsage);
    } else if (keyStoreEntry instanceof KeyStore.SecretKeyEntry) {
        credential = processSecretKeyEntry((KeyStore.SecretKeyEntry) keyStoreEntry, entityID, keystoreUsage);
    } else {
        throw new SecurityException("KeyStore entry was of an unsupported type: "
                + keyStoreEntry.getClass().getName());
    }
    return credential;
}
 
Example 4
Project: jdk8u-jdk   File: PKCS12KeyStore.java   View Source Code Vote up 6 votes
/**
 * Determines if the keystore {@code Entry} for the specified
 * {@code alias} is an instance or subclass of the specified
 * {@code entryClass}.
 *
 * @param alias the alias name
 * @param entryClass the entry class
 *
 * @return true if the keystore {@code Entry} for the specified
 *          {@code alias} is an instance or subclass of the
 *          specified {@code entryClass}, false otherwise
 *
 * @since 1.5
 */
@Override
public boolean
    engineEntryInstanceOf(String alias,
                          Class<? extends KeyStore.Entry> entryClass)
{
    if (entryClass == KeyStore.TrustedCertificateEntry.class) {
        return engineIsCertificateEntry(alias);
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (entryClass == KeyStore.PrivateKeyEntry.class) {
        return (entry != null && entry instanceof PrivateKeyEntry);
    }
    if (entryClass == KeyStore.SecretKeyEntry.class) {
        return (entry != null && entry instanceof SecretKeyEntry);
    }
    return false;
}
 
Example 5
Project: openjdk-jdk10   File: PKCS12KeyStore.java   View Source Code Vote up 6 votes
/**
 * Determines if the keystore {@code Entry} for the specified
 * {@code alias} is an instance or subclass of the specified
 * {@code entryClass}.
 *
 * @param alias the alias name
 * @param entryClass the entry class
 *
 * @return true if the keystore {@code Entry} for the specified
 *          {@code alias} is an instance or subclass of the
 *          specified {@code entryClass}, false otherwise
 *
 * @since 1.5
 */
@Override
public boolean
    engineEntryInstanceOf(String alias,
                          Class<? extends KeyStore.Entry> entryClass)
{
    if (entryClass == KeyStore.TrustedCertificateEntry.class) {
        return engineIsCertificateEntry(alias);
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (entryClass == KeyStore.PrivateKeyEntry.class) {
        return (entry != null && entry instanceof PrivateKeyEntry);
    }
    if (entryClass == KeyStore.SecretKeyEntry.class) {
        return (entry != null && entry instanceof SecretKeyEntry);
    }
    return false;
}
 
Example 6
Project: elasticsearch_my   File: KeyStoreWrapper.java   View Source Code Vote up 5 votes
/** Retrieve a string setting. The {@link SecureString} should be closed once it is used. */
@Override
public SecureString getString(String setting) throws GeneralSecurityException {
    KeyStore.Entry entry = keystore.get().getEntry(setting, keystorePassword.get());
    if (entry instanceof KeyStore.SecretKeyEntry == false) {
        throw new IllegalStateException("Secret setting " + setting + " is not a string");
    }
    // TODO: only allow getting a setting once?
    KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry) entry;
    PBEKeySpec keySpec = (PBEKeySpec) secretFactory.getKeySpec(secretKeyEntry.getSecretKey(), PBEKeySpec.class);
    SecureString value = new SecureString(keySpec.getPassword());
    keySpec.clearPassword();
    return value;
}
 
Example 7
Project: jdk8u-jdk   File: P12SecretKey.java   View Source Code Vote up 5 votes
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 8
Project: openjdk-jdk10   File: P12SecretKey.java   View Source Code Vote up 5 votes
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 9
Project: fresco_floodlight   File: CryptoUtil.java   View Source Code Vote up 5 votes
public static byte[] getSharedSecret(String keyStorePath,
                                     String keyStorePassword) 
                                                throws Exception {
    if (keyStorePath == null) return null;
    char[] password = keyStorePassword.toCharArray();
    KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(password);

    KeyStore ks = readKeyStore(keyStorePath, password);

    KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)
            ks.getEntry(CHALLENGE_RESPONSE_SECRET, protParam);
    SecretKey secretKey = entry.getSecretKey();
    return secretKey.getEncoded();
}
 
Example 10
Project: iTAP-controller   File: CryptoUtil.java   View Source Code Vote up 5 votes
public static byte[] getSharedSecret(String keyStorePath,
                                     String keyStorePassword) 
                                                throws Exception {
    if (keyStorePath == null) return null;
    char[] password = keyStorePassword.toCharArray();
    KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(password);

    KeyStore ks = readKeyStore(keyStorePath, password);

    KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)
            ks.getEntry(CHALLENGE_RESPONSE_SECRET, protParam);
    SecretKey secretKey = entry.getSecretKey();
    return secretKey.getEncoded();
}
 
Example 11
Project: OpenJSharp   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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
Project: uroborosql   File: SecretColumnSqlFilter.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 *
 * @see jp.co.future.uroborosql.filter.AbstractSqlFilter#initialize()
 */
@Override
public void initialize() {
	if (getCryptColumnNames() == null || getCryptColumnNames().isEmpty()) {
		setSkipFilter(true);
		return;
	} else {
		cryptParamKeys = new ArrayList<>();
		List<String> newColumnNames = new ArrayList<>();
		for (String columnName : getCryptColumnNames()) {
			cryptParamKeys.add(CaseFormat.CAMEL_CASE.convert(columnName));
			newColumnNames.add(CaseFormat.UPPER_SNAKE_CASE.convert(columnName));
		}
		// 定義ファイルで指定されたカラム名は大文字でない可能性があるので、ここで大文字に置換し直す
		cryptColumnNames = newColumnNames;
	}

	KeyStore store;
	try {
		if (StringUtils.isBlank(getKeyStoreFilePath())) {
			LOG.error("Invalid KeyStore file path. Path:{}", getKeyStoreFilePath());
			setSkipFilter(true);
			return;
		}
		File storeFile = new File(getKeyStoreFilePath());
		if (!storeFile.exists()) {
			LOG.error("Not found KeyStore file path. Path:{}", getKeyStoreFilePath());
			setSkipFilter(true);
			return;
		}
		if (storeFile.isDirectory()) {
			LOG.error("Invalid KeyStore file path. Path:{}", getKeyStoreFilePath());
			setSkipFilter(true);
			return;
		}
		if (StringUtils.isBlank(getStorePassword())) {
			LOG.error("Invalid password for access KeyStore.");
			setSkipFilter(true);
			return;
		}
		if (StringUtils.isBlank(getAlias())) {
			LOG.error("KeyStoreにアクセスするためのエイリアスが指定されていません。");
			LOG.error("No alias for access KeyStore.");
			setSkipFilter(true);
			return;
		}

		store = KeyStore.getInstance("JCEKS");

		char[] pass;
		try (InputStream is = new BufferedInputStream(new FileInputStream(storeFile))) {
			pass = new String(Base64.getUrlDecoder().decode(getStorePassword())).toCharArray();

			store.load(is, pass);
		}

		KeyStore.SecretKeyEntry entry = (SecretKeyEntry) store.getEntry(getAlias(),
				new KeyStore.PasswordProtection(pass));

		secretKey = entry.getSecretKey();
		encryptCipher = Cipher.getInstance(transformationType);
		encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
	} catch (Exception ex) {
		LOG.error("Failed to acquire secret key. Cause:{}", ex.getMessage());
		setSkipFilter(true);
		ex.printStackTrace();
	}
}
 
Example 13
Project: jdk8u-jdk   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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
Project: openjdk-jdk10   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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
Project: fresco_floodlight   File: CryptoUtil.java   View Source Code Vote up 4 votes
public static void writeSharedSecret(String keyStorePath,
                                     String keyStorePassword,
                                     byte[] sharedSecret) 
                                               throws Exception {
    char[] password = keyStorePassword.toCharArray();
    KeyStore ks;
    try {
        ks = readKeyStore(keyStorePath, password);
    } catch (FileNotFoundException e) {
        ks = KeyStore.getInstance("JCEKS");
        ks.load(null, password);
    } 

    KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(password);
    SecretKeySpec signingKey = 
            new SecretKeySpec(sharedSecret, "HmacSHA1");
    KeyStore.SecretKeyEntry skEntry =
            new KeyStore.SecretKeyEntry(signingKey);
    ks.setEntry(CHALLENGE_RESPONSE_SECRET, skEntry, protParam);

    // store away the keystore
    java.io.FileOutputStream fos = null;
    File keyStoreFile = new File(keyStorePath);
    File parent = keyStoreFile.getParentFile();
    if (parent != null)
        parent.mkdirs();
    try {
        fos = new java.io.FileOutputStream(keyStoreFile);
        ks.store(fos, password);
        keyStoreFile.setReadable(false, false);
        keyStoreFile.setReadable(true, true);
        keyStoreFile.setWritable(false, false);
        keyStoreFile.setWritable(true, true);
        keyStoreFile.setExecutable(false, false);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}
 
Example 16
Project: iTAP-controller   File: CryptoUtil.java   View Source Code Vote up 4 votes
public static void writeSharedSecret(String keyStorePath,
                                     String keyStorePassword,
                                     byte[] sharedSecret) 
                                               throws Exception {
    char[] password = keyStorePassword.toCharArray();
    KeyStore ks;
    try {
        ks = readKeyStore(keyStorePath, password);
    } catch (FileNotFoundException e) {
        ks = KeyStore.getInstance("JCEKS");
        ks.load(null, password);
    } 

    KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(password);
    SecretKeySpec signingKey = 
            new SecretKeySpec(sharedSecret, "HmacSHA1");
    KeyStore.SecretKeyEntry skEntry =
            new KeyStore.SecretKeyEntry(signingKey);
    ks.setEntry(CHALLENGE_RESPONSE_SECRET, skEntry, protParam);

    // store away the keystore
    java.io.FileOutputStream fos = null;
    File keyStoreFile = new File(keyStorePath);
    File parent = keyStoreFile.getParentFile();
    if (parent != null)
        parent.mkdirs();
    try {
        fos = new java.io.FileOutputStream(keyStoreFile);
        ks.store(fos, password);
        keyStoreFile.setReadable(false, false);
        keyStoreFile.setReadable(true, true);
        keyStoreFile.setWritable(false, false);
        keyStoreFile.setWritable(true, true);
        keyStoreFile.setExecutable(false, false);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}