Search in sources :

Example 36 with UnrecoverableKeyException

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

the class PKCS12KeyStore method encryptPrivateKey.

/*
     * Encrypt private key using Password-based encryption (PBE)
     * as defined in PKCS#5.
     *
     * NOTE: By default, pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
     *       used to derive the key and IV.
     *
     * @return encrypted private key encoded as EncryptedPrivateKeyInfo
     */
private byte[] encryptPrivateKey(byte[] data, KeyStore.PasswordProtection passwordProtection) throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
    byte[] key = null;
    try {
        String algorithm;
        AlgorithmParameters algParams;
        AlgorithmId algid;
        // Initialize PBE algorithm and parameters
        algorithm = passwordProtection.getProtectionAlgorithm();
        if (algorithm != null) {
            AlgorithmParameterSpec algParamSpec = passwordProtection.getProtectionParameters();
            if (algParamSpec != null) {
                algParams = AlgorithmParameters.getInstance(algorithm);
                algParams.init(algParamSpec);
            } else {
                algParams = getAlgorithmParameters(algorithm);
            }
        } else {
            // Check default key protection algorithm for PKCS12 keystores
            algorithm = AccessController.doPrivileged(new PrivilegedAction<String>() {

                public String run() {
                    String prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[0]);
                    if (prop == null) {
                        prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[1]);
                    }
                    return prop;
                }
            });
            if (algorithm == null || algorithm.isEmpty()) {
                algorithm = "PBEWithSHA1AndDESede";
            }
            algParams = getAlgorithmParameters(algorithm);
        }
        ObjectIdentifier pbeOID = mapPBEAlgorithmToOID(algorithm);
        if (pbeOID == null) {
            throw new IOException("PBE algorithm '" + algorithm + " 'is not supported for key entry protection");
        }
        // Use JCE
        SecretKey skey = getPBEKey(passwordProtection.getPassword());
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
        byte[] encryptedKey = cipher.doFinal(data);
        algid = new AlgorithmId(pbeOID, cipher.getParameters());
        if (debug != null) {
            debug.println("  (Cipher algorithm: " + cipher.getAlgorithm() + ")");
        }
        // wrap encrypted private key in EncryptedPrivateKeyInfo
        // as defined in PKCS#8
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey);
        key = encrInfo.getEncoded();
    } catch (Exception e) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage());
        uke.initCause(e);
        throw uke;
    }
    return key;
}
Also used : 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) UnrecoverableKeyException(java.security.UnrecoverableKeyException) AlgorithmId(sun.security.x509.AlgorithmId) PrivilegedAction(java.security.PrivilegedAction) EncryptedPrivateKeyInfo(sun.security.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) AlgorithmParameters(java.security.AlgorithmParameters) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 37 with UnrecoverableKeyException

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

