Search in sources :

Example 36 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project nifi by apache.

the class OpenSSLPKCS5CipherProvider method getInitializedCipher.

protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, boolean encryptMode) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
    if (encryptionMethod == null) {
        throw new IllegalArgumentException("The encryption method must be specified");
    }
    if (StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException("Encryption with an empty password is not supported");
    }
    validateSalt(encryptionMethod, salt);
    String algorithm = encryptionMethod.getAlgorithm();
    String provider = encryptionMethod.getProvider();
    // Initialize secret key from password
    final PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
    final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, provider);
    SecretKey tempKey = factory.generateSecret(pbeKeySpec);
    final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, getIterationCount());
    Cipher cipher = Cipher.getInstance(algorithm, provider);
    cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, tempKey, parameterSpec);
    return cipher;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 37 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project entando-core by entando.

the class PageTokenManager method decrypt.

@Override
public String decrypt(String property) {
    SecretKeyFactory keyFactory;
    try {
        keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(this.getPasswordCharArray()));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(this.getSalt().getBytes(), 20));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    } catch (GeneralSecurityException e) {
        logger.error("Error in decrypt");
    } catch (IOException e) {
        logger.error("Error in decrypt");
    }
    return null;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher) IOException(java.io.IOException) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 38 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project webofneeds by researchstudio-sat.

the class KeystorePasswordUtils method generatePassword.

/**
 * Generates a 1000-fold hash of the specified string toHash, using saltString
 * as salt if non-null.
 *
 * @param toHash
 * @param hashLength
 *            in bits
 * @param saltString
 *            must be a hexadecimal number
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static String generatePassword(String toHash, int hashLength) {
    try {
        int iterations = 1000;
        char[] chars = toHash.toCharArray();
        byte[] salt = getSalt();
        PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, hashLength);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = skf.generateSecret(spec).getEncoded();
        return CURRENT_VERSION + ":" + iterations + ":" + toHex(salt) + ":" + Base64.getEncoder().encodeToString(hash);
    } catch (Exception e) {
        throw new RuntimeException("could not generate key", e);
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKeyFactory(javax.crypto.SecretKeyFactory) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 39 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project webofneeds by researchstudio-sat.

the class KeystorePasswordUtils method encryptPassword.

/*
	public static void main(String... args) {
		String password = "supersecretpassword";
		String key = "mykey";
		StopWatch sw = new StopWatch();
		sw.start();
		System.out.println("encrypting...");
		String encrypted = encryptPassword(password, key);
		sw.stop();
		System.out.println("took " + sw.getLastTaskTimeMillis());
		sw.start();
		System.out.println("encrypting " + password + " with key " + key + " to: " + encrypted);
		String decrypted = decryptPassword(encrypted, key);
		System.out.println("decrypting again yields: " + decrypted);
		sw.stop();
		System.out.println("took " + sw.getLastTaskTimeMillis());

		System.out.println("generating password: " + generatePassword("abebu", 256, null));
	}*/
public static String encryptPassword(String password, String key) {
    try {
        int iterations = 1000;
        byte[] salt = getSalt();
        byte[] iv = getSalt();
        PBEKeySpec spec = new PBEKeySpec(key.toCharArray(), salt, iterations, 256);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] encryptionKey = skf.generateSecret(spec).getEncoded();
        SecretKeySpec secretKey = new SecretKeySpec(encryptionKey, "AES");
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm() + "/CFB8/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
        return CURRENT_VERSION + ":" + iterations + ":" + toHex(salt) + ":" + toHex(iv) + ":" + toHex(cipher.doFinal(password.getBytes()));
    } catch (Exception e) {
        throw new IllegalArgumentException("cannot encrypt password", e);
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 40 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project jdk8u_jdk by JetBrains.

the class Pair method doGenSecretKey.

/**
     * Creates a new secret key.
     */
private void doGenSecretKey(String alias, String keyAlgName, int keysize) throws Exception {
    if (alias == null) {
        alias = keyAlias;
    }
    if (keyStore.containsAlias(alias)) {
        MessageFormat form = new MessageFormat(rb.getString("Secret.key.not.generated.alias.alias.already.exists"));
        Object[] source = { alias };
        throw new Exception(form.format(source));
    }
    // Use the keystore's default PBE algorithm for entry protection
    boolean useDefaultPBEAlgorithm = true;
    SecretKey secKey = null;
    if (keyAlgName.toUpperCase(Locale.ENGLISH).startsWith("PBE")) {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");
        // User is prompted for PBE credential
        secKey = factory.generateSecret(new PBEKeySpec(promptForCredential()));
        // Check whether a specific PBE algorithm was specified
        if (!"PBE".equalsIgnoreCase(keyAlgName)) {
            useDefaultPBEAlgorithm = false;
        }
        if (verbose) {
            MessageFormat form = new MessageFormat(rb.getString("Generated.keyAlgName.secret.key"));
            Object[] source = { useDefaultPBEAlgorithm ? "PBE" : secKey.getAlgorithm() };
            System.err.println(form.format(source));
        }
    } else {
        KeyGenerator keygen = KeyGenerator.getInstance(keyAlgName);
        if (keysize == -1) {
            if ("DES".equalsIgnoreCase(keyAlgName)) {
                keysize = 56;
            } else if ("DESede".equalsIgnoreCase(keyAlgName)) {
                keysize = 168;
            } else {
                throw new Exception(rb.getString("Please.provide.keysize.for.secret.key.generation"));
            }
        }
        keygen.init(keysize);
        secKey = keygen.generateKey();
        if (verbose) {
            MessageFormat form = new MessageFormat(rb.getString("Generated.keysize.bit.keyAlgName.secret.key"));
            Object[] source = { new Integer(keysize), secKey.getAlgorithm() };
            System.err.println(form.format(source));
        }
    }
    if (keyPass == null) {
        keyPass = promptForKeyPass(alias, null, storePass);
    }
    if (useDefaultPBEAlgorithm) {
        keyStore.setKeyEntry(alias, secKey, keyPass, null);
    } else {
        keyStore.setEntry(alias, new KeyStore.SecretKeyEntry(secKey), new KeyStore.PasswordProtection(keyPass, keyAlgName, null));
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) MessageFormat(java.text.MessageFormat) KeyStore(java.security.KeyStore) 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) BigInteger(java.math.BigInteger) SecretKey(javax.crypto.SecretKey) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyGenerator(javax.crypto.KeyGenerator)

Aggregations

PBEKeySpec (javax.crypto.spec.PBEKeySpec)249 SecretKeyFactory (javax.crypto.SecretKeyFactory)190 SecretKey (javax.crypto.SecretKey)118 Cipher (javax.crypto.Cipher)82 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)63 KeySpec (java.security.spec.KeySpec)59 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)59 SecretKeySpec (javax.crypto.spec.SecretKeySpec)49 IOException (java.io.IOException)25 KeyStoreException (java.security.KeyStoreException)23 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)22 EncryptedPrivateKeyInfo (javax.crypto.EncryptedPrivateKeyInfo)17 CertificateException (java.security.cert.CertificateException)15 GeneralSecurityException (java.security.GeneralSecurityException)14 UnrecoverableKeyException (java.security.UnrecoverableKeyException)14 AlgorithmParameters (java.security.AlgorithmParameters)13 Key (java.security.Key)13 KeyStore (java.security.KeyStore)13 InvalidKeyException (java.security.InvalidKeyException)12