Search in sources :

Example 36 with KeyStoreException

use of java.security.KeyStoreException in project OpenAM by OpenRock.

the class AuthenticatorOathService method getEncryptionKeyPair.

private KeyPair getEncryptionKeyPair() {
    try {
        final KeyStore keyStore = new KeyStoreBuilder().withKeyStoreFile(new File(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_FILE))).withPassword(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_PASSWORD)).withKeyStoreType(KeyStoreType.valueOf(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_TYPE))).build();
        final Certificate cert = keyStore.getCertificate(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_KEYPAIR_ALIAS));
        final PublicKey publicKey = cert.getPublicKey();
        final PrivateKey privateKey = (PrivateKey) keyStore.getKey(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_KEYPAIR_ALIAS), CollectionHelper.getMapAttr(options, OATH_KEYSTORE_PRIVATEKEY_PASSWORD).toCharArray());
        return new KeyPair(publicKey, privateKey);
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException("Invalid keystore location specified", e);
    } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException e) {
        debug.error("AuthenticatorOathService.getEncryptionKeyPair(): Unable to load encryption key pair", e);
        throw new IllegalStateException(e);
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) FileNotFoundException(java.io.FileNotFoundException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreBuilder(org.forgerock.openam.shared.security.crypto.KeyStoreBuilder) KeyStore(java.security.KeyStore) UnrecoverableKeyException(java.security.UnrecoverableKeyException) File(java.io.File) Certificate(java.security.cert.Certificate)

Example 37 with KeyStoreException

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

the class X509KeySelector method select.

/**
     * Finds a key from the keystore satisfying the specified constraints.
     *
     * <p>This method compares data contained in {@link KeyInfo} entries
     * with information stored in the <code>KeyStore</code>. The implementation
     * iterates over the KeyInfo types and returns the first {@link PublicKey}
     * of an X509Certificate in the keystore that is compatible with the
     * specified AlgorithmMethod according to the following rules for each
     * keyinfo type:
     *
     * X509Data X509Certificate: if it contains a <code>KeyUsage</code>
     *   extension that asserts the <code>digitalSignature</code> bit and
     *   matches an <code>X509Certificate</code> in the <code>KeyStore</code>.
     * X509Data X509IssuerSerial: if the serial number and issuer DN match an
     *    <code>X509Certificate</code> in the <code>KeyStore</code>.
     * X509Data X509SubjectName: if the subject DN matches an
     *    <code>X509Certificate</code> in the <code>KeyStore</code>.
     * X509Data X509SKI: if the subject key identifier matches an
     *    <code>X509Certificate</code> in the <code>KeyStore</code>.
     * KeyName: if the keyname matches an alias in the <code>KeyStore</code>.
     * RetrievalMethod: supports rawX509Certificate and X509Data types. If
     *    rawX509Certificate type, it must match an <code>X509Certificate</code>
     *    in the <code>KeyStore</code>.
     *
     * @param keyInfo a <code>KeyInfo</code> (may be <code>null</code>)
     * @param purpose the key's purpose
     * @param method the algorithm method that this key is to be used for.
     *    Only keys that are compatible with the algorithm and meet the
     *    constraints of the specified algorithm should be returned.
     * @param an <code>XMLCryptoContext</code> that may contain additional
     *    useful information for finding an appropriate key
     * @return a key selector result
     * @throws KeySelectorException if an exceptional condition occurs while
     *    attempting to find a key. Note that an inability to find a key is not
     *    considered an exception (<code>null</code> should be
     *    returned in that case). However, an error condition (ex: network
     *    communications failure) that prevented the <code>KeySelector</code>
     *    from finding a potential key should be considered an exception.
     * @throws ClassCastException if the data type of <code>method</code>
     *    is not supported by this key selector
     */
public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException {
    SignatureMethod sm = (SignatureMethod) method;
    try {
        // return null if keyinfo is null or keystore is empty
        if (keyInfo == null || ks.size() == 0) {
            return new SimpleKeySelectorResult(null);
        }
        // Iterate through KeyInfo types
        Iterator i = keyInfo.getContent().iterator();
        while (i.hasNext()) {
            XMLStructure kiType = (XMLStructure) i.next();
            // check X509Data
            if (kiType instanceof X509Data) {
                X509Data xd = (X509Data) kiType;
                KeySelectorResult ksr = x509DataSelect(xd, sm);
                if (ksr != null) {
                    return ksr;
                }
            // check KeyName
            } else if (kiType instanceof KeyName) {
                KeyName kn = (KeyName) kiType;
                Certificate cert = ks.getCertificate(kn.getName());
                if (cert != null && algEquals(sm.getAlgorithm(), cert.getPublicKey().getAlgorithm())) {
                    return new SimpleKeySelectorResult(cert.getPublicKey());
                }
            // check RetrievalMethod
            } else if (kiType instanceof RetrievalMethod) {
                RetrievalMethod rm = (RetrievalMethod) kiType;
                try {
                    KeySelectorResult ksr = null;
                    if (rm.getType().equals(X509Data.RAW_X509_CERTIFICATE_TYPE)) {
                        OctetStreamData data = (OctetStreamData) rm.dereference(context);
                        CertificateFactory cf = CertificateFactory.getInstance("X.509");
                        X509Certificate cert = (X509Certificate) cf.generateCertificate(data.getOctetStream());
                        ksr = certSelect(cert, sm);
                    } else if (rm.getType().equals(X509Data.TYPE)) {
                        X509Data xd = (X509Data) ((DOMRetrievalMethod) rm).dereferenceAsXMLStructure(context);
                        ksr = x509DataSelect(xd, sm);
                    } else {
                        // skip; keyinfo type is not supported
                        continue;
                    }
                    if (ksr != null) {
                        return ksr;
                    }
                } catch (Exception e) {
                    throw new KeySelectorException(e);
                }
            }
        }
    } catch (KeyStoreException kse) {
        // throw exception if keystore is uninitialized
        throw new KeySelectorException(kse);
    }
    // return null since no match could be found
    return new SimpleKeySelectorResult(null);
}
Also used : DOMRetrievalMethod(org.jcp.xml.dsig.internal.dom.DOMRetrievalMethod) KeyStoreException(java.security.KeyStoreException) CertificateFactory(java.security.cert.CertificateFactory) DOMRetrievalMethod(org.jcp.xml.dsig.internal.dom.DOMRetrievalMethod) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 38 with KeyStoreException

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

the class LockSettingsService method verifyTiedProfileChallenge.

@Override
public VerifyCredentialResponse verifyTiedProfileChallenge(String password, boolean isPattern, long challenge, int userId) throws RemoteException {
    checkPasswordReadPermission(userId);
    if (!isManagedProfileWithUnifiedLock(userId)) {
        throw new RemoteException("User id must be managed profile with unified lock");
    }
    final int parentProfileId = mUserManager.getProfileParent(userId).id;
    // Unlock parent by using parent's challenge
    final VerifyCredentialResponse parentResponse = isPattern ? doVerifyPattern(password, true, challenge, parentProfileId, null) : doVerifyPassword(password, true, challenge, parentProfileId, null);
    if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
        // Failed, just return parent's response
        return parentResponse;
    }
    try {
        // Unlock work profile, and work profile with unified lock must use password only
        return doVerifyPassword(getDecryptedPasswordForTiedProfile(userId), true, challenge, userId, null);
    } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
        Slog.e(TAG, "Failed to decrypt child profile key", e);
        throw new RemoteException("Unable to get tied profile token");
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) VerifyCredentialResponse(com.android.internal.widget.VerifyCredentialResponse) 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)