the class JceKeyStore 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 void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    synchronized (entries) {
        DataInputStream dis;
        MessageDigest md = null;
        CertificateFactory cf = null;
        Hashtable<String, CertificateFactory> cfs = null;
        ByteArrayInputStream bais = null;
        byte[] encoded = null;
        if (stream == null)
            return;
        if (password != null) {
            md = getPreKeyedHash(password);
            dis = new DataInputStream(new DigestInputStream(stream, md));
        } else {
            dis = new DataInputStream(stream);
        }
        // NOTE: don't pass dis to ois at this point or it'll fail to load
        // the keystore!!!
        ObjectInputStream ois = null;
        try {
            // Body format: see store method
            int xMagic = dis.readInt();
            int xVersion = dis.readInt();
            //   versions 1 and 2
            if (((xMagic != JCEKS_MAGIC) && (xMagic != JKS_MAGIC)) || ((xVersion != VERSION_1) && (xVersion != VERSION_2))) {
                throw new IOException("Invalid keystore format");
            }
            if (xVersion == VERSION_1) {
                cf = CertificateFactory.getInstance("X509");
            } else {
                // version 2
                cfs = new Hashtable<String, CertificateFactory>(3);
            }
            entries.clear();
            int count = dis.readInt();
            for (int i = 0; i < count; i++) {
                int tag;
                String alias;
                tag = dis.readInt();
                if (tag == 1) {
                    // private-key entry
                    PrivateKeyEntry entry = new PrivateKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the private key
                    try {
                        entry.protectedKey = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Keysize too big");
                    }
                    dis.readFully(entry.protectedKey);
                    // read the certificate chain
                    int numOfCerts = dis.readInt();
                    try {
                        if (numOfCerts > 0) {
                            entry.chain = new Certificate[numOfCerts];
                        }
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Too many certificates in " + "chain");
                    }
                    for (int j = 0; j < numOfCerts; j++) {
                        if (xVersion == 2) {
                            // read the certificate type, and instantiate a
                            // certificate factory of that type (reuse
                            // existing factory if possible)
                            String certType = dis.readUTF();
                            if (cfs.containsKey(certType)) {
                                // reuse certificate factory
                                cf = cfs.get(certType);
                            } else {
                                // create new certificate factory
                                cf = CertificateFactory.getInstance(certType);
                                // store the certificate factory so we can
                                // reuse it later
                                cfs.put(certType, cf);
                            }
                        }
                        // instantiate the certificate
                        try {
                            encoded = new byte[dis.readInt()];
                        } catch (OutOfMemoryError e) {
                            throw new IOException("Certificate too big");
                        }
                        dis.readFully(encoded);
                        bais = new ByteArrayInputStream(encoded);
                        entry.chain[j] = cf.generateCertificate(bais);
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 2) {
                    // trusted certificate entry
                    TrustedCertEntry entry = new TrustedCertEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the trusted certificate
                    if (xVersion == 2) {
                        // read the certificate type, and instantiate a
                        // certificate factory of that type (reuse
                        // existing factory if possible)
                        String certType = dis.readUTF();
                        if (cfs.containsKey(certType)) {
                            // reuse certificate factory
                            cf = cfs.get(certType);
                        } else {
                            // create new certificate factory
                            cf = CertificateFactory.getInstance(certType);
                            // store the certificate factory so we can
                            // reuse it later
                            cfs.put(certType, cf);
                        }
                    }
                    try {
                        encoded = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Certificate too big");
                    }
                    dis.readFully(encoded);
                    bais = new ByteArrayInputStream(encoded);
                    entry.cert = cf.generateCertificate(bais);
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 3) {
                    // secret-key entry
                    SecretKeyEntry entry = new SecretKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the sealed key
                    try {
                        ois = new ObjectInputStream(dis);
                        entry.sealedKey = (SealedObject) ois.readObject();
                    // NOTE: don't close ois here since we are still
                    // using dis!!!
                    } catch (ClassNotFoundException cnfe) {
                        throw new IOException(cnfe.getMessage());
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else {
                    throw new IOException("Unrecognized keystore entry");
                }
            }
            /*
                 * If a password has been provided, we check the keyed digest
                 * at the end. If this check fails, the store has been tampered
                 * with
                 */
            if (password != null) {
                byte[] computed, actual;
                computed = md.digest();
                actual = new byte[computed.length];
                dis.readFully(actual);
                for (int i = 0; i < computed.length; i++) {
                    if (computed[i] != actual[i]) {
                        throw new IOException("Keystore was tampered with, or " + "password was incorrect", new UnrecoverableKeyException("Password verification failed"));
                    }
                }
            }
        } finally {
            if (ois != null) {
                ois.close();
            } else {
                dis.close();
            }
        }
    }
}
Also used : DigestInputStream(java.security.DigestInputStream) CertificateFactory(java.security.cert.CertificateFactory) UnrecoverableKeyException(java.security.UnrecoverableKeyException) MessageDigest(java.security.MessageDigest)

Example 38 with UnrecoverableKeyException

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

the class JceKeyStore 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 {
    Key key = null;
    Object entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (!((entry instanceof PrivateKeyEntry) || (entry instanceof SecretKeyEntry))) {
        return null;
    }
    KeyProtector keyProtector = new KeyProtector(password);
    if (entry instanceof PrivateKeyEntry) {
        byte[] encrBytes = ((PrivateKeyEntry) entry).protectedKey;
        EncryptedPrivateKeyInfo encrInfo;
        try {
            encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
        } catch (IOException ioe) {
            throw new UnrecoverableKeyException("Private key not stored " + "as PKCS #8 " + "EncryptedPrivateKeyInfo");
        }
        key = keyProtector.recover(encrInfo);
    } else {
        key = keyProtector.unseal(((SecretKeyEntry) entry).sealedKey);
    }
    return key;
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) SealedObject(javax.crypto.SealedObject) Key(java.security.Key) PrivateKey(java.security.PrivateKey)

Example 39 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreProvider method loadAndroidKeyStorePublicKeyFromKeystore.

@NonNull
public static AndroidKeyStorePublicKey loadAndroidKeyStorePublicKeyFromKeystore(@NonNull KeyStore keyStore, @NonNull String privateKeyAlias, int uid) throws UnrecoverableKeyException {
    KeyCharacteristics keyCharacteristics = new KeyCharacteristics();
    int errorCode = keyStore.getKeyCharacteristics(privateKeyAlias, null, null, uid, keyCharacteristics);
    if (errorCode != KeyStore.NO_ERROR) {
        throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to obtain information about private key").initCause(KeyStore.getKeyStoreException(errorCode));
    }
    ExportResult exportResult = keyStore.exportKey(privateKeyAlias, KeymasterDefs.KM_KEY_FORMAT_X509, null, null, uid);
    if (exportResult.resultCode != KeyStore.NO_ERROR) {
        throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to obtain X.509 form of public key").initCause(KeyStore.getKeyStoreException(exportResult.resultCode));
    }
    final byte[] x509EncodedPublicKey = exportResult.exportData;
    Integer keymasterAlgorithm = keyCharacteristics.getEnum(KeymasterDefs.KM_TAG_ALGORITHM);
    if (keymasterAlgorithm == null) {
        throw new UnrecoverableKeyException("Key algorithm unknown");
    }
    String jcaKeyAlgorithm;
    try {
        jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm(keymasterAlgorithm);
    } catch (IllegalArgumentException e) {
        throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to load private key").initCause(e);
    }
    return AndroidKeyStoreProvider.getAndroidKeyStorePublicKey(privateKeyAlias, uid, jcaKeyAlgorithm, x509EncodedPublicKey);
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyCharacteristics(android.security.keymaster.KeyCharacteristics) ExportResult(android.security.keymaster.ExportResult) NonNull(android.annotation.NonNull)

Example 40 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project android_frameworks_base by crdroidandroid.

the class LockSettingsService method setLockPasswordInternal.

private void setLockPasswordInternal(String password, String savedCredential, int userId) throws RemoteException {
    byte[] currentHandle = getCurrentHandle(userId);
    if (password == null) {
        clearUserKeyProtection(userId);
        getGateKeeperService().clearSecureUserId(userId);
        mStorage.writePasswordHash(null, userId);
        setKeystorePassword(null, userId);
        fixateNewestUserKeyAuth(userId);
        onUserLockChanged(userId);
        notifyActivePasswordMetricsAvailable(null, userId);
        return;
    }
    if (isManagedProfileWithUnifiedLock(userId)) {
        // get credential from keystore when managed profile has unified lock
        try {
            savedCredential = getDecryptedPasswordForTiedProfile(userId);
        } catch (FileNotFoundException e) {
            Slog.i(TAG, "Child profile key not found");
        } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
            Slog.e(TAG, "Failed to decrypt child profile key", e);
        }
    } else {
        if (currentHandle == null) {
            if (savedCredential != null) {
                Slog.w(TAG, "Saved credential provided, but none stored");
            }
            savedCredential = null;
        }
    }
    byte[] enrolledHandle = enrollCredential(currentHandle, savedCredential, password, userId);
    if (enrolledHandle != null) {
        CredentialHash willStore = new CredentialHash(enrolledHandle, CredentialHash.VERSION_GATEKEEPER);
        setUserKeyProtection(userId, password, doVerifyPassword(password, willStore, true, 0, userId, null));
        mStorage.writePasswordHash(enrolledHandle, userId);
        fixateNewestUserKeyAuth(userId);
        onUserLockChanged(userId);
    } else {
        throw new RemoteException("Failed to enroll password");
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CredentialHash(com.android.server.LockSettingsStorage.CredentialHash) FileNotFoundException(java.io.FileNotFoundException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RemoteException(android.os.RemoteException)

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