Search in sources :

Example 16 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project mobile-center-sdk-android by Microsoft.

the class CryptoTest method verifyRsaPreferred.

private void verifyRsaPreferred(int apiLevel) throws Exception {
    CryptoUtils cryptoUtils = new CryptoUtils(mContext, mCryptoFactory, apiLevel);
    String encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    CryptoUtils.DecryptedData decryptedData = cryptoUtils.decrypt(encrypted);
    assertEquals("anything", decryptedData.getDecryptedData());
    assertNull(decryptedData.getNewEncryptedData());
    decryptedData = cryptoUtils.decrypt(encrypted);
    assertEquals("anything", decryptedData.getDecryptedData());
    assertNull(decryptedData.getNewEncryptedData());
    /* Test old data encryption upgrade. */
    CryptoUtils.DecryptedData oldDecryptedData = cryptoUtils.decrypt("None:oldData");
    assertEquals("oldData", oldDecryptedData.getDecryptedData());
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "oldData", oldDecryptedData.getNewEncryptedData());
    oldDecryptedData = cryptoUtils.decrypt("None:oldData");
    assertEquals("oldData", oldDecryptedData.getDecryptedData());
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "oldData", oldDecryptedData.getNewEncryptedData());
    /* Check we can still read data after expiration. */
    doThrow(new CertificateExpiredException()).doNothing().when(mRsaCert).checkValidity();
    decryptedData = cryptoUtils.decrypt(encrypted);
    assertEquals("anything", decryptedData.getDecryptedData());
    assertNull(decryptedData.getNewEncryptedData());
    decryptedData = cryptoUtils.decrypt(encrypted);
    assertEquals("anything", decryptedData.getDecryptedData());
    assertNull(decryptedData.getNewEncryptedData());
    /* But encrypt will use another cert. */
    encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    /* Verify another cert was created. */
    ArgumentCaptor<String> alias = ArgumentCaptor.forClass(String.class);
    verify(mRsaBuilder, times(2)).setAlias(alias.capture());
    String alias0 = alias.getAllValues().get(0);
    String alias1 = alias.getAllValues().get(1);
    assertNotEquals(alias0, alias1);
    verify(mKeyStore).getEntry(alias1, null);
    /* Count how many times alias0 was used to test interactions after more easily... */
    alias = ArgumentCaptor.forClass(String.class);
    verify(mKeyStore, atLeastOnce()).getEntry(alias.capture(), any(KeyStore.ProtectionParameter.class));
    int alias0count = 0;
    for (String aliasValue : alias.getAllValues()) {
        if (aliasValue.equals(alias0)) {
            alias0count++;
        }
    }
    /* If we restart crypto utils it must pick up the second cert. */
    when(mKeyStore.containsAlias(alias0)).thenReturn(true);
    when(mKeyStore.containsAlias(alias1)).thenReturn(true);
    Calendar calendar = Calendar.getInstance();
    when(mKeyStore.getCreationDate(alias0)).thenReturn(calendar.getTime());
    calendar.add(Calendar.YEAR, 1);
    when(mKeyStore.getCreationDate(alias1)).thenReturn(calendar.getTime());
    cryptoUtils = new CryptoUtils(mContext, mCryptoFactory, apiLevel);
    encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    /* Check alias0 no more used and that we used second alias to encrypt that value. */
    verify(mKeyStore, times(alias0count)).getEntry(alias0, null);
    verify(mKeyStore, times(2)).getEntry(alias1, null);
    /* Roll over a second time. */
    doThrow(new CertificateExpiredException()).doNothing().when(mRsaCert).checkValidity();
    encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    /* Verify another cert was created with reusing first alias name, deleting old one. */
    alias = ArgumentCaptor.forClass(String.class);
    verify(mRsaBuilder, times(3)).setAlias(alias.capture());
    assertNotEquals(alias0, alias1);
    assertEquals(alias0, alias.getAllValues().get(2));
    verify(mKeyStore).deleteEntry(alias0);
    verify(mKeyStore, times(alias0count + 1)).getEntry(alias0, null);
    verify(mKeyStore, times(3)).getEntry(alias1, null);
    /* Check that it will reload alias0 again after restart. */
    calendar.add(Calendar.YEAR, 1);
    when(mKeyStore.getCreationDate(alias0)).thenReturn(calendar.getTime());
    cryptoUtils = new CryptoUtils(mContext, mCryptoFactory, apiLevel);
    encrypted = cryptoUtils.encrypt("anything");
    assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "anything", encrypted);
    verify(mKeyStore, times(alias0count + 2)).getEntry(alias0, null);
    verify(mKeyStore, times(3)).getEntry(alias1, null);
}
Also used : CertificateExpiredException(java.security.cert.CertificateExpiredException) Calendar(java.util.Calendar) Matchers.anyString(org.mockito.Matchers.anyString) SuppressLint(android.annotation.SuppressLint)

Example 17 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project mobile-center-sdk-android by Microsoft.

the class CryptoTest method readExpiredDataOnBeforeAndroidM.

@Test
public void readExpiredDataOnBeforeAndroidM() throws Exception {
    /* Encrypt test data. */
    CryptoUtils cryptoUtils = new CryptoUtils(mContext, mCryptoFactory, Build.VERSION_CODES.LOLLIPOP);
    String data = "oldData";
    String encryptedData = cryptoUtils.encrypt(data);
    /* Make key rotate on next encryption. */
    when(mCipher.doFinal(any(byte[].class))).thenThrow(new InvalidKeyException(new CertificateExpiredException())).thenAnswer(new Answer<byte[]>() {

        @Override
        public byte[] answer(InvocationOnMock invocation) {
            return (byte[]) invocation.getArguments()[0];
        }
    });
    cryptoUtils.encrypt("otherData");
    /*
         * Make decrypt fail with current key and work with expired key (i.e. the second call).
         */
    when(mCipher.doFinal(any(byte[].class))).thenThrow(new BadPaddingException()).thenAnswer(new Answer<byte[]>() {

        @Override
        public byte[] answer(InvocationOnMock invocation) {
            return (byte[]) invocation.getArguments()[0];
        }
    });
    int expectedKeyStoreCalls = 3;
    verify(mKeyStore, times(expectedKeyStoreCalls)).getEntry(notNull(String.class), isNull(KeyStore.ProtectionParameter.class));
    /* Verify we can decrypt with retry on expired key. */
    CryptoUtils.DecryptedData decryptedData = cryptoUtils.decrypt(encryptedData);
    assertEquals(data, decryptedData.getDecryptedData());
    assertNull(decryptedData.getNewEncryptedData());
    /* Verify the second alias was picked for decryption. */
    expectedKeyStoreCalls += 2;
    ArgumentCaptor<String> aliasCaptor = ArgumentCaptor.forClass(String.class);
    verify(mKeyStore, times(expectedKeyStoreCalls)).getEntry(aliasCaptor.capture(), isNull(KeyStore.ProtectionParameter.class));
    List<String> aliases = aliasCaptor.getAllValues();
    /* Check last calls: first we tried to read with the second alias (after rotation). */
    assertTrue(aliases.get(3).startsWith("appcenter.1."));
    /* Then we tried with the old one. */
    assertTrue(aliases.get(4).startsWith("appcenter.0."));
}
Also used : CertificateExpiredException(java.security.cert.CertificateExpiredException) Matchers.anyString(org.mockito.Matchers.anyString) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SuppressLint(android.annotation.SuppressLint) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 18 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project zm-mailbox by Zimbra.

the class ClientCertAuthenticator method validateClientCert.

private void validateClientCert(X509Certificate[] certs) throws ServiceException {
    String subjectDN = null;
    try {
        boolean revocationCheckEnabled = Provisioning.getInstance().getLocalServer().isMailSSLClientCertOCSPEnabled();
        Set<TrustAnchor> trustedCertsSet = null;
        if (revocationCheckEnabled) {
            char[] pass = LC.client_ssl_truststore_password.value().toCharArray();
            trustedCertsSet = CertValidationUtil.loadTrustedAnchors(pass, LC.client_ssl_truststore.value());
        }
        for (X509Certificate cert : certs) {
            subjectDN = getSubjectDNForLogging(cert);
            CertValidationUtil.validateCertificate(cert, revocationCheckEnabled, trustedCertsSet);
        }
    } catch (CertificateExpiredException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "client certificate expired", e);
    } catch (CertificateNotYetValidException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "client certificate not yet valid", e);
    } catch (CertificateException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "can't generate certpath for client certificate", e);
    } catch (KeyStoreException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received KeyStoreException while loading KeyStore", e);
    } catch (NoSuchAlgorithmException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received NoSuchAlgorithmException while obtaining instance of certpath validator", e);
    } catch (FileNotFoundException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "mailboxd keystore can't be found", e);
    } catch (IOException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received IOException", e);
    } catch (InvalidAlgorithmParameterException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received InvalidAlgorithmParameter while obtaining instance of certpath validator", e);
    } catch (CertPathValidatorException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received CertPathValidatorException" + e.getMessage(), e);
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CertificateExpiredException(java.security.cert.CertificateExpiredException) FileNotFoundException(java.io.FileNotFoundException) TrustAnchor(java.security.cert.TrustAnchor) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException)

