Search in sources :

Example 66 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project robovm by robovm.

the class ProtectionParameterImpl method test_Constructor.

/**
     * Test for <code>KeyManagerFactory</code> constructor
     * Assertion: returns KeyManagerFactory object
     */
public void test_Constructor() throws NoSuchAlgorithmException {
    if (!DEFSupported) {
        fail(NotSupportedMsg);
        return;
    }
    KeyManagerFactorySpi spi = new MyKeyManagerFactorySpi();
    KeyManagerFactory keyMF = new myKeyManagerFactory(spi, defaultProvider, defaultAlgorithm);
    assertEquals("Incorrect algorithm", keyMF.getAlgorithm(), defaultAlgorithm);
    assertEquals("Incorrect provider", keyMF.getProvider(), defaultProvider);
    try {
        keyMF.init(null, new char[1]);
        fail("UnrecoverableKeyException must be thrown");
    } catch (UnrecoverableKeyException e) {
    } catch (Exception e) {
        fail("Unexpected: " + e.toString() + " was thrown");
    }
    keyMF = new myKeyManagerFactory(null, null, null);
    assertNull("Aalgorithm must be null", keyMF.getAlgorithm());
    assertNull("Provider must be null", keyMF.getProvider());
    try {
        keyMF.getKeyManagers();
    } catch (NullPointerException e) {
    }
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyManagerFactorySpi(javax.net.ssl.KeyManagerFactorySpi) MyKeyManagerFactorySpi(org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi) MyKeyManagerFactorySpi(org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchProviderException(java.security.NoSuchProviderException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 67 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project platform_frameworks_base by android.

the class AndroidKeyStoreProvider method loadAndroidKeyStoreSecretKeyFromKeystore.

@NonNull
public static AndroidKeyStoreSecretKey loadAndroidKeyStoreSecretKeyFromKeystore(@NonNull KeyStore keyStore, @NonNull String secretKeyAlias, int uid) throws UnrecoverableKeyException {
    KeyCharacteristics keyCharacteristics = new KeyCharacteristics();
    int errorCode = keyStore.getKeyCharacteristics(secretKeyAlias, null, null, uid, keyCharacteristics);
    if (errorCode != KeyStore.NO_ERROR) {
        throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to obtain information about key").initCause(KeyStore.getKeyStoreException(errorCode));
    }
    Integer keymasterAlgorithm = keyCharacteristics.getEnum(KeymasterDefs.KM_TAG_ALGORITHM);
    if (keymasterAlgorithm == null) {
        throw new UnrecoverableKeyException("Key algorithm unknown");
    }
    List<Integer> keymasterDigests = keyCharacteristics.getEnums(KeymasterDefs.KM_TAG_DIGEST);
    int keymasterDigest;
    if (keymasterDigests.isEmpty()) {
        keymasterDigest = -1;
    } else {
        // More than one digest can be permitted for this key. Use the first one to form the
        // JCA key algorithm name.
        keymasterDigest = keymasterDigests.get(0);
    }
    @KeyProperties.KeyAlgorithmEnum String keyAlgorithmString;
    try {
        keyAlgorithmString = KeyProperties.KeyAlgorithm.fromKeymasterSecretKeyAlgorithm(keymasterAlgorithm, keymasterDigest);
    } catch (IllegalArgumentException e) {
        throw (UnrecoverableKeyException) new UnrecoverableKeyException("Unsupported secret key type").initCause(e);
    }
    return new AndroidKeyStoreSecretKey(secretKeyAlias, uid, keyAlgorithmString);
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyCharacteristics(android.security.keymaster.KeyCharacteristics) NonNull(android.annotation.NonNull)

Example 68 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project nhin-d by DirectProject.

the class CreateSignedPKCS7 method create.

/**
	 * Creates a pcks7 file from the certificate and key files.
	 * @param anchorDir :The Directory where the .der files are present.
	 * @param createFile : The .p7m File name.
	 * @param metaFile :One XML file as per required specification of TrustBundle metadata schema. 
	 * @param p12certiFile : The .p12 file.
	 * @param passkey :Pass Key for the .p12 file if present or else it should be blank.
	 * @param destDir : The Destination folder where the output .p7m files will be created.
	 * 	 * @return File : Returns the created SignedBundle as a .p7m file.
	 */
public File create(String anchorDir, File createFile, File metaFile, boolean metaExists, File p12certiFile, String passKey) {
    File pkcs7File = null;
    FileOutputStream outStr = null;
    InputStream inStr = null;
    try {
        // Create the unsigned Trust Bundle
        CreateUnSignedPKCS7 unSignedPKCS7 = new CreateUnSignedPKCS7();
        File unsigned = unSignedPKCS7.create(anchorDir, createFile, metaFile, metaExists);
        byte[] unsignedByte = loadFileData(unsigned);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        CMSSignedData unsignedData = new CMSSignedData(unsignedByte);
        // Create the certificate array
        KeyStore ks = java.security.KeyStore.getInstance("PKCS12", "BC");
        ks.load(new FileInputStream(p12certiFile), defaultPwd.toCharArray());
        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            if (ks.getKey(alias, defaultPwd.toCharArray()) != null && ks.getKey(alias, defaultPwd.toCharArray()) instanceof PrivateKey) {
                ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build((PrivateKey) ks.getKey(alias, defaultPwd.toCharArray()));
                X509CertificateHolder holder = new X509CertificateHolder(ks.getCertificate(alias).getEncoded());
                certList.add((X509Certificate) ks.getCertificate(alias));
                gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, holder));
            }
        }
        Store certStores = new JcaCertStore(certList);
        gen.addCertificates(certStores);
        CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(unsignedData.getEncoded()), true);
        //SignedData encapInfo = SignedData.getInstance(sigData.getContentInfo().getContent());
        pkcs7File = getPKCS7OutFile(createFile);
        outStr = new FileOutputStream(pkcs7File);
        outStr.write(sigData.getEncoded());
    } catch (CMSException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (IOException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (KeyStoreException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (NoSuchProviderException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (NoSuchAlgorithmException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (CertificateException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (UnrecoverableKeyException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (OperatorCreationException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (Exception e) {
        // e.printStackTrace(System.err);
        return null;
    } finally {
        IOUtils.closeQuietly(outStr);
        IOUtils.closeQuietly(inStr);
    }
    return pkcs7File;
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) Store(org.bouncycastle.util.Store) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) KeyStore(java.security.KeyStore) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ContentSigner(org.bouncycastle.operator.ContentSigner) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) CMSException(org.bouncycastle.cms.CMSException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) FileOutputStream(java.io.FileOutputStream) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) NoSuchProviderException(java.security.NoSuchProviderException) File(java.io.File) CMSException(org.bouncycastle.cms.CMSException)

Example 69 with UnrecoverableKeyException

use of java.security.UnrecoverableKeyException in project nhin-d by DirectProject.

the class CreateUnSignedPKCS7 method create.

/**
	 * Creates a pcks7 file from the certificate and key files.
	 * @param certFile The X509 DER encoded certificate file.
	 * @param keyFile The PCKS8 DER encoded private key file.
	 * @param password Option password for the private key file.  This is required if the private key file is encrypted.  Should be null or empty
	 * if the private key file is not encrypted.
	 * @param createFile Optional file descriptor for the output file of the pkcs12 file.  If this is null, the file name is based on the 
	 * certificate file name.
	 * @return File descriptor of the created pcks7 file.  Null if an error occurred.  
	 */
public File create(String anchorDir, File createFile, File metaFile, boolean metaExists) {
    File pkcs7File = null;
    FileOutputStream outStr = null;
    InputStream inStr = null;
    // load cert file
    try {
        File userDir = new File(anchorDir);
        File[] files = userDir.listFiles();
        X509Certificate[] certs = new X509Certificate[files.length];
        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        int counter = 0;
        for (File certFile : files) {
            if (certFile.isFile() && !certFile.isHidden()) {
                if (certFile.getName().endsWith(".der")) {
                    byte[] certData = loadFileData(certFile);
                    certs[counter] = getX509Certificate(certData);
                    certList.add(certs[counter]);
                    counter++;
                }
            }
        }
        if (counter == 0) {
            error = "Trust Anchors are not available in specified folder!";
            return null;
        }
        byte[] metaDataByte;
        if (metaExists) {
            metaDataByte = loadFileData(metaFile);
        } else {
            metaDataByte = "Absent".getBytes();
        }
        CMSTypedData msg = new CMSProcessableByteArray(metaDataByte);
        Store certStores = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        //SignedData data = new SignedData(arg0, arg1, arg2, arg3, arg4)
        gen.addCertificates(certStores);
        CMSSignedData sigData = gen.generate(msg, metaExists);
        //System.out.println("Inside Unsigned area: Create File:"+createFile);
        pkcs7File = getPKCS7OutFile(createFile);
        outStr = new FileOutputStream(pkcs7File);
        outStr.write(sigData.getEncoded());
    } catch (CMSException e) {
        //e.printStackTrace(System.err);
        return null;
    } catch (IOException e) {
        //e.printStackTrace(System.err);
        return null;
    } catch (KeyStoreException e) {
        //e.printStackTrace(System.err);
        return null;
    } catch (NoSuchProviderException e) {
        //e.printStackTrace(System.err);
        return null;
    } catch (NoSuchAlgorithmException e) {
        //e.printStackTrace(System.err);
        return null;
    } catch (CertificateException e) {
        //e.printStackTrace(System.err);
        return null;
    } catch (UnrecoverableKeyException e) {
        //e.printStackTrace(System.err);
        return null;
    } catch (OperatorCreationException e) {
        //e.printStackTrace(System.err);
        return null;
    } catch (Exception e) {
        //e.printStackTrace(System.err);
        return null;
    } finally {
        IOUtils.closeQuietly(outStr);
        IOUtils.closeQuietly(inStr);
    }
    return pkcs7File;
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) ArrayList(java.util.ArrayList) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) Store(org.bouncycastle.util.Store) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) CMSTypedData(org.bouncycastle.cms.CMSTypedData) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CMSException(org.bouncycastle.cms.CMSException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchProviderException(java.security.NoSuchProviderException) CertificateEncodingException(java.security.cert.CertificateEncodingException) FileOutputStream(java.io.FileOutputStream) NoSuchProviderException(java.security.NoSuchProviderException) File(java.io.File) CMSException(org.bouncycastle.cms.CMSException)

Example 70 with UnrecoverableKeyException

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

the class LockSettingsService method resetKeyStore.

@Override
public void resetKeyStore(int userId) throws RemoteException {
    checkWritePermission(userId);
    if (DEBUG)
        Slog.v(TAG, "Reset keystore for user: " + userId);
    int managedUserId = -1;
    String managedUserDecryptedPassword = null;
    final List<UserInfo> profiles = mUserManager.getProfiles(userId);
    for (UserInfo pi : profiles) {
        // Unlock managed profile with unified lock
        if (pi.isManagedProfile() && !mLockPatternUtils.isSeparateProfileChallengeEnabled(pi.id) && mStorage.hasChildProfileLock(pi.id)) {
            try {
                if (managedUserId == -1) {
                    managedUserDecryptedPassword = getDecryptedPasswordForTiedProfile(pi.id);
                    managedUserId = pi.id;
                } else {
                    // Should not happen
                    Slog.e(TAG, "More than one managed profile, uid1:" + managedUserId + ", uid2:" + pi.id);
                }
            } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
                Slog.e(TAG, "Failed to decrypt child profile key", e);
            }
        }
    }
    try {
        // Clear all the users credentials could have been installed in for this user.
        for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
            for (int uid : SYSTEM_CREDENTIAL_UIDS) {
                mKeyStore.clearUid(UserHandle.getUid(profileId, uid));
            }
        }
    } finally {
        if (managedUserId != -1 && managedUserDecryptedPassword != null) {
            if (DEBUG)
                Slog.v(TAG, "Restore tied profile lock");
            tieProfileLockToParent(managedUserId, managedUserDecryptedPassword);
        }
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) UserInfo(android.content.pm.UserInfo) 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)

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