Search in sources :

Example 86 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project pratilipi by Pratilipi.

the class PasswordUtil method hash.

// using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt
// cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html
private static String hash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
    if (password == null || password.length() == 0)
        throw new IllegalArgumentException("Empty passwords are not supported.");
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
    return Base64.encodeBase64String(key.getEncoded());
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 87 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project android_frameworks_base by ResurrectionRemix.

the class BackupManagerService method buildCharArrayKey.

private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
        return keyFactory.generateSecret(ks);
    } catch (InvalidKeySpecException e) {
        Slog.e(TAG, "Invalid key spec for PBKDF2!");
    } catch (NoSuchAlgorithmException e) {
        Slog.e(TAG, "PBKDF2 unavailable!");
    }
    return null;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 88 with PBEKeySpec

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

the class PKCS12KeyStore method engineGetKey.

/**
     * Returns the key associated with the given alias, using the given
     * password to recover it.
     *
     * @param alias the alias name
     * @param password the password for recovering the key
     *
     * @return the requested key, or null if the given alias does not exist
     * or does not identify a <i>key entry</i>.
     *
     * @exception NoSuchAlgorithmException if the algorithm for recovering the
     * key cannot be found
     * @exception UnrecoverableKeyException if the key cannot be recovered
     * (e.g., the given password is wrong).
     */
public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException {
    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    Key key = null;
    if (entry == null || (!(entry instanceof KeyEntry))) {
        return null;
    }
    // get the encoded private key or secret key
    byte[] encrBytes = null;
    if (entry instanceof PrivateKeyEntry) {
        encrBytes = ((PrivateKeyEntry) entry).protectedPrivKey;
    } else if (entry instanceof SecretKeyEntry) {
        encrBytes = ((SecretKeyEntry) entry).protectedSecretKey;
    } else {
        throw new UnrecoverableKeyException("Error locating key");
    }
    byte[] encryptedKey;
    AlgorithmParameters algParams;
    ObjectIdentifier algOid;
    try {
        // get the encrypted private key
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
        encryptedKey = encrInfo.getEncryptedData();
        // parse Algorithm parameters
        DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
        DerInputStream in = val.toDerInputStream();
        algOid = in.getOID();
        algParams = parseAlgParameters(algOid, in);
    } catch (IOException ioe) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
        uke.initCause(ioe);
        throw uke;
    }
    try {
        byte[] keyInfo;
        while (true) {
            try {
                // Use JCE
                SecretKey skey = getPBEKey(password);
                Cipher cipher = Cipher.getInstance(mapPBEParamsToAlgorithm(algOid, algParams));
                cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
                keyInfo = cipher.doFinal(encryptedKey);
                break;
            } catch (Exception e) {
                if (password.length == 0) {
                    // Retry using an empty password
                    // without a NULL terminator.
                    password = new char[1];
                    continue;
                }
                throw e;
            }
        }
        /*
             * Parse the key algorithm and then use a JCA key factory
             * to re-create the key.
             */
        DerValue val = new DerValue(keyInfo);
        DerInputStream in = val.toDerInputStream();
        int i = in.getInteger();
        DerValue[] value = in.getSequence(2);
        AlgorithmId algId = new AlgorithmId(value[0].getOID());
        String keyAlgo = algId.getName();
        // decode private key
        if (entry instanceof PrivateKeyEntry) {
            KeyFactory kfac = KeyFactory.getInstance(keyAlgo);
            PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(keyInfo);
            key = kfac.generatePrivate(kspec);
            if (debug != null) {
                debug.println("Retrieved a protected private key (" + key.getClass().getName() + ") at alias '" + alias + "'");
            }
        // decode secret key
        } else {
            byte[] keyBytes = in.getOctetString();
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, keyAlgo);
            // Special handling required for PBE: needs a PBEKeySpec
            if (keyAlgo.startsWith("PBE")) {
                SecretKeyFactory sKeyFactory = SecretKeyFactory.getInstance(keyAlgo);
                KeySpec pbeKeySpec = sKeyFactory.getKeySpec(secretKeySpec, PBEKeySpec.class);
                key = sKeyFactory.generateSecret(pbeKeySpec);
            } else {
                key = secretKeySpec;
            }
            if (debug != null) {
                debug.println("Retrieved a protected secret key (" + key.getClass().getName() + ") at alias '" + alias + "'");
            }
        }
    } catch (Exception e) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
        uke.initCause(e);
        throw uke;
    }
    return key;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) DerValue(sun.security.util.DerValue) DerInputStream(sun.security.util.DerInputStream) SecretKeyFactory(javax.crypto.SecretKeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory) 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) SecretKey(javax.crypto.SecretKey) AlgorithmId(sun.security.x509.AlgorithmId) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(sun.security.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) AlgorithmParameters(java.security.AlgorithmParameters)

Example 89 with PBEKeySpec

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

the class PKCS12KeyStore method getPBEKey.

/*
     * Generate PBE key
     */
private SecretKey getPBEKey(char[] password) throws IOException {
    SecretKey skey = null;
    try {
        PBEKeySpec keySpec = new PBEKeySpec(password);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        skey = skFac.generateSecret(keySpec);
        keySpec.clearPassword();
    } catch (Exception e) {
        throw new IOException("getSecretKey failed: " + e.getMessage(), e);
    }
    return skey;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) SecretKeyFactory(javax.crypto.SecretKeyFactory) 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)

Example 90 with PBEKeySpec

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

the class DefaultPBEWrapper method initCipher.

/**
     * Instantiate Cipher for the PBE algorithm.
     *
     * @param mode Cipher mode: encrypt or decrypt.
     * @return Cipher in accordance to the PBE algorithm
     * @throws java.security.GeneralSecurityException
     */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    SecretKey key = SecretKeyFactory.getInstance(baseAlgo).generateSecret(new PBEKeySpec(password.toCharArray()));
    Cipher ci = Cipher.getInstance(transformation, provider);
    ci.init(mode, key, new PBEParameterSpec(salt, DEFAULT_ITERATION));
    return ci;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) Provider(java.security.Provider)

Aggregations

PBEKeySpec (javax.crypto.spec.PBEKeySpec)110 SecretKeyFactory (javax.crypto.SecretKeyFactory)85 SecretKey (javax.crypto.SecretKey)60 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)39 Cipher (javax.crypto.Cipher)39 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)33 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)27 KeySpec (java.security.spec.KeySpec)26 SecretKeySpec (javax.crypto.spec.SecretKeySpec)17 KeyStoreException (java.security.KeyStoreException)16 IOException (java.io.IOException)15 CertificateException (java.security.cert.CertificateException)12 UnrecoverableKeyException (java.security.UnrecoverableKeyException)11 KeyStore (java.security.KeyStore)10 CertificateEncodingException (java.security.cert.CertificateEncodingException)8 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)8 EncryptedPrivateKeyInfo (javax.crypto.EncryptedPrivateKeyInfo)8 Key (java.security.Key)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 InvalidKeyException (java.security.InvalidKeyException)6