use of java.security.cert.CertificateExpiredException in project santuario-java by apache.
the class CertsInFilesystemDirectoryResolver method readCertsFromHarddrive.
/**
* Method readCertsFromHarddrive
*
* @throws StorageResolverException
*/
private void readCertsFromHarddrive() throws StorageResolverException {
File certDir = new File(this.merlinsCertificatesDir);
List<String> al = new ArrayList<>();
String[] names = certDir.list();
if (names != null) {
for (int i = 0; i < names.length; i++) {
String currentFileName = names[i];
if (currentFileName.endsWith(".crt")) {
al.add(names[i]);
}
}
}
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException ex) {
throw new StorageResolverException(ex);
}
for (int i = 0; i < al.size(); i++) {
String filename = certDir.getAbsolutePath() + File.separator + al.get(i);
boolean added = false;
String dn = null;
try (InputStream inputStream = Files.newInputStream(Paths.get(filename))) {
X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
// add to ArrayList
cert.checkValidity();
this.certs.add(cert);
dn = cert.getSubjectX500Principal().getName();
added = true;
} catch (FileNotFoundException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not add certificate from file " + filename, ex);
}
} catch (CertificateNotYetValidException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not add certificate from file " + filename, ex);
}
} catch (CertificateExpiredException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not add certificate from file " + filename, ex);
}
} catch (CertificateException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not add certificate from file " + filename, ex);
}
} catch (IOException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not add certificate from file " + filename, ex);
}
}
if (added) {
LOG.debug("Added certificate: {}", dn);
}
}
}
use of java.security.cert.CertificateExpiredException in project i2p.i2p by i2p.
the class KeyStoreUtil method addCert.
/**
* Load an X509 Cert from a file and add it to the
* trusted set of certificates in the key store
*
* This DOES check for revocation, IF cs is non-null.
*
* @param cs may be null; if non-null, check for revocation
* @return success
* @since 0.9.25
*/
public static boolean addCert(File file, String alias, KeyStore ks, CertStore cs) {
try {
X509Certificate cert = CertUtil.loadCert(file);
info("Read X509 Certificate from " + file.getAbsolutePath() + " Issuer: " + cert.getIssuerX500Principal() + " Serial: " + cert.getSerialNumber().toString(16) + "; Valid From: " + cert.getNotBefore() + " To: " + cert.getNotAfter());
if (cs != null && CertUtil.isRevoked(cs, cert)) {
error("Certificate is revoked: " + file, new Exception());
return false;
}
ks.setCertificateEntry(alias, cert);
info("Now trusting X509 Certificate, Issuer: " + cert.getIssuerX500Principal());
} catch (CertificateExpiredException cee) {
String s = "Rejecting expired X509 Certificate: " + file.getAbsolutePath();
// Android often has old system certs
// our SSL certs may be old also
// if (SystemVersion.isAndroid())
warn(s, cee);
// error(s, cee);
return false;
} catch (CertificateNotYetValidException cnyve) {
error("Rejecting X509 Certificate not yet valid: " + file.getAbsolutePath(), cnyve);
return false;
} catch (GeneralSecurityException gse) {
error("Error reading X509 Certificate: " + file.getAbsolutePath(), gse);
return false;
} catch (IOException ioe) {
error("Error reading X509 Certificate: " + file.getAbsolutePath(), ioe);
return false;
}
return true;
}
use of java.security.cert.CertificateExpiredException in project i2p.i2p by i2p.
the class KeyStoreUtil method logCertExpiration.
/**
* Validate expiration for all private key certs in a key store.
* Use this for keystores containing selfsigned certs where the
* user will be expected to renew an expiring cert.
* Use this for keystores we are feeding to an SSLContext and ServerSocketFactory.
*
* We added support for self-signed certs in 0.8.3 2011-01, with a 10-year expiration.
* We still don't generate them by default. We don't expect anybody's
* certs to expire until 2021.
*
* @param location the path or other identifying info, for logging only
* @param expiresWithin ms if cert expires within this long, we will log a warning, e.g. 180*24*60*60*1000L
* @return true if all are good, false if we logged something
* @since 0.9.34
*/
public static boolean logCertExpiration(KeyStore ks, String location, long expiresWithin) {
boolean rv = true;
try {
int count = 0;
for (Enumeration<String> e = ks.aliases(); e.hasMoreElements(); ) {
String alias = e.nextElement();
if (ks.isKeyEntry(alias)) {
Certificate[] cs;
try {
cs = ks.getCertificateChain(alias);
} catch (KeyStoreException kse) {
error("Unable to check certificates for \"" + alias + "\" in key store " + location, kse);
rv = false;
continue;
}
for (Certificate c : cs) {
if (c != null && (c instanceof X509Certificate)) {
count++;
X509Certificate cert = (X509Certificate) c;
try {
// System.out.println("checking " + alias + " in " + location);
cert.checkValidity();
long expiresIn = cert.getNotAfter().getTime() - System.currentTimeMillis();
// System.out.println("expiration of " + alias + " is in " + DataHelper.formatDuration(expiresIn));
if (expiresIn < expiresWithin) {
Log l = I2PAppContext.getGlobalContext().logManager().getLog(KeyStoreUtil.class);
String subj = cert.getIssuerX500Principal().toString();
l.logAlways(Log.WARN, "Certificate \"" + subj + "\" in key store " + location + " will expire in " + DataHelper.formatDuration2(expiresIn).replace(" ", " ") + "\nYou should renew the certificate soon." + // TODO better help or tools, or autorenew
"\nFor a local self-signed certificate, you may delete the keystore and restart," + " or ask for help on how to renew.");
}
} catch (CertificateExpiredException cee) {
String subj = cert.getIssuerX500Principal().toString();
error("Expired certificate \"" + subj + "\" in key store " + location + "\nYou must renew the certificate." + // TODO better help or tools, or autorenew
"\nFor a local self-signed certificate, you may simply delete the keystore and restart," + "\nor ask for help on how to renew.", null);
rv = false;
} catch (CertificateNotYetValidException cnyve) {
String subj = cert.getIssuerX500Principal().toString();
error("Not yet valid certificate \"" + subj + "\" in key store " + location, null);
rv = false;
}
}
}
}
}
if (count == 0)
error("No certificates found in key store " + location, null);
} catch (GeneralSecurityException e) {
error("Unable to check certificates in key store " + location, e);
rv = false;
}
return rv;
}
use of java.security.cert.CertificateExpiredException in project nifi-registry by apache.
the class X509IdentityProvider method authenticate.
/**
* For a given {@link AuthenticationRequest}, this validates the client certificate and creates a populated {@link AuthenticationResponse}.
*
* The {@link AuthenticationRequest} authenticationRequest paramenter is expected to be populated as:
* - username: principal DN from first client cert
* - credentials: first client certificate (X509Certificate)
* - details: proxied-entities chain (String)
*
* @param authenticationRequest the request, containing identity claim credentials for the IdentityProvider to authenticate and determine an identity
*/
@Override
public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) throws InvalidCredentialsException {
if (authenticationRequest == null || authenticationRequest.getUsername() == null) {
return null;
}
String principal = authenticationRequest.getUsername();
try {
X509Certificate clientCertificate = (X509Certificate) authenticationRequest.getCredentials();
validateClientCertificate(clientCertificate);
} catch (CertificateExpiredException cee) {
final String message = String.format("Client certificate for (%s) is expired.", principal);
logger.warn(message, cee);
throw new InvalidCredentialsException(message, cee);
} catch (CertificateNotYetValidException cnyve) {
final String message = String.format("Client certificate for (%s) is not yet valid.", principal);
logger.warn(message, cnyve);
throw new InvalidCredentialsException(message, cnyve);
} catch (final Exception e) {
logger.warn(e.getMessage(), e);
}
// build the authentication response
return new AuthenticationResponse(principal, principal, expiration, issuer);
}
use of java.security.cert.CertificateExpiredException in project AppCenter-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, false);
assertEquals("anything", decryptedData.getDecryptedData());
assertNull(decryptedData.getNewEncryptedData());
decryptedData = cryptoUtils.decrypt(encrypted, true);
assertEquals("anything", decryptedData.getDecryptedData());
assertNull(decryptedData.getNewEncryptedData());
/* Test old data encryption upgrade. */
CryptoUtils.DecryptedData oldDecryptedData = cryptoUtils.decrypt("None:oldData", false);
assertEquals("oldData", oldDecryptedData.getDecryptedData());
assertEquals(CIPHER_RSA + "/" + RSA_KEY_SIZE + ALGORITHM_DATA_SEPARATOR + "oldData", oldDecryptedData.getNewEncryptedData());
oldDecryptedData = cryptoUtils.decrypt("None:oldData", true);
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, false);
assertEquals("anything", decryptedData.getDecryptedData());
assertNull(decryptedData.getNewEncryptedData());
decryptedData = cryptoUtils.decrypt(encrypted, true);
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);
}
Aggregations