Example 39 with KeyStoreException

use of java.security.KeyStoreException in project LolliPin by OrangeGangsters.

the class FingerprintUiHelper method initCipher.

/**
     * Initialize the {@link Cipher} instance with the created key in the {@link #createKey()}
     * method.
     *
     * @return {@code true} if initialization is successful, {@code false} if the lock screen has
     * been disabled or reset after the key was generated, or if a fingerprint got enrolled after
     * the key was generated.
     */
private boolean initCipher() {
    try {
        if (mKeyStore == null) {
            mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        }
        createKey();
        mKeyStore.load(null);
        SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null);
        mCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        mCipher.init(Cipher.ENCRYPT_MODE, key);
        return true;
    } catch (NoSuchPaddingException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
        return false;
    }
}
Also used : SecretKey(javax.crypto.SecretKey) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 40 with KeyStoreException

use of java.security.KeyStoreException in project android_frameworks_base by AOSPA.

the class AndroidKeyStoreTest method testKeyStore_SetKeyEntry_ProtectedKey_Encrypted_Failure.

public void testKeyStore_SetKeyEntry_ProtectedKey_Encrypted_Failure() throws Exception {
    setupPassword();
    mKeyStore.load(null, null);
    final CertificateFactory f = CertificateFactory.getInstance("X.509");
    final Certificate caCert = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_CA_1));
    KeyFactory keyFact = KeyFactory.getInstance("RSA");
    PrivateKey privKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_RSA_KEY_1));
    final Certificate[] chain = new Certificate[2];
    chain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_USER_1));
    chain[1] = caCert;
    try {
        mKeyStore.setKeyEntry(TEST_ALIAS_1, privKey, "foo".toCharArray(), chain);
        fail("Should fail when a password is specified");
    } catch (KeyStoreException success) {
    }
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyStoreException(java.security.KeyStoreException) CertificateFactory(java.security.cert.CertificateFactory) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

KeyStoreException (java.security.KeyStoreException)797 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)506 IOException (java.io.IOException)409 KeyStore (java.security.KeyStore)359 CertificateException (java.security.cert.CertificateException)353 UnrecoverableKeyException (java.security.UnrecoverableKeyException)194 X509Certificate (java.security.cert.X509Certificate)189 KeyManagementException (java.security.KeyManagementException)172 Certificate (java.security.cert.Certificate)132 InputStream (java.io.InputStream)103 SSLContext (javax.net.ssl.SSLContext)103 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)95 FileInputStream (java.io.FileInputStream)94 File (java.io.File)80 PrivateKey (java.security.PrivateKey)71 TrustManager (javax.net.ssl.TrustManager)70 FileNotFoundException (java.io.FileNotFoundException)61 ByteArrayInputStream (java.io.ByteArrayInputStream)58 CertificateFactory (java.security.cert.CertificateFactory)58 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)53