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);
}
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."));
}
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);
}
}
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);
}
}
}
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() });
}
Aggregations