Example 19 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project CzechIdMng by bcvsolutions.

the class CertificateUtils method verifyCertificate.

/**
 * Check if is given certificate signed with the given certificate authority.
 * Does not supports check via certificate chain. Does not supports CRL check.
 *
 * @param certificate
 * @param authority
 * @throws CertificateException
 */
public static void verifyCertificate(X509Certificate certificate, X509Certificate authority) throws CertificateException {
    Assert.notNull(certificate, "Certificate cannot be null!");
    Assert.notNull(authority, "Authority cannot be null!");
    // Check if certificate send is your CA's
    if (!authority.equals(certificate)) {
        // verifyCertificate(certificate, Sets.newHashSet(authority));
        try {
            // Not your CA's. Check if it has been signed by your CA
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            CertPath cp = cf.generateCertPath(Lists.newArrayList(certificate));
            TrustAnchor anchor = new TrustAnchor((X509Certificate) authority, null);
            PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
            params.setRevocationEnabled(false);
            CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
            cpv.validate(cp, params);
        } catch (CertPathValidatorException ex) {
            if (ex.getCause() instanceof CertificateExpiredException) {
                throw (CertificateExpiredException) ex.getCause();
            }
            throw new CertificateException("Certificate not trusted", ex);
        } catch (Exception ex) {
            throw new CertificateException("Certificate not trusted", ex);
        }
    }
}
Also used : CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertificateExpiredException(java.security.cert.CertificateExpiredException) PKIXParameters(java.security.cert.PKIXParameters) TrustAnchor(java.security.cert.TrustAnchor) CertificateException(java.security.cert.CertificateException) CertPath(java.security.cert.CertPath) CertificateFactory(java.security.cert.CertificateFactory) CertificateExpiredException(java.security.cert.CertificateExpiredException) CertPathValidatorException(java.security.cert.CertPathValidatorException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 20 with CertificateExpiredException

use of java.security.cert.CertificateExpiredException in project Payara by payara.

the class RemoveExpiredCertsCommand method filterExpiredKeys.

private void filterExpiredKeys(KeyStore store) throws KeyStoreException {
    logger.log(Level.INFO, "Removing expired keys.");
    int removedKeys = 0;
    // Count through all aliases
    Enumeration<String> aliases = store.aliases();
    while (aliases.hasMoreElements()) {
        // Get the certificate and alias
        String alias = aliases.nextElement();
        Certificate cert = store.getCertificate(alias);
        // If the certificate is an X509 certificate
        if (cert.getType().equals("X.509")) {
            X509Certificate xCert = (X509Certificate) cert;
            String expiryDate = new SimpleDateFormat("dd/MM/yyyy").format(xCert.getNotAfter());
            logger.log(Level.FINE, "Checking certificate {0} (expires {1}).", new Object[] { alias, expiryDate });
            // Check the certificate validity, and remove it if it's expired.
            try {
                xCert.checkValidity();
            } catch (CertificateExpiredException | CertificateNotYetValidException e) {
                store.deleteEntry(alias);
                logger.log(Level.INFO, "Removed certificate {0} (expired {1}).", new Object[] { alias, expiryDate });
                removedKeys++;
            }
        }
    }
    logger.log(Level.INFO, "Successfully removed {0} expired keys out of a total {1}.", new Object[] { removedKeys, store.size() });
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) SimpleDateFormat(java.text.SimpleDateFormat) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

CertificateExpiredException (java.security.cert.CertificateExpiredException)46 X509Certificate (java.security.cert.X509Certificate)32 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)28 CertificateException (java.security.cert.CertificateException)15 ArrayList (java.util.ArrayList)7 GeneralSecurityException (java.security.GeneralSecurityException)6 InvalidKeyException (java.security.InvalidKeyException)6 KeyStore (java.security.KeyStore)6 Certificate (java.security.cert.Certificate)6 IOException (java.io.IOException)5 KeyStoreException (java.security.KeyStoreException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Date (java.util.Date)5 SuppressLint (android.annotation.SuppressLint)4 Principal (java.security.Principal)4 Calendar (java.util.Calendar)4 Test (org.junit.Test)4 FileNotFoundException (java.io.FileNotFoundException)3 CertificateFactory (java.security.cert.CertificateFactory)3 X509TrustManager (javax.net.ssl.X509TrustManager